<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");

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

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

$role = trim($_GET["role"] ?? "validator");
$sppgId = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;
$sekolahId = isset($_GET["sekolah_id"]) ? (int) $_GET["sekolah_id"] : 0;
$status = trim($_GET["status"] ?? "menunggu_validasi");
$tanggal = trim($_GET["tanggal"] ?? "");
$search = trim($_GET["search"] ?? "");
$kategori = trim($_GET["kategori"] ?? "");

$where = [];
$params = [];
$types = "";

if ($status !== "" && $status !== "semua") {
    $where[] = "mh.status = ?";
    $params[] = $status;
    $types .= "s";
}

if ($tanggal !== "") {
    $where[] = "mh.tanggal = ?";
    $params[] = $tanggal;
    $types .= "s";
}

if ($kategori !== "" && $kategori !== "semua") {
    $where[] = "mh.kategori = ?";
    $params[] = $kategori;
    $types .= "s";
}

if ($role === "sppg" && $sppgId > 0) {
    $where[] = "mh.sppg_id = ?";
    $params[] = $sppgId;
    $types .= "i";
}

if (($role === "validator" || $role === "sekolah") && $sekolahId > 0) {
    $where[] = "mh.sekolah_id = ?";
    $params[] = $sekolahId;
    $types .= "i";
}

if ($search !== "") {
    $where[] = "(
        COALESCE(s.nama, '') LIKE ?
        OR COALESCE(sk.nama_sekolah, '') LIKE ?
        OR COALESCE(mh.catatan, '') LIKE ?
        OR COALESCE(mh.lokasi, '') LIKE ?
        OR COALESCE(mh.kategori, '') LIKE ?
    )";

    $like = "%{$search}%";

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;

    $types .= "sssss";
}

$sql = "
SELECT
  mh.id,
  mh.sppg_id,
  mh.tanggal,
  mh.hari,
  mh.kategori,
  mh.nama_menu,
  mh.deskripsi,
  mh.dana_per_porsi,
  mh.gambar_url,
  mh.created_at,
  mh.waktu,
  mh.lokasi,
  mh.status,
  mh.catatan,
  mh.dana_total,
  mh.dana_per_omprengan,
  mh.total_bahan,
  mh.foto_bahan_url,
  mh.foto_makanan_url,
  mh.sekolah_id,
  mh.jumlah_omprengan,

  s.nama AS nama_sppg,
  s.provinsi,
  s.kabupaten,

  sk.nama_sekolah,
  sk.jenjang,
  sk.jumlah_siswa,
  sk.alamat AS alamat_sekolah
FROM menu_harian mh
LEFT JOIN sppg s ON s.id = mh.sppg_id
LEFT JOIN sekolah sk ON sk.id = mh.sekolah_id
";

if (count($where) > 0) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY mh.id DESC LIMIT 200";

$stmt = $conn->prepare($sql);

if (!$stmt) {
    response(false, "Query validasi laporan gagal disiapkan: " . $conn->error, [
        "sql" => $sql
    ]);
}

if (count($params) > 0) {
    $stmt->bind_param($types, ...$params);
}

if (!$stmt->execute()) {
    response(false, "Query validasi laporan gagal dijalankan: " . $stmt->error, null);
}

$result = $stmt->get_result();
$data = [];

while ($row = $result->fetch_assoc()) {
    $menuId = (int) $row["id"];

    $items = [];
    $dana = [];

    $stmtItem = $conn->prepare("
        SELECT nama_item
        FROM menu_harian_item
        WHERE menu_id = ?
        ORDER BY id ASC
    ");

    if ($stmtItem) {
        $stmtItem->bind_param("i", $menuId);
        $stmtItem->execute();

        $resItem = $stmtItem->get_result();

        while ($item = $resItem->fetch_assoc()) {
            $items[] = $item["nama_item"];
        }
    }

    $stmtDana = $conn->prepare("
        SELECT label, nominal
        FROM menu_harian_dana
        WHERE menu_id = ?
        ORDER BY id ASC
    ");

    if ($stmtDana) {
        $stmtDana->bind_param("i", $menuId);
        $stmtDana->execute();

        $resDana = $stmtDana->get_result();

        while ($d = $resDana->fetch_assoc()) {
            $dana[] = [
                "label" => $d["label"],
                "nominal" => (int) $d["nominal"]
            ];
        }
    }

    if ($row["kategori"] === "Reguler" || $row["kategori"] === null || trim($row["kategori"]) === "") {
        $row["kategori"] = "Siswa";
    }

    $gambarUtama = $row["foto_makanan_url"] ?: ($row["gambar_url"] ?: null);

    $danaPerPorsi = (int) ($row["dana_per_porsi"] ?? 0);

    if ($danaPerPorsi <= 0) {
        $danaPerPorsi = (int) ($row["dana_per_omprengan"] ?? 0);
    }

    $row["id"] = $menuId;
    $row["sppg_id"] = $row["sppg_id"] !== null ? (int) $row["sppg_id"] : null;
    $row["sekolah_id"] = $row["sekolah_id"] !== null ? (int) $row["sekolah_id"] : null;

    $row["dana_per_porsi"] = $danaPerPorsi;
    $row["dana_total"] = (int) ($row["dana_total"] ?? 0);
    $row["dana_per_omprengan"] = (int) ($row["dana_per_omprengan"] ?? 0);
    $row["total_bahan"] = (int) ($row["total_bahan"] ?? 0);
    $row["jumlah_omprengan"] = (int) ($row["jumlah_omprengan"] ?? 0);
    $row["jumlah_siswa"] = (int) ($row["jumlah_siswa"] ?? 0);

    $row["gambar_utama"] = $gambarUtama;
    $row["menu_items"] = $items;
    $row["rincian_dana"] = $dana;

    $data[] = $row;
}

response(true, "Data laporan validasi berhasil diambil", [
    "total" => count($data),
    "items" => $data
]);
?>