<?php
// File: API_KONEKSI/customer/dashboard_summary.php
header('Content-Type: application/json');

include '../config/koneksi.php';
include '../config/middleware.php';

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $payload = authenticateJWT();
    $user_id = $payload['user_id'] ?? '';

    if (empty($user_id)) {
        echo json_encode([
            "status" => "gagal", 
            "pesan" => "ID Pengguna tidak ditemukan dari token", 
            "data" => []
        ]);
        exit;
    }

    $notif_unread_count = 0;
    $active_booking_count = 0;
    
    // Get unread notification count
    $query = "SELECT COUNT(*) as unread FROM dat_notifikasi WHERE user_id = ? AND is_read = 0 AND deleted_st = 0";
    $stmt = $conn->prepare($query);
    
    if ($stmt) {
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $notif_unread_count = (int)$row['unread'];
        }
        $stmt->close();
    }

    // Get active booking count (status pending/confirmed)
    $query_booking = "SELECT COUNT(*) as active_bookings FROM dat_reservasi WHERE user_id = ? AND reservasi_st IN ('Pending', 'Verified', 'Proses') AND deleted_st = 0";
    $stmt_booking = $conn->prepare($query_booking);
    
    if ($stmt_booking) {
        $stmt_booking->bind_param("s", $user_id);
        $stmt_booking->execute();
        $result_booking = $stmt_booking->get_result();
        
        if ($row_booking = $result_booking->fetch_assoc()) {
            $active_booking_count = (int)$row_booking['active_bookings'];
        }
        $stmt_booking->close();
    }

    $data = [
        "unread_notif_count" => $notif_unread_count,
        "has_unread_notif" => $notif_unread_count > 0,
        "active_booking_count" => $active_booking_count
    ];

    echo json_encode([
        "status" => "sukses",
        "pesan" => "Data beranda berhasil dimuat",
        "data" => [$data]
    ]);

} else {
    echo json_encode([
        "status" => "gagal", 
        "pesan" => "Metode request tidak diizinkan", 
        "data" => []
    ]);
}
?>