<?php
// === CORS dan Headers ===
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');

// === Preflight CORS ===
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// === Konfigurasi upload ===
$target_dir = "uploads/";
$base_url = (isset($_SERVER['HTTPS']) ? ''http://localhost/Apipkl'' : 'http://localhost/apipkl') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/' . $target_dir;

// Buat folder jika belum ada
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

// === Fungsi respon JSON ===
function send_json($data) {
    echo json_encode($data);
    exit;
}

// === Handle GET: list semua file ===
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $files = [];

    foreach (scandir($target_dir) as $file) {
        if ($file !== '.' && $file !== '..') {
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array(strtolower($ext), ['pdf', 'jpg', 'jpeg', 'png', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'txt'])) {
                $files[] = [
                    "nama_file" => $file,
                    "url" => $base_url . $file,
                    "tanggal" => date("d-m-Y H:i:s", filemtime($target_dir . $file))
                ];
            }
        }
    }

    send_json(["success" => true, "data" => $files]);
}

// === Handle POST: upload file ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES["file"]) || $_FILES["file"]["error"] !== UPLOAD_ERR_OK) {
        send_json(["success" => false, "msg" => "❌ File tidak ditemukan atau gagal upload."]);
    }

    $file = $_FILES["file"];
    $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));

    // Validasi tipe file yang diperbolehkan
    $allowed_ext = ['pdf', 'jpg', 'jpeg', 'png', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'txt'];
    if (!in_array($ext, $allowed_ext)) {
        send_json([
            "success" => false,
            "msg" => "❌ Format file tidak diperbolehkan. Hanya: PDF, DOC(X), PPT(X), JPG, PNG, XLS(X), TXT."
        ]);
    }

    // Nama file baru yang unik
    $new_name = "laporan_" . time() . "_" . rand(100, 999) . "." . $ext;
    $target_file = $target_dir . $new_name;

    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        send_json([
            "success" => true,
            "msg" => "✅ File berhasil diunggah.",
            "file_url" => $base_url . $new_name,
            "filename" => $new_name
        ]);
    } else {
        send_json(["success" => false, "msg" => "❌ Gagal menyimpan file ke server."]);
    }
}

// === Fallback jika bukan GET atau POST
send_json(["success" => false, "msg" => "❌ Metode tidak didukung. Gunakan GET atau POST."]);
