
<?php
// Prevent script from timing out during execution loops
set_time_limit(0);

/* =======================================================
   TIMEZONE SYNCHRONIZATION
=========================================================*/
date_default_timezone_set('Asia/Kuala_Lumpur'); 

require_once __DIR__ . "/../config/db.php";

$db_timezone = date('P'); 
mysqli_query($conn, "SET time_zone = '$db_timezone'");

/* =======================================================
   PHPMailer Setup
=========================================================*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../vendor/PHPMailer/src/Exception.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/SMTP.php';

$current_time = date('Y-m-d H:i:s');

/* =======================================================
   SYSTEM MAINTENANCE: RESET FLAGS FOR CHANGED DEADLINES
=========================================================*/
$reset_intent = "UPDATE equipment SET reminder_sent = 0 WHERE next_due_date > ? AND reminder_sent = 1";
$reset_stmt = mysqli_prepare($conn, $reset_intent);
mysqli_stmt_bind_param($reset_stmt, "s", $current_time);
mysqli_stmt_execute($reset_stmt);

/* =======================================================
   ACTION 1: AUTO-UPDATE PASSED DEADLINES TO OVERDUE
=========================================================*/
$overdue_query = "UPDATE equipment 
                  SET status = 'Overdue' 
                  WHERE next_due_date <= ? 
                  AND status NOT IN ('Inactive', 'Under Maintenance')";
$stmt = mysqli_prepare($conn, $overdue_query);
mysqli_stmt_bind_param($stmt, "s", $current_time);
mysqli_stmt_execute($stmt);

/* =======================================================
   ACTION 2: FIND ITEMS DUE IN ~1 DAY (24 HOURS)
=========================================================*/
// CHANGED: TIMESTAMPDIFF looks for equipment due between 0 and 1440 minutes (24 hours) from now
$alert_query = "
    SELECT e.id, e.equipment_name, e.serial_number, e.next_due_date, e.department_id
    FROM equipment e
    WHERE e.next_due_date IS NOT NULL 
      AND e.status NOT IN ('Inactive', 'Under Maintenance', 'Overdue')
      AND e.reminder_sent = 0
      AND TIMESTAMPDIFF(MINUTE, ?, e.next_due_date) BETWEEN 0 AND 1440
";

$alert_stmt = mysqli_prepare($conn, $alert_query);
mysqli_stmt_bind_param($alert_stmt, "s", $current_time);
mysqli_stmt_execute($alert_stmt);
$items_due_soon = mysqli_stmt_get_result($alert_stmt);

while ($item = mysqli_fetch_assoc($items_due_soon)) {
    
    // Fetch technicians linked to this specific item's department_id
    $tech_query = "SELECT full_name, email FROM users WHERE department_id = ? AND role = 'technician' AND is_deleted = 0";
    $tech_stmt = mysqli_prepare($conn, $tech_query);
    mysqli_stmt_bind_param($tech_stmt, "i", $item['department_id']);
    mysqli_stmt_execute($tech_stmt);
    $technicians = mysqli_stmt_get_result($tech_stmt);
    
    $email_sent_to_at_least_one = false;

    while ($tech = mysqli_fetch_assoc($technicians)) {
        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = 'mail.priorisys.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'support@qrcare.priorisys.com';
            $mail->Password   = 'Hifzhan2017';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;

            $mail->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => false, 
                    'verify_peer_name' => false, 
                    'allow_self_signed' => true
                ]
            ];

            $mail->setFrom('support@qrcare.priorisys.com', 'QRCareTrack Alerts');
            $mail->addAddress($tech['email'], $tech['full_name']);
            $mail->isHTML(true);
            
            // CHANGED: Email updated to contextually reflect the 24-hour warning notice
            $mail->Subject = "REMINDER: Maintenance Due in 24 Hours - " . $item['equipment_name'];
            $formatted_time = date('d M Y, h:i A', strtotime($item['next_due_date']));
            
            $mail->Body = "
            <div style='font-family: Segoe UI, sans-serif; padding: 20px; max-width: 600px; border: 1px solid #e0e0e0; border-radius: 8px;'>
                <h2 style='color: #d97706;'>⏳ Upcoming Maintenance Reminder</h2>
                <p>Hello <strong>{$tech['full_name']}</strong>,</p>
                <p>This is an automated notification that an equipment unit assigned to your department is scheduled for service inspection in <strong>24 hours</strong>.</p>
                
                <table style='width: 100%; border-collapse: collapse; margin: 15px 0; background: #fffdfa;'>
                    <tr><td style='padding: 8px; border: 1px solid #f59e0b;'><strong>Equipment Name:</strong></td><td style='padding: 8px; border: 1px solid #f59e0b;'>{$item['equipment_name']}</td></tr>
                    <tr><td style='padding: 8px; border: 1px solid #f59e0b;'><strong>Serial Number:</strong></td><td style='padding: 8px; border: 1px solid #f59e0b;'>{$item['serial_number']}</td></tr>
                    <tr><td style='padding: 8px; border: 1px solid #f59e0b;'><strong>Scheduled Deadline:</strong></td><td style='padding: 8px; border: 1px solid #f59e0b; color: #b45309;'><strong>{$formatted_time}</strong></td></tr>
                </table>

                <p>Please ensure you prepare the required verification logging parameters before work orders execute.</p>
                <br>
                <p>Regards,<br><strong>QRCareTrack Automation Engine</strong></p>
            </div>";

            if($mail->send()) {
                $email_sent_to_at_least_one = true;
            }
        } catch (Exception $e) {
            error_log("Failed sending automated alert to: " . $tech['email']);
        }
    }

    // Flag item so it won't send duplicate emails during subsequent automated sweeps
    if ($email_sent_to_at_least_one) {
        $update_flag = mysqli_prepare($conn, "UPDATE equipment SET reminder_sent = 1 WHERE id = ?");
        mysqli_stmt_bind_param($update_flag, "i", $item['id']);
        mysqli_stmt_execute($update_flag);
    }
}

echo "Execution finished at: " . date('Y-m-d H:i:s');