<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

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

$user_id = $_SESSION['user_id'];
$message = "";

/* =========================================
   GET USER INFO
========================================= */
$stmt = mysqli_prepare($conn,
    "SELECT full_name,email FROM users WHERE id=?"
);

mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);

$user = mysqli_fetch_assoc(
    mysqli_stmt_get_result($stmt)
);

if (!$user) {
    die("User not found.");
}

$name  = $user['full_name'];
$email = $user['email'];

/* =========================================
   SEND RESET EMAIL FUNCTION
========================================= */
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;

        /* Optional for localhost/XAMPP */
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->setFrom(
            'support@qrcare.priorisys.com',
            'QRCareTrack'
        );

        $mail->addAddress($toEmail, $toName);

        $mail->isHTML(true);

        $mail->Subject = "Change Password - QRCareTrack";

        $mail->Body = "
<div style='font-family:Segoe UI,sans-serif;
            max-width:600px;
            margin:auto;
            border:1px solid #ddd;
            border-radius:8px;
            overflow:hidden;
            box-shadow:0 4px 12px rgba(0,0,0,0.1);'>

    <div style='background:#2bbbad;
                color:white;
                padding:20px;
                text-align:center;
                font-size:20px;
                font-weight:bold;'>

        QRCareTrack Password Change

    </div>

    <div style='padding:25px;
                color:#333;
                line-height:1.6;'>

        <p>Hello <strong>$toName</strong>,</p>

        <p>
            You requested to change your password.
        </p>

        <p>
            Click the button below to continue:
        </p>

        <div style='text-align:center;margin:30px 0;'>

            <a href='$resetLink'
               style='background:#2bbbad;
                      color:white;
                      padding:12px 25px;
                      border-radius:6px;
                      text-decoration:none;
                      display:inline-block;
                      font-weight:bold;'>

                Change Password

            </a>

        </div>

        <p style='font-size:13px;color:#666;'>
            This link will expire in 15 minutes.
        </p>

        <p style='font-size:13px;color:#666;'>
            If you did not request this action,
            please ignore this email.
        </p>

    </div>

    <div style='background:#f5f5f5;
                padding:15px;
                text-align:center;
                font-size:12px;
                color:#888;'>

        © " . date('Y') . " QRCareTrack

    </div>

</div>
";

        $mail->AltBody =
"Hello $toName,

You requested to change your password.

Reset Link:
$resetLink

This link expires in 15 minutes.

QRCareTrack";

        $mail->send();

        return true;

    } catch (Exception $e) {

        return false;
    }
}

/* =========================================
   SEND RESET LINK
========================================= */
if (isset($_POST['send_link'])) {

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

    /* Send Email */
    if (sendResetEmail($email, $name, $reset_link)) {

        $message =
            "Password reset link has been sent to your email.";

    } else {

        $message =
            "Failed to send reset email.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Change Password - QRCareTrack</title>

    <style>

        *{
            box-sizing:border-box;
            font-family:'Segoe UI',sans-serif;
        }

        body{
            margin:0;
            height:100vh;
            display:flex;
            justify-content:center;
            align-items:center;
            background:#f5f7fb;
        }

        .card{
            width:420px;
            background:white;
            padding:35px;
            border-radius:12px;
            box-shadow:0 10px 30px rgba(0,0,0,0.1);
            text-align:center;
        }

        h2{
            margin-bottom:20px;
        }

        p{
            color:#666;
            font-size:14px;
        }

        .btn{
            width:100%;
            padding:12px;
            border:none;
            border-radius:25px;
            background:#2bbbad;
            color:white;
            font-size:15px;
            cursor:pointer;
            margin-top:20px;
        }

        .btn:hover{
            background:#239c92;
        }

        .message{
            background:#e8f8f5;
            color:#1d8348;
            padding:10px;
            border-radius:6px;
            margin-bottom:15px;
            font-size:14px;
        }

        .back{
            margin-top:15px;
        }

        .back a{
            text-decoration:none;
            color:#666;
            font-size:14px;
        }

    </style>
</head>

<body>

<div class="card">

    <h2>Change Password</h2>

    <p>
        Click the button below to receive
        a secure password reset link.
    </p>

    <?php if(!empty($message)): ?>

        <div class="message">
            <?= $message ?>
        </div>

    <?php endif; ?>

    <form method="POST">

        <button type="submit"
                name="send_link"
                class="btn">

            Send Reset Link

        </button>

    </form>

    <div class="back">
        <a href="../settings.php">
            ← Back to Settings
        </a>
    </div>

</div>

</body>
</html>