<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";

$type = $_GET["type"] ?? "sppg";

$allowed = [
    "sppg" => "sppg",
    "sekolah" => "sekolah",
    "karyawan" => "karyawan",
    "bahan" => "bahan_makanan",
    "omprengan" => "omprengan",
    "laporan" => "laporan_operasional",
    "pengaduan" => "pengaduan",
    "audit" => "audit_log"
];

if (!array_key_exists($type, $allowed)) {
    header("Content-Type: application/json");
    echo json_encode([
        "success" => false,
        "message" => "Jenis backup tidak valid"
    ]);
    exit;
}

$table = $allowed[$type];

header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=backup_" . $type . "_" . date("Ymd_His") . ".csv");

$output = fopen("php://output", "w");

$sql = "SELECT * FROM $table ORDER BY id DESC";
$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    $firstRow = $result->fetch_assoc();

    fputcsv($output, array_keys($firstRow));
    fputcsv($output, $firstRow);

    while ($row = $result->fetch_assoc()) {
        fputcsv($output, $row);
    }
} else {
    fputcsv($output, ["message"]);
    fputcsv($output, ["Tidak ada data"]);
}

fclose($output);
$conn->close();

?>