<?php
require_once '../includes/db.php';
require_once '../includes/session.php';

$message = "";
$messageType = "";
$debug = "";

// ==========================
// GET TOKEN
// ==========================
$token = $_GET['token'] ?? '';
if (!$token) die("No token provided.");

// ==========================
// VALIDATE TOKEN
// ==========================
try {
    $stmt = $conn->prepare("
        SELECT * FROM password_resets
        WHERE token = ? AND used = 0
        LIMIT 1
    ");
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

    $stmt->bind_param("s", $token);
    if (!$stmt->execute()) throw new Exception("Execute failed: " . $stmt->error);

    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$data) throw new Exception("Invalid or already used reset link.");

    // ==========================
    // CHECK EXPIRY
    // ==========================
    if (strtotime($data['expires_at']) < time()) {
        throw new Exception("Reset link has expired.");
    }

    // ==========================
    // HANDLE RESET
    // ==========================
    if ($_SERVER["REQUEST_METHOD"] === "POST") {

        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if ($password !== $confirm_password) {
            $message = "Passwords do not match!";
            $messageType = "error";
        } elseif (strlen($password) < 6) {
            $message = "Password must be at least 6 characters!";
            $messageType = "error";
        } else {

            $hashed = password_hash($password, PASSWORD_BCRYPT);

            // UPDATE PASSWORD
            $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            if (!$update) throw new Exception("Prepare failed: " . $conn->error);
            $update->bind_param("si", $hashed, $data['user_id']);
            $update->execute();
            $update->close();

            // MARK TOKEN AS USED
            $mark = $conn->prepare("UPDATE password_resets SET used = 1 WHERE id = ?");
            if (!$mark) throw new Exception("Prepare failed: " . $conn->error);
            $mark->bind_param("i", $data['id']);
            $mark->execute();
            $mark->close();

            $message = "✅ Password reset successful. You can now login.";
            $messageType = "success";
        }
    }

} catch (Exception $e) {
    $message = $e->getMessage();
    $messageType = "error";
    $debug = $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reset Password - Texas Capital Bank</title>
<style>
body { margin:0; font-family: Arial,sans-serif; background: linear-gradient(135deg,#0f172a,#1e293b); height:100vh; display:flex; justify-content:center; align-items:center; }
.login-box { width:380px; background:#fff; padding:30px; border-radius:12px; box-shadow:0 20px 60px rgba(0,0,0,0.4); text-align:center; }
.login-logo img { width:80px; margin-bottom:10px; }
.login-title { font-size:18px; font-weight:bold; color:#1e293b; margin-bottom:5px; }
.login-subtitle { font-size:13px; color:#64748b; margin-bottom:20px; }
input { width:100%; padding:12px; margin:8px 0; border:1px solid #cbd5e1; border-radius:8px; outline:none; transition:0.2s; }
input:focus { border-color:#2563eb; box-shadow:0 0 0 3px rgba(37,99,235,0.2); }
button { width:100%; padding:12px; background:#2563eb; color:white; border:none; border-radius:8px; font-weight:bold; cursor:pointer; margin-top:10px; transition:0.2s; }
button:hover { background:#1d4ed8; }
.error, .success { padding:10px; border-radius:8px; margin-bottom:10px; font-size:14px; text-align:left; }
.error { background-color:#fee2e2; color:#b91c1c; border:1px solid #f5c6cb; }
.success { background-color:#e6f4ea; color:#276749; border:1px solid #c6f0d6; }
.auth-links { margin-top:15px; font-size:13px; display:flex; justify-content:flex-start; }
.auth-links a { color:#2563eb; text-decoration:none; transition:0.2s; }
.auth-links a:hover { text-decoration:underline; opacity:0.8; }
.footer { margin-top:15px; font-size:12px; color:#94a3b8; }
.debug { margin-top:10px; padding:10px; background:#f8f9fa; color:#111; border:1px solid #ddd; font-size:12px; border-radius:6px; text-align:left; }
</style>
</head>
<body>

<div class="login-box">
    <div class="login-logo">
        <img src="/assets/images/logo2.png" alt="Bank Logo">
    </div>

    <div class="login-title">Reset Password</div>
    <div class="login-subtitle">Set a new password for your account</div>

    <?php if ($message): ?>
        <div class="<?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <form method="POST">
        <input type="password" name="password" placeholder="New Password" required>
        <input type="password" name="confirm_password" placeholder="Confirm Password" required>
        <button type="submit">Reset Password</button>
    </form>

    <div class="auth-links">
        <a href="login.php">← Back to Login</a>
    </div>

    <?php if ($debug): ?>
        <div class="debug"><strong>DEBUG:</strong> <?= htmlspecialchars($debug) ?></div>
    <?php endif; ?>

    <div class="footer">
        © <?= date('Y') ?> Texas Capital Bank Banking Corporation
    </div>
</div>

</body>
</html>