<?php
// forgot-password.php — Password reset request
session_start();
include 'config.php';

$message = '';
$error = '';
$reset_token = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } else {
        $stmt = $conn->prepare("SELECT id, org_name FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        if (!$user) {
            // Don't reveal whether email exists — generic message
            $message = "If an account with that email exists, a reset link has been generated.";
        } else {
            // Generate token
            $token = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

            $stmt = $conn->prepare("UPDATE users SET password_reset_token = ?, password_reset_expires = ? WHERE id = ?");
            $stmt->bind_param("ssi", $token, $expires, $user['id']);
            $stmt->execute();

            // Build reset URL (SEO-friendly)
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];
            $reset_url = "$protocol://$host/reset-password/$token";

            // Audit log
            if (file_exists(__DIR__ . '/util/audit_logger.php')) {
                include_once __DIR__ . '/util/audit_logger.php';
                audit_log(
                    $conn,
                    'password_reset_requested',
                    'users',
                    $user['id'],
                    $user['id'],
                    0,
                    null,
                    null,
                    "Password reset requested for " . $email
                );
            }

            // Send email via SMTP
            $email_sent = false;
            if (file_exists(__DIR__ . '/smtp_mailer.php')) {
                include_once __DIR__ . '/smtp_mailer.php';
                $mailer = new SmtpMailer();
                $subject = "SaniBook — Password Reset Request";
                $html_body = '
                <div style="max-width:520px;margin:0 auto;font-family:Inter,Arial,sans-serif;background:#f8fafc;padding:32px;">
                    <div style="background:#fff;border-radius:16px;border:1px solid #e2e8f0;padding:32px;text-align:center;">
                        <div style="width:56px;height:56px;background:#fef3c7;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;margin-bottom:16px;">
                            <span style="font-size:24px;">🔐</span>
                        </div>
                        <h2 style="color:#0f172a;font-size:22px;margin:0 0 8px;">Password Reset</h2>
                        <p style="color:#64748b;font-size:14px;margin:0 0 24px;">
                            Hi <strong>' . htmlspecialchars($user['org_name']) . '</strong>, we received a request to reset your password.
                        </p>
                        <a href="' . htmlspecialchars($reset_url) . '"
                           style="display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:14px 32px;border-radius:10px;font-weight:700;font-size:14px;">
                            Reset My Password
                        </a>
                        <p style="color:#94a3b8;font-size:12px;margin:24px 0 0;">
                            This link expires in <strong>1 hour</strong>. If you didn\'t request this, ignore this email.
                        </p>
                        <hr style="border:none;border-top:1px solid #e2e8f0;margin:24px 0;">
                        <p style="color:#cbd5e1;font-size:11px;margin:0;">
                            SaniBook Registry &bull; sanibook.ke
                        </p>
                    </div>
                </div>';
                $email_sent = $mailer->send($email, $subject, $html_body);
            }

            if ($email_sent) {
                $message = "A password reset link has been sent to your email.";
            } else {
                // Fallback: show token if email fails
                $reset_token = $token;
                $message = "Email delivery failed. Use the token below to reset your password.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Forgot Password - SaniBook</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        body {
            font-family: 'Inter', system-ui, sans-serif;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen flex items-center justify-center">
    <div class="w-full max-w-md p-6">
        <div class="bg-white rounded-2xl shadow-lg p-8 border border-slate-200">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-yellow-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <i class="fa-solid fa-envelope-open-text text-2xl text-yellow-600"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-900">Forgot Password</h2>
                <p class="text-slate-500 text-sm mt-1">Enter your email to get a reset token</p>
            </div>

            <?php if ($message): ?>
                <div
                    class="bg-green-50 border border-green-200 text-green-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-check-circle"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            <?php if ($reset_token): ?>
                <div class="bg-yellow-50 border border-yellow-200 text-yellow-800 p-4 rounded-lg mb-4">
                    <p class="text-xs font-bold uppercase mb-1">Reset Token</p>
                    <p class="font-mono text-sm break-all bg-white p-2 rounded border border-yellow-300">
                        <?= htmlspecialchars($reset_token) ?>
                    </p>
                    <p class="text-xs mt-2">Share this with the user or use it at:
                        <a href="reset-password.php?token=<?= urlencode($reset_token) ?>"
                            class="text-blue-600 hover:underline">
                            Reset Password Page
                        </a>
                    </p>
                </div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div
                    class="bg-red-50 border border-red-200 text-red-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-exclamation-circle"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-5">
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-1">Email Address</label>
                    <div class="relative">
                        <input type="email" name="email" required
                            class="w-full border border-slate-300 rounded-lg p-3 pl-10 text-sm focus:ring-2 focus:ring-blue-500"
                            placeholder="your@email.com">
                        <i class="fa-solid fa-envelope absolute left-3 top-3.5 text-slate-400"></i>
                    </div>
                </div>
                <button type="submit"
                    class="w-full py-3 bg-yellow-500 text-white rounded-lg font-bold hover:bg-yellow-600 transition-all shadow-md text-sm">
                    <i class="fa-solid fa-paper-plane mr-1"></i> Request Reset Token
                </button>
            </form>

            <div class="mt-4 text-center">
                <a href="login.php" class="text-sm text-blue-600 hover:underline">
                    <i class="fa-solid fa-arrow-left mr-1"></i> Back to Login
                </a>
            </div>
        </div>
    </div>
</body>

</html>