<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/PHPMailer/src/Exception.php';
require '../vendor/PHPMailer/src/PHPMailer.php';
require '../vendor/PHPMailer/src/SMTP.php';

$message = "";

// Function untuk hantar email
function sendResetEmail($toEmail, $toName, $resetLink) {
    $mail = new PHPMailer(true);

    try {
        $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->setFrom('support@qrcare.priorisys.com', 'QRCareTrack');
        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);
        $mail->Subject = "Password Reset - QRCareTrack";
        $mail->Body = "
<div style='font-family:Segoe UI,sans-serif; max-width:600px; margin:auto; border:1px solid #ddd; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.1); overflow:hidden;'>
    <div style='background:#2bbbad; padding:20px; color:white; text-align:center; font-size:18px; font-weight:bold;'>
        QRCareTrack Password Reset
    </div>
    <div style='padding:25px; color:#333; font-size:14px; line-height:1.6;'>
        <p>Hello <strong>$toName</strong>,</p>
        <p>You requested to reset your password. Click the button below to set a new password:</p>
        <p style='text-align:center; margin:30px 0;'>
            <a href='$resetLink' 
               style='background:#2bbbad;color:white;
                      padding:12px 25px;
                      text-decoration:none;
                      border-radius:6px;
                      display:inline-block;
                      font-weight:bold;'>
               Reset Password
            </a>
        </p>
        <p style='font-size:12px; color:#555;'>This link will expire in 15 minutes.</p>
        <p style='font-size:12px; color:#555;'>If you did not request this, you can safely ignore this email.</p>
    </div>
    <div style='background:#f5f5f5; padding:15px; text-align:center; font-size:12px; color:#888;'>
        &copy; ".date('Y')." QRCareTrack. All rights reserved.
    </div>
</div>
";
        $mail->AltBody = "Hello $toName,\n\nYou requested to reset your password.\nCopy this link to reset: $resetLink\nThis link expires in 15 minutes.\nIf you did not request this, ignore this email.";

        // Bypass SSL verification (localhost sahaja)
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->send();
        return true;
    } catch (Exception $e) {
        // Untuk debug sementara
        echo "Mailer Error: " . $mail->ErrorInfo;
        return false;
    }
}

if (isset($_POST['send_link'])) {
    $email = trim($_POST['email']);

    $sql = "SELECT id, full_name FROM users WHERE email = ?";
    $stmt = mysqli_prepare($conn, $sql);
    if (!$stmt) die("SQL Error: " . mysqli_error($conn));

    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($user = mysqli_fetch_assoc($result)) {
        $user_id = $user['id'];
        $name = $user['full_name'];

        // Generate secure token
        $token = bin2hex(random_bytes(32));
        $expiry = date("Y-m-d H:i:s", strtotime("+15 minutes"));

        // Delete old token
        $delete = "DELETE FROM password_resets WHERE user_id = ?";
        $stmtDel = mysqli_prepare($conn, $delete);
        mysqli_stmt_bind_param($stmtDel, "i", $user_id);
        mysqli_stmt_execute($stmtDel);

        // Insert new token
        $insert = "INSERT INTO password_resets (user_id, token, expiry) VALUES (?, ?, ?)";
        $stmt2 = mysqli_prepare($conn, $insert);
        mysqli_stmt_bind_param($stmt2, "iss", $user_id, $token, $expiry);
        mysqli_stmt_execute($stmt2);

        // Reset link
        $reset_link = "https://qrcare.priorisys.com/auth/reset_password.php?token=" . $token;

        // Hantar email
        sendResetEmail($email, $name, $reset_link);
    }

    $message = "If the email exists, a reset link has been sent.";
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Forgot Password - QRCareTrack</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* Guna style asal awak */
        * { box-sizing: border-box; font-family: 'Segoe UI', sans-serif; }
        body { margin:0; height:100vh; background: url('../assets/background.png') no-repeat center center/cover; display:flex; justify-content:center; align-items:center; }
        .card { width:400px; background:#fff; padding:40px 35px; border-radius:12px; box-shadow:0 15px 35px rgba(0,0,0,0.15); text-align:center; }
        .logo { width:80px; margin-bottom:20px; }
        h2 { margin-bottom:25px; font-weight:600; color:#333; }
        .form-group { text-align:left; margin-bottom:18px; }
        label { font-size:14px; color:#444; display:block; margin-bottom:6px; }
        input { width:100%; padding:10px 12px; border:1px solid #ccc; border-radius:6px; font-size:14px; transition:0.2s; }
        input:focus { border-color:#2bbbad; outline:none; box-shadow:0 0 0 2px rgba(43,187,173,0.2); }
        .btn { width:100%; padding:11px; background-color:#2bbbad; border:none; border-radius:25px; color:white; font-size:15px; cursor:pointer; transition:0.2s; margin-top:10px; }
        .btn:hover { background-color:#239c92; }
        .message { background:#e8f8f5; color:#1d8348; padding:8px; border-radius:5px; margin-bottom:15px; font-size:13px; }
        .back { margin-top:15px; font-size:13px; }
        .back a { text-decoration:none; color:#666; }
        .back a:hover { text-decoration:underline; }
        @media (max-width:480px) { .card { width:90%; padding:30px 20px; } }
    </style>
</head>
<body>

<div class="card">
    <img src="../assets/logo.png" class="logo" alt="Logo">
    <h2>Forgot Password</h2>

    <?php if (!empty($message)) : ?>
        <div class="message"><?php echo $message; ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>Enter Your Email</label>
            <input type="email" name="email" required>
        </div>
        <button type="submit" name="send_link" class="btn">Send Reset Link</button>
    </form>

    <div class="back">
        <a href="login.php">Back to Login</a>
    </div>
</div>

</body>
</html>