<?php
// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");

// Load CORS configuration FIRST
require_once __DIR__ . '/includes/cors.php';
configureCors();

// Load environment variables
require_once __DIR__ . '/includes/config_loader.php';

// Load dependencies
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/auth_functions.php'; // Your existing auth functions
require_once __DIR__ . '/includes/sms_helper.php';
require_once __DIR__ . '/includes/email_helper.php'; // If you have separate email helper
require_once __DIR__ . '/auth/AuditLogger.php';
require_once __DIR__ . '/auth/JWTManager.php';

// Initialize variables
$error = null;
$success = null;

// Load SMTP configuration
$smtpConfig = loadSmtpConfig();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        logSecurityEvent(null, 'csrf_failure', [
            'page' => 'forgot_password',
            'ip' => $_SERVER['REMOTE_ADDR']
        ]);
        $error = 'Invalid request. Please try again.';
    } else {
        // Sanitize and validate email input
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            logSecurityEvent(null, 'invalid_email_format', ['email' => $_POST['email']]);
            $error = 'Invalid email address format.';
        } else {
            try {
                // Rate limiting: Check if the member has exceeded the reset request limit
                $stmt = $pdo->prepare("
                    SELECT COUNT(*) FROM password_resets 
                    WHERE email = ? AND created_at > NOW() - INTERVAL 1 HOUR
                ");
                $stmt->execute([$email]);
                $count = $stmt->fetchColumn();

                if ($count > 3) {
                    logSecurityEvent(null, 'password_reset_rate_limit', ['email' => $email]);
                    $error = 'Too many password reset requests. Please try again later.';
                } else {
                    // Check if the email exists in the member database
                    $stmt = $pdo->prepare("
                        SELECT a.member_id, a.username, m.first_name, m.last_name 
                        FROM member_portal_accounts a
                        JOIN members m ON m.id = a.member_id
                        WHERE a.email = ?
                    ");
                    $stmt->execute([$email]);
                    $member = $stmt->fetch();

                    if ($member) {
                        // Generate a secure token and expiry time
                        $token = bin2hex(random_bytes(32));
                        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));

                        // Save the token and expiry to the database
                        $stmt = $pdo->prepare("
                            INSERT INTO password_resets (email, token, expires_at) 
                            VALUES (?, ?, ?)
                        ");
                        $stmt->execute([$email, $token, $expiry]);

                        // Clean up expired tokens
                        $pdo->exec("DELETE FROM password_resets WHERE expires_at < NOW()");

                        // Generate the password reset link
                        $resetLink = 'https://' . $_SERVER['HTTP_HOST'] . '/reset_password.php?token=' . $token;

                        // Send email with reset link and username
                        if (sendPasswordResetEmail($email, $member['first_name'], $member['username'], $resetLink, $smtpConfig)) {
                            logSecurityEvent($member['member_id'], 'password_reset_requested', [
                                'email' => $email,
                                'token' => $token,
                                'ip' => $_SERVER['REMOTE_ADDR']
                            ]);
                            
                            $success = 'If this email is registered with our member portal, you will receive a reset link shortly.';
                        } else {
                            logSecurityEvent($member['member_id'], 'password_reset_email_failed', [
                                'email' => $email,
                                'error' => 'Email sending failed'
                            ]);
                            $error = 'Failed to send reset email. Please try again.';
                        }
                    } else {
                        logSecurityEvent(null, 'password_reset_unknown_email', ['email' => $email]);
                        // Show generic message whether email exists or not (security best practice)
                        $success = 'If this email is registered with our member portal, you will receive a reset link shortly.';
                    }
                }
            } catch (Exception $e) {
                logSecurityEvent(null, 'system_error', [
                    'error' => $e->getMessage(),
                    'page' => 'forgot_password'
                ]);
                $error = 'An error occurred. Please try again later.';
            }
        }
    }
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/**
 * Send a password reset email using PHPMailer.
 *
 * @param string $email The recipient's email address.
 * @param string $firstName The member's first name.
 * @param string $username The member's username.
 * @param string $link The password reset link.
 * @param array $config SMTP configuration.
 * @return bool True if email was sent successfully, false otherwise
 */
