<?php
// File: API_KONEKSI/distribusi/cron_gdrive.php
// Script ini dieksekusi secara otomatis sekali sehari untuk mengecek link GDrive
include_once __DIR__ . '/../config/koneksi.php';
include_once __DIR__ . '/../config/id_generator.php';

$cron_file = __DIR__ . '/../config/last_cron_gdrive.txt';
$today = date('Y-m-d');

$should_run = true;
if (file_exists($cron_file)) {
    $last_run = file_get_contents($cron_file);
    if (trim($last_run) === $today) {
        $should_run = false;
    }
}

if ($should_run && isset($conn)) {
    // 1. CEK H-1 (6 Hari sejak diupload)
    $q_h1 = "SELECT d.distribusi_id, r.user_id, r.reservasi_id, p.paket_nm, u.role_nm 
             FROM dat_distribusi d
             JOIN dat_reservasi r ON d.reservasi_id = r.reservasi_id
             JOIN mst_paket p ON r.paket_id = p.paket_id
             JOIN mst_user u ON r.user_id = u.user_id
             WHERE d.akses_st = 'Active' 
               AND d.deleted_st = 0 
               AND DATEDIFF(CURDATE(), DATE(d.upload_tgl)) = 6";
               
    $res_h1 = $conn->query($q_h1);
    if ($res_h1 && $res_h1->num_rows > 0) {
        $stmt_cek = $conn->prepare("SELECT notif_id FROM dat_notifikasi WHERE target_id = ? AND judul_tx LIKE '%Sisa 1 Hari%'");
        $stmt_ins = $conn->prepare("INSERT INTO dat_notifikasi (notif_id, user_id, tipe_notif, target_id, judul_tx, pesan_tx) VALUES (?, ?, ?, ?, ?, ?)");
        
        while ($row = $res_h1->fetch_assoc()) {
            // Cek biar gak dobel kirim per reservasi
            $stmt_cek->bind_param("s", $row['reservasi_id']);
            $stmt_cek->execute();
            $stmt_cek->store_result();
            if ($stmt_cek->num_rows == 0) {
                if ($row['role_nm'] === 'Pelanggan') {
                    $judul = "Link GDrive Sisa 1 Hari ⚠️";
                    $pesan = "Akses link foto paket " . $row['paket_nm'] . " kamu akan ditutup besok. Segera unduh hasilnya ya!";
                    $notif_id = generateNotifId($conn);
                    $tipe = 'distribusi';
                    $stmt_ins->bind_param("ssssss", $notif_id, $row['user_id'], $tipe, $row['reservasi_id'], $judul, $pesan);
                    $stmt_ins->execute();
                }
            }
        }
        $stmt_cek->close();
        $stmt_ins->close();
    }

    // 2. CEK EXPIRED (7 Hari atau lebih)
    $q_exp = "SELECT d.distribusi_id, r.user_id, r.reservasi_id, p.paket_nm, u.role_nm 
              FROM dat_distribusi d
              JOIN dat_reservasi r ON d.reservasi_id = r.reservasi_id
              JOIN mst_paket p ON r.paket_id = p.paket_id
              JOIN mst_user u ON r.user_id = u.user_id
              WHERE d.akses_st = 'Active' 
                AND d.deleted_st = 0 
                AND DATEDIFF(CURDATE(), DATE(d.upload_tgl)) >= 7";
    $res_exp = $conn->query($q_exp);

    if ($res_exp && $res_exp->num_rows > 0) {
        $stmt_upd = $conn->prepare("UPDATE dat_distribusi SET akses_st = 'Expired', updated_at = NOW() WHERE distribusi_id = ?");
        
        $stmt_cek2 = $conn->prepare("SELECT notif_id FROM dat_notifikasi WHERE target_id = ? AND judul_tx LIKE '%Telah Hangus%'");
        $stmt_ins2 = $conn->prepare("INSERT INTO dat_notifikasi (notif_id, user_id, tipe_notif, target_id, judul_tx, pesan_tx) VALUES (?, ?, ?, ?, ?, ?)");
        
        while ($row = $res_exp->fetch_assoc()) {
            // Update status dulu
            $stmt_upd->bind_param("s", $row['distribusi_id']);
            $stmt_upd->execute();
            
            // Cek notif biar gak dobel
            $stmt_cek2->bind_param("s", $row['reservasi_id']);
            $stmt_cek2->execute();
            $stmt_cek2->store_result();
            if ($stmt_cek2->num_rows == 0) {
                if ($row['role_nm'] === 'Pelanggan') {
                    $judul = "Link Telah Hangus 🚫";
                    $pesan = "Batas waktu akses GDrive hasil foto paket " . $row['paket_nm'] . " telah kedaluwarsa. Hubungi admin jika butuh bantuan.";
                    $notif_id = generateNotifId($conn);
                    $tipe = 'distribusi';
                    $stmt_ins2->bind_param("ssssss", $notif_id, $row['user_id'], $tipe, $row['reservasi_id'], $judul, $pesan);
                    $stmt_ins2->execute();
                }
            }
        }
        $stmt_cek2->close();
        $stmt_ins2->close();
        $stmt_upd->close();
    }
    
    // Simpan tanda sudah running hari ini
    file_put_contents($cron_file, $today);
}
?>
