<?php
/**
 * Process Forgot Password Request
 * Generate and send OTP via email
 */
require_once 'config.php';
require_once 'auth-helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: forgot-password.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$error = '';
$success = false;

// Validate email
if (empty($email)) {
    $error = 'Please enter your email address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Please enter a valid email address';
} else {
    // Check if user exists
    $user = getUserByEmail($conn, $email);
    
    if (!$user) {
        // For security, don't reveal if email exists or not
        $error = 'If an account exists with this email, you will receive a password reset link shortly';
        $success = true; // Show success message but don't actually send OTP
    } else {
        // Generate OTP
        $otp = generateOTP();
        
        // Store OTP in database
        $storeResult = storeOTP($conn, $email, $otp);
        
        if ($storeResult['success']) {
            // Send OTP via email
            $userName = trim($user['firstname'] . ' ' . $user['lastname']);
            $sendResult = sendOTPEmail($email, $otp, $userName);
            
            if ($sendResult['success']) {
                $_SESSION['reset_email'] = $email;
                $_SESSION['reset_initiated'] = true;
                
                $success = true;
                
                // Redirect to OTP verification page
                header('Location: verify-otp.php?email=' . urlencode($email));
                exit;
            } else {
                $error = 'Unable to send OTP. Please try again later.';
            }
        } else {
            $error = 'An error occurred. Please try again later.';
        }
    }
}

// Redirect back with message
if ($success) {
    header('Location: forgot-password.php?success=' . urlencode('If an account exists with this email, check your inbox for the reset code'));
} else {
    header('Location: forgot-password.php?error=' . urlencode($error));
}
exit;
?>
