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

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

/* =========================
   EMAIL FUNCTION
========================= */
function sendEmail($toEmail, $toName, $subject, $htmlBody, $altBody = "")
{
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'hifzhanfatihin30@gmail.com';
        $mail->Password   = 'ntqx vlyx slsw kuos';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        // Fix SSL issue for XAMPP
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->setFrom('hifzhanfatihin30@gmail.com', 'QRCareTrack');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;
        $mail->AltBody = $altBody;

        return $mail->send();

    } catch (Exception $e) {
        error_log("Mailer Error: " . $mail->ErrorInfo);
        return false;
    }
}

/* =========================
   FIND EQUIPMENT DUE IN 1 MINUTE
========================= */

/*
Example:
If next_due_date = 2026-04-23 18:30:00

This script will trigger around:
2026-04-23 18:29:00
*/

$stmt = mysqli_prepare($conn, "
    SELECT
        id,
        equipment_name,
        department_id,
        next_due_date
    FROM equipment
    WHERE TIMESTAMPDIFF(MINUTE, NOW(), next_due_date) = 1
");

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

/* =========================
   LOOP EQUIPMENT
========================= */
while ($equipment = mysqli_fetch_assoc($result)) {

    $equipment_id  = $equipment['id'];
    $department_id = $equipment['department_id'];

    /* =========================
       GET TECHNICIANS IN SAME DEPARTMENT
    ========================= */
    $techStmt = mysqli_prepare($conn, "
        SELECT
            full_name,
            email
        FROM users
        WHERE role = 'technician'
        AND department_id = ?
    ");

    mysqli_stmt_bind_param($techStmt, "i", $department_id);
    mysqli_stmt_execute($techStmt);
    $techResult = mysqli_stmt_get_result($techStmt);

    if (mysqli_num_rows($techResult) == 0) {
        error_log("No technician found for department ID: " . $department_id);
        continue;
    }

    /* =========================
       SEND EMAIL TO EACH TECHNICIAN
    ========================= */
    while ($tech = mysqli_fetch_assoc($techResult)) {

        $subject = "Preventive Maintenance Reminder - QRCareTrack";

        $html = "
            <div style='font-family:Segoe UI, sans-serif; max-width:600px; margin:auto; padding:20px; border:1px solid #ddd; border-radius:8px;'>

                <h2>Preventive Maintenance Reminder</h2>

                <p>Hi {$tech['full_name']},</p>

                <p>
                    This is a reminder that the following equipment is scheduled for preventive maintenance soon.
                </p>

                <p>
                    <strong>Equipment Name:</strong> {$equipment['equipment_name']}<br>
                    <strong>Due Date & Time:</strong> " . date("d M Y h:i A", strtotime($equipment['next_due_date'])) . "
                </p>

                <p>
                    Please prepare for the maintenance activity and ensure the equipment is checked on time.
                </p>

                <p>
                    Thank you.
                </p>

                <p>
                    <strong>QRCareTrack System</strong>
                </p>

            </div>
        ";

        $altBody = "
Preventive Maintenance Reminder

Hi {$tech['full_name']},

Equipment: {$equipment['equipment_name']}
Due Date & Time: " . date("d M Y h:i A", strtotime($equipment['next_due_date'])) . "

Please prepare for preventive maintenance.

QRCareTrack System
        ";

        if (sendEmail(
            $tech['email'],
            $tech['full_name'],
            $subject,
            $html,
            $altBody
        )) {
            error_log("Reminder email sent to: " . $tech['email']);
        } else {
            error_log("Failed sending reminder to: " . $tech['email']);
        }
    }
}

echo "Reminder check completed.";
?>