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

date_default_timezone_set("Asia/Kuala_Lumpur");

/* =========================
   EMAIL FUNCTION
========================= */
function sendEmail($toEmail, $toName, $subject, $htmlBody)
{
    $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;

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

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

        return $mail->send();

    } catch (Exception $e) {
        error_log($mail->ErrorInfo);
        return false;
    }
}

/* =========================
   TARGET TIMER (2 MIN TEST)
========================= */
$toEmail = "muhammadhifzhanfatihin30@yahoo.com";
$toName  = "Hifzhan";

/*
We store target time once per page load
BUT store it in GET so refresh doesn't reset it
*/
if (!isset($_GET['start'])) {
    $startTime = time();
    header("Location: ?start=$startTime");
    exit();
}

$startTime = intval($_GET['start']);
$targetTime = $startTime + 120; // 2 minutes
$currentTime = time();

$emailSent = false;
$message = "⏳ Waiting for 2-minute timer...";

/* =========================
   SEND EMAIL ONCE TIME HIT
========================= */
if ($currentTime >= $targetTime && !isset($_GET['sent'])) {

    $subject = "⏰ Timer Test Email - QRCareTrack";

    $html = "
        <h2>Timer Triggered!</h2>
        <p>Email sent after 2 minutes.</p>
        <p><strong>Server Time:</strong> " . date("d M Y h:i:s A") . "</p>
    ";

    if (sendEmail($toEmail, $toName, $subject, $html)) {
        $emailSent = true;
        $message = "✔ Email Sent Successfully!";
    } else {
        $message = "✖ Failed to send email";
    }

    // mark as sent using URL flag
    header("Location: ?start=$startTime&sent=1");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reliable 2-Min Email Timer</title>

    <style>
        body { font-family: Arial; padding: 30px; }
        .box {
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 10px;
            width: 500px;
        }
        #clock {
            font-size: 20px;
            font-weight: bold;
            margin-top: 10px;
        }
        .ok { color: green; font-weight: bold; }
        .wait { color: orange; }
    </style>
</head>

<body>

<div class="box">

    <h2>2-Minute Email Timer (FIXED VERSION)</h2>

    <p><strong>Start Time:</strong> <?= date("d M Y h:i:s A", $startTime) ?></p>
    <p><strong>Target Time:</strong> <?= date("d M Y h:i:s A", $targetTime) ?></p>
    <p><strong>Server Time:</strong> <?= date("d M Y h:i:s A") ?></p>

    <p class="<?= $emailSent ? 'ok' : 'wait' ?>">
        <?= $message ?>
    </p>

    <h3>Live Clock</h3>
    <div id="clock">Loading...</div>

</div>

<script>
function updateClock() {
    const now = new Date();

    let d = String(now.getDate()).padStart(2,'0');
    let m = String(now.getMonth()+1).padStart(2,'0');
    let y = now.getFullYear();

    let h = now.getHours();
    let min = String(now.getMinutes()).padStart(2,'0');
    let s = String(now.getSeconds()).padStart(2,'0');

    let ampm = h >= 12 ? "PM" : "AM";
    h = h % 12;
    h = h ? h : 12;

    document.getElementById("clock").innerHTML =
        `${d}/${m}/${y} ${h}:${min}:${s} ${ampm}`;
}

setInterval(updateClock, 1000);
updateClock();
</script>

</body>
</html>