<?php
// File: API_KONEKSI/admin/beranda.php

header('Content-Type: application/json');
include '../config/koneksi.php';

// Jalankan cron gdrive secara otomatis 1x sehari (aman karena ada sistem lock file)
include_once '../distribusi/cron_gdrive.php';

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $admin_id = $_GET['user_id'] ?? '';
    $today = date('Y-m-d');

    $data = [
        "pesanan_baru" => 0,
        "pendapatan" => 0,
        "sesi_aktif" => 0,
        "foto_tertunda" => 0,
        "unread_notif" => 0
    ];

    // 1. Pesanan Baru (Dibuat hari ini)
    $stmt1 = $conn->prepare("SELECT COUNT(*) AS total FROM dat_reservasi WHERE DATE(created_at) = ? AND deleted_st = 0");
    $stmt1->bind_param("s", $today);
    $stmt1->execute();
    $data['pesanan_baru'] = $stmt1->get_result()->fetch_assoc()['total'];
    $stmt1->close();

    // 2. Pendapatan Hari Ini (Total harga dari pembayaran yang diverifikasi hari ini)
    $stmt2 = $conn->prepare("
        SELECT SUM(r.final_harga) AS total 
        FROM dat_reservasi r 
        JOIN dat_pembayaran p ON r.reservasi_id = p.reservasi_id 
        WHERE p.validasi_st = 'Verified' AND DATE(p.bayar_tgl) = ? AND r.deleted_st = 0
    ");
    $stmt2->bind_param("s", $today);
    $stmt2->execute();
    $result2 = $stmt2->get_result()->fetch_assoc();
    $data['pendapatan'] = $result2['total'] ?? 0; // Jika null jadikan 0
    $stmt2->close();

    // 3. Sesi Aktif (Jadwal pemotretan yang jatuh pada hari ini dan tidak dibatalkan)
    $stmt3 = $conn->prepare("SELECT COUNT(*) AS total FROM dat_reservasi WHERE booking_tgl = ? AND reservasi_st NOT IN ('Dibatalkan', 'Batal') AND deleted_st = 0");
    $stmt3->bind_param("s", $today);
    $stmt3->execute();
    $data['sesi_aktif'] = $stmt3->get_result()->fetch_assoc()['total'];
    $stmt3->close();

    // 4. Foto Tertunda (Sesi sudah lewat/hari ini, tapi belum ada link gdrive di dat_distribusi)
    $stmt4 = $conn->prepare("
        SELECT COUNT(*) AS total 
        FROM dat_reservasi r 
        WHERE r.booking_tgl <= ? AND r.reservasi_st NOT IN ('Dibatalkan', 'Batal') AND r.deleted_st = 0 
        AND NOT EXISTS (
            SELECT 1 FROM dat_distribusi d WHERE d.reservasi_id = r.reservasi_id AND d.deleted_st = 0
        )
    ");
    $stmt4->bind_param("s", $today);
    $stmt4->execute();
    $data['foto_tertunda'] = $stmt4->get_result()->fetch_assoc()['total'];
    $stmt4->close();

    // 5. Cek Notifikasi Belum Dibaca
    $stmt5 = $conn->prepare("SELECT COUNT(*) AS total FROM dat_notifikasi WHERE user_id = ? AND is_read = 0 AND deleted_st = 0");
    $stmt5->bind_param("s", $admin_id);
    $stmt5->execute();
    $data['unread_notif'] = $stmt5->get_result()->fetch_assoc()['total'];
    $stmt5->close();

    echo json_encode(["status" => "sukses", "pesan" => "Data beranda berhasil dimuat", "data" => [$data]]);
} else {
    echo json_encode(["status" => "gagal", "pesan" => "Metode request tidak valid!", "data" => []]);
}

$conn->close();
?>