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

require_once '../includes/db.php';
require_once '../includes/mailer.php';

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

// ==========================
// INIT DB
// ==========================
$conn = db();
if (!$conn) die("Database connection failed");

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

    $email = trim($_POST['email']);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address.";
        $messageType = "error";
    } else {

        try {
            // CHECK USER
            $stmt = $conn->prepare("
                SELECT id, CONCAT(first_name,' ',last_name) AS full_name 
                FROM users 
                WHERE email = ? 
                LIMIT 1
            ");
            if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

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

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

            if ($user) {

                // GENERATE TOKEN
                $token = bin2hex(random_bytes(32));
                $expires = date("Y-m-d H:i:s", strtotime("+30 minutes"));

                // SAVE TOKEN
                $insert = $conn->prepare("
                    INSERT INTO password_resets (user_id, token, expires_at)
                    VALUES (?, ?, ?)
                ");
                if (!$insert) throw new Exception("Insert prepare failed: " . $conn->error);

                $insert->bind_param("iss", $user['id'], $token, $expires);
                if (!$insert->execute()) throw new Exception("Insert execute failed: " . $insert->error);
                $insert->close();

                // RESET LINK
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
                $host = $_SERVER['HTTP_HOST'];
                $link = $protocol . "://" . $host . "/auth/reset_password.php?token=" . $token;

                // SEND EMAIL
                if (!sendMail($email, "Password Reset Request", 
                    "Hello {$user['full_name']},\n\nClick the link below to reset your password:\n\n{$link}\n\nThis link will expire in 30 minutes."
                )) {
                    throw new Exception("Failed to send email. Check mail configuration.");
                }

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

            } else {
                $message = "⚠️ No account found with that email.";
                $messageType = "error";
            }

        } catch (Exception $e) {
            $message = "An error occurred.";
            $messageType = "error";
            $debug = $e->getMessage(); // reveal detailed error
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forgot 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: #ffffff; 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: space-between; }
.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">Forgot Password</div>
    <div class="login-subtitle">Enter your email to reset your password</div>

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

    <form method="POST">
        <input type="email" name="email" placeholder="Email Address" required>
        <button type="submit">Send Reset Link</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>