<?php
/**
 * Forgot Password Page
 * Allows users to request a password reset link
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/mailer.php';

initSecureSession();

// Redirect if already logged in
if(isAuthenticated() && validateSession()) {
    header('Location: dashboard');
    exit;
}

$error = '';
$success = '';

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Verify CSRF token
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!verifyCSRFToken($csrf_token)) {
        $error = 'Security token expired. Please try again.';
    } else {
        // Rate limiting
        $ip = getClientIP();
        if (!checkRateLimit("password_reset_$ip", 3, 300)) { // 3 attempts per 5 minutes
            $error = 'Too many reset attempts. Please wait a few minutes.';
        } else {
            $email = sanitizeInput($_POST['email'] ?? '');

            if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = 'Please enter a valid email address.';
            } else {
                // Find user by email
                $email_escaped = mysqli_real_escape_string($conn, $email);
                $result = mysqli_query($conn, "SELECT id, username, full_name, email, status FROM users WHERE email = '$email_escaped'");

                if (mysqli_num_rows($result) === 1) {
                    $user = mysqli_fetch_assoc($result);

                    // Check if account is active
                    if ($user['status'] === 'approved') {
                        // Create reset token
                        $token = createPasswordResetToken($conn, $user['id'], $user['email']);

                        if ($token) {
                            // Build reset URL
                            $resetUrl = APP_URL . '/reset-password?token=' . urlencode($token);

                            // Send email
                            $emailSent = sendPasswordResetEmail(
                                $user['email'],
                                $user['full_name'] ?: $user['username'],
                                $token,
                                $resetUrl
                            );

                            if ($emailSent) {
                                // Log the action
                                $ip_escaped = mysqli_real_escape_string($conn, $ip);
                                mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address)
                                                     VALUES ({$user['id']}, 'password_reset_request', 'Password reset requested', '$ip_escaped')");

                                $success = 'If an account with that email exists, we have sent a password reset link. Please check your inbox and spam folder.';
                            } else {
                                $error = 'Failed to send reset email. Please try again or contact support.';
                            }
                        } else {
                            $error = 'An error occurred. Please try again.';
                        }
                    } else {
                        // Account not approved - show generic message for security
                        $success = 'If an account with that email exists, we have sent a password reset link. Please check your inbox and spam folder.';
                    }
                } else {
                    // User not found - show generic message for security
                    $success = 'If an account with that email exists, we have sent a password reset link. Please check your inbox and spam folder.';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .reset-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 420px;
        }
        .reset-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .reset-header i {
            font-size: 60px;
            color: #1a3a6e;
        }
        .reset-header h2 {
            color: #1a3a6e;
            margin-top: 15px;
        }
        .form-control {
            border-radius: 25px;
            padding: 12px 20px;
            border: 2px solid #e0e0e0;
        }
        .form-control:focus {
            border-color: #1a3a6e;
            box-shadow: none;
        }
        .btn-reset {
            background: linear-gradient(135deg, #1a3a6e 0%, #2d5a3d 100%);
            border: none;
            border-radius: 25px;
            padding: 12px;
            font-weight: bold;
            width: 100%;
            color: white;
        }
        .btn-reset:hover {
            background: linear-gradient(135deg, #2d5a3d 0%, #1a3a6e 100%);
            color: white;
        }
        .back-link {
            text-align: center;
            margin-top: 20px;
        }
        .back-link a {
            color: #1a3a6e;
            font-weight: bold;
        }
        .info-box {
            background: #e7f3ff;
            border: 1px solid #b6d4fe;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .info-box i {
            color: #0d6efd;
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-header">
            <i class="fas fa-key"></i>
            <h2>Forgot Password</h2>
            <p class="text-muted">Enter your email to reset your password</p>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo htmlspecialchars($error); ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success); ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
        <?php else: ?>

        <div class="info-box">
            <p class="mb-0 small">
                <i class="fas fa-info-circle mr-2"></i>
                Enter the email address associated with your account and we'll send you a link to reset your password.
            </p>
        </div>

        <form action="" method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text" style="border-radius: 25px 0 0 25px; border: 2px solid #e0e0e0; border-right: none;">
                            <i class="fas fa-envelope text-muted"></i>
                        </span>
                    </div>
                    <input type="email" name="email" class="form-control" placeholder="Enter your email address"
                           required autofocus style="border-radius: 0 25px 25px 0; border-left: none;">
                </div>
            </div>

            <button type="submit" class="btn btn-reset">
                <i class="fas fa-paper-plane mr-2"></i>Send Reset Link
            </button>
        </form>
        <?php endif; ?>

        <div class="back-link">
            <p><a href="login"><i class="fas fa-arrow-left mr-2"></i>Back to Login</a></p>
        </div>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