function sendPasswordResetEmail($email, $firstName, $username, $link, $config) {
    // Check if SMTP configuration is valid
    if (empty($config) || !is_array($config)) {
        error_log("Invalid SMTP configuration array");
        return false;
    }
    
    // Map the configuration keys to match what PHPMailer expects
    $smtpHost = $config['smtp_host'] ?? $config['host'] ?? '';
    $smtpUsername = $config['smtp_username'] ?? $config['username'] ?? $config['from_address'] ?? '';
    $smtpPassword = $config['smtp_password'] ?? $config['password'] ?? '';
    $smtpEncryption = $config['smtp_encryption'] ?? $config['encryption'] ?? 'tls';
    $smtpPort = $config['smtp_port'] ?? $config['port'] ?? 587;
    $fromAddress = $config['from_address'] ?? $config['smtp_username'] ?? '';
    $fromName = $config['from_name'] ?? 'Member Portal';
    
    // Validate required configuration
    if (empty($smtpHost) || empty($smtpUsername) || empty($smtpPassword)) {
        error_log("Missing required SMTP configuration: host=" . $smtpHost . ", username=" . $smtpUsername);
        return false;
    }

    require_once __DIR__ . '/./vendor/autoload.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        $mail->SMTPSecure = $smtpEncryption;
        $mail->Port = $smtpPort;
        
        // Enable debugging if needed
        // $mail->SMTPDebug = 2;
        // $mail->Debugoutput = function($str, $level) {
        //     error_log("SMTP: $str");
        // };

        // Email content
        $mail->setFrom($fromAddress, $fromName);
        $mail->addAddress($email);
        $mail->addReplyTo($fromAddress, 'Member Support');

        // Current time for email footer
        $currentTime = date('Y-m-d H:i:s');

        // Load email template
        $emailTemplate = <<<HTML
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #2563eb; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background-color: #f9f9f9; }
                .button { display: inline-block; padding: 12px 24px; background-color: #2563eb; color: white; text-decoration: none; border-radius: 5px; }
                .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>Member Portal Password Reset</h2>
                </div>
                <div class="content">
                    <p>Hello {$firstName},</p>
                    <p>You requested to reset your password for the Member Portal. Click the button below to proceed:</p>
                    <p style="text-align: center;">
                        <a href="{$link}" class="button">Reset Password</a>
                    </p>
                    <p>This link will expire in 1 hour for security reasons.</p>
                    <p>If you did not request this password reset, please ignore this email or contact our support team immediately.</p>
                    <p>Your username: <strong>{$username}</strong></p>
                </div>
                <div class="footer">
                    <p>Request IP: {$_SERVER['REMOTE_ADDR']}<br>
                    Request Time: {$currentTime}</p>
                    <p>&copy; " . date('Y') . " Baptist Convention SACCO LTD. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        HTML;

        $plainText = "Hello {$firstName},\n\nYou requested to reset your password for the Member Portal. Visit this link to proceed:\n{$link}\n\nThis link will expire in 1 hour for security reasons.\n\nIf you did not request this password reset, please ignore this email or contact our support team immediately.\n\nYour username: {$username}\n\nRequest IP: {$_SERVER['REMOTE_ADDR']}\nRequest Time: {$currentTime}";

        $mail->isHTML(true);
        $mail->Subject = 'Member Portal Password Reset Request';
        $mail->Body = $emailTemplate;
        $mail->AltBody = $plainText;

        // Send email
        return $mail->send();
    } catch (Exception $e) {
        error_log("Email send failed: " . $mail->ErrorInfo);
        return false;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Forgot Password | Member Portal</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        :root {
            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --secondary: #64748b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --light: #f8fafc;
            --dark: #1e293b;
            --gray: #94a3b8;
            --border: #e2e8f0;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        .forgot-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 440px;
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .forgot-header {
            background: var(--primary);
            color: white;
            padding: 24px 32px;
            text-align: center;
            position: relative;
        }
        
        .security-indicator {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        .forgot-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .forgot-header p {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .forgot-body {
            padding: 32px;
        }
        
        .logo {
            margin-bottom: 24px;
            text-align: center;
        }
        
        .logo img {
            height: 60px;
        }
        
        .form-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--dark);
        }
        
        .input-group {
            position: relative;
        }
        
        input[type="email"] {
            width: 100%;
            padding: 12px 16px;
            padding-right: 40px;
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.2s;
        }
        
        input[type="email"]:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            outline: none;
        }
        
        .input-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
        }
        
        .submit-btn {
            width: 100%;
            padding: 14px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
        }
        
        .submit-btn:hover {
            background-color: var(--primary-dark);
        }
        
        .submit-btn:active {
            transform: translateY(1px);
        }
        
        .submit-btn.loading {
            opacity: 0.8;
            pointer-events: none;
        }
        
        .spinner {
            width: 18px;
            height: 18px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
        
        .error-message {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid var(--danger);
        }
        
        .success-message {
            background-color: rgba(16, 185, 129, 0.1);
            color: var(--success);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid var(--success);
        }
        
        .login-footer {
            text-align: center;
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid var(--border);
            font-size: 14px;
            color: var(--secondary);
        }
        
        .login-footer a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .privacy-notice {
            font-size: 12px;
            color: var(--secondary);
            margin-top: 16px;
            text-align: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @media (max-width: 480px) {
            .forgot-container {
                border-radius: 12px;
            }
            
            .forgot-header {
                padding: 20px;
            }
            
            .forgot-body {
                padding: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="forgot-container">
        <div class="forgot-header">
            <div class="security-indicator">
                <i class="fas fa-lock"></i>
                <span>Secure</span>
            </div>
            <h1>Reset Your Password</h1>
            <p>Enter your email to receive a reset link</p>
        </div>
        
        <div class="forgot-body">
            <div class="logo">
                <!-- Replace with your SACCO logo -->
                <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect width="60" height="60" rx="12" fill="#2563eb"/>
                    <path d="M20 30L26 36L40 22" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            
            <?php if (!empty($error)): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo htmlspecialchars($error); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($success)): ?>
                <div class="success-message">
                    <i class="fas fa-check-circle"></i>
                    <span><?php echo htmlspecialchars($success); ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="forgotForm">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

                <div class="form-group">
                    <label for="email">Email Address</label>
                    <div class="input-group">
                        <input type="email" id="email" name="email" required autocomplete="email" placeholder="Enter your registered email address">
                        <i class="fas fa-envelope input-icon"></i>
                    </div>
                </div>
                
                <button type="submit" class="submit-btn" id="submitButton">
                    <span>Send Reset Link</span>
                    <div class="spinner" style="display: none;"></div>
                </button>
                
                <div class="privacy-notice">
                    <i class="fas fa-shield-alt"></i>
                    Your information is secure. We'll email you a reset link.
                </div>
            </form>
            
            <div class="login-footer">
                <p>Remember your password? <a href="login.php">Back to Login</a></p>
                <p>Need help? <a href="contact.php">Contact Support</a></p>
                <p>&copy; <?php echo date('Y'); ?> Baptist Convention SACCO LTD. All rights reserved.</p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const forgotForm = document.getElementById('forgotForm');
            const submitButton = document.getElementById('submitButton');
            
            // Form submission
            forgotForm.addEventListener('submit', function(e) {
                // Basic validation
                const email = document.getElementById('email').value.trim();
                
                if (!email) {
                    e.preventDefault();
                    forgotForm.classList.add('shake');
                    setTimeout(() => {
                        forgotForm.classList.remove('shake');
                    }, 500);
                    return;
                }
                
                const spinner = submitButton.querySelector('.spinner');
                const buttonText = submitButton.querySelector('span');
                
                // Show loading state
                spinner.style.display = 'block';
                buttonText.textContent = 'Sending...';
                submitButton.classList.add('loading');
            });
            
            // Auto-focus on email field
            document.getElementById('email').focus();
        });
    </script>
</body>
</html>