<?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";

$sppgId = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;
$tanggal = $_GET["tanggal"] ?? date("Y-m-d");

if ($sppgId <= 0) {
    response(false, "ID SPPG tidak valid", null);
}

$data = [
    "menu_utama" => null,
    "menu_khusus" => [],
    "rincian_bahan" => [],
    "bahan" => [],
    "rincian_dana" => []
];

$sqlMenu = "
    SELECT
        id,
        sppg_id,
        tanggal,
        hari,
        kategori,
        nama_menu,
        deskripsi,

        dana_per_porsi,
        dana_per_omprengan,
        dana_total,
        total_bahan,
        jumlah_omprengan,

        gambar_url,
        foto_bahan_url,
        foto_makanan_url,

        lokasi,
        lokasi_mbg_tipe,
        sekolah_id,
        puskesmas_id,
        puskesmas_nama,
        puskesmas_daerah,

        kalori,
        protein,
        karbohidrat,
        lemak,
        serat,
        zat_besi,
        kalsium,
        vitamin,
        catatan_gizi,

        status,
        catatan,
        created_at
    FROM menu_harian
    WHERE sppg_id = ?
      AND tanggal = ?
    ORDER BY id DESC
    LIMIT 1
";

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

if (!$stmt) {
    response(false, "Query menu harian gagal disiapkan: " . $conn->error, null);
}

$stmt->bind_param("is", $sppgId, $tanggal);
$stmt->execute();

$result = $stmt->get_result();

if (!$result || $result->num_rows === 0) {
    response(false, "Data menu harian belum tersedia untuk tanggal ini", $data);
}

$menu = $result->fetch_assoc();

$menuId = (int) $menu["id"];

$menu["id"] = $menuId;
$menu["sppg_id"] = (int) $menu["sppg_id"];

$menu["dana_per_porsi"] = (float) ($menu["dana_per_porsi"] ?? 0);
$menu["dana_per_omprengan"] = (int) ($menu["dana_per_omprengan"] ?? 0);
$menu["dana_total"] = (int) ($menu["dana_total"] ?? 0);
$menu["total_bahan"] = (int) ($menu["total_bahan"] ?? 0);
$menu["jumlah_omprengan"] = (int) ($menu["jumlah_omprengan"] ?? 0);

$menu["sekolah_id"] = $menu["sekolah_id"] !== null ? (int) $menu["sekolah_id"] : null;
$menu["puskesmas_id"] = $menu["puskesmas_id"] !== null ? (int) $menu["puskesmas_id"] : null;

$menu["kalori"] = (int) ($menu["kalori"] ?? 0);
$menu["protein"] = (float) ($menu["protein"] ?? 0);
$menu["karbohidrat"] = (float) ($menu["karbohidrat"] ?? 0);
$menu["lemak"] = (float) ($menu["lemak"] ?? 0);
$menu["serat"] = (float) ($menu["serat"] ?? 0);
$menu["zat_besi"] = (float) ($menu["zat_besi"] ?? 0);
$menu["kalsium"] = (float) ($menu["kalsium"] ?? 0);

$menu["nama_menu"] = $menu["nama_menu"] ?: "Menu " . ($menu["kategori"] ?: "Makanan");
$menu["items"] = [];

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

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

    $resItems = $stmtItems->get_result();

    while ($item = $resItems->fetch_assoc()) {
        $menu["items"][] = [
            "id" => (int) $item["id"],
            "nama_item" => $item["nama_item"]
        ];
    }
}

$rincianBahan = [];

$stmtBahan = $conn->prepare("
    SELECT
        id,
        nama_bahan,
        satuan,
        stok AS jumlah,
        harga_satuan,
        total
    FROM bahan_makanan
    WHERE menu_id = ?
    ORDER BY id ASC
");

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

    $resBahan = $stmtBahan->get_result();

    while ($bahan = $resBahan->fetch_assoc()) {
        $jumlah = (float) ($bahan["jumlah"] ?? 0);
        $harga = (int) ($bahan["harga_satuan"] ?? 0);
        $total = (int) ($bahan["total"] ?? 0);

        if ($total <= 0 && $jumlah > 0 && $harga > 0) {
            $total = (int) ($jumlah * $harga);
        }

        $rincianBahan[] = [
            "id" => (int) $bahan["id"],
            "nama_bahan" => $bahan["nama_bahan"],
            "jumlah" => $jumlah,
            "satuan" => $bahan["satuan"],
            "harga_satuan" => $harga,
            "total" => $total
        ];
    }
}

$rincianDana = [];

$stmtDana = $conn->prepare("
    SELECT
        id,
        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 ($dana = $resDana->fetch_assoc()) {
        $rincianDana[] = [
            "id" => (int) $dana["id"],
            "label" => $dana["label"],
            "nominal" => (int) $dana["nominal"]
        ];
    }
}

$data["menu_utama"] = $menu;
$data["rincian_bahan"] = $rincianBahan;
$data["bahan"] = $rincianBahan;
$data["rincian_dana"] = $rincianDana;

response(true, "Data menu harian berhasil diambil", $data);

?>