<?php
require_once '../config.php';

// Enforce Rate Limiting (Max 5 attempts per minute per IP)
checkRateLimit('forgot', 5, 60);

$data = json_decode(file_get_contents("php://input"), true);

if (empty($data['email'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Email or phone number is required."]);
    exit();
}

$loginInput = sanitizeInput($data['email']);

try {
    $db = getDBConnection();

    // Check if user exists
    $stmt = $db->prepare("SELECT email FROM users WHERE email = ? OR phone = ?");
    $stmt->execute([$loginInput, $loginInput]);
    $user = $stmt->fetch();

    if (!$user) {
        http_response_code(404);
        echo json_encode(["status" => "error", "message" => "No account registered with this email or phone number."]);
        exit();
    }

    $email = $user['email'];

    // Generate reset code
    $otp_code = strval(rand(100000, 999999));
    $expires_at = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    // Insert OTP code
    $stmt = $db->prepare("INSERT INTO user_otps (email, code, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$email, $otp_code, $expires_at]);

    // Dispatch premium HTML password recovery email
    $emailSubject = "Reset Your Think Rich Naija Password";
    $emailBody = "
        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 10px;'>
            <div style='text-align: center; margin-bottom: 20px;'>
                <h1 style='color: #009247; margin: 0;'>Think Rich Naija</h1>
            </div>
            <h2 style='color: #2d3748;'>Password Recovery Request</h2>
            <p style='color: #4a5568; line-height: 1.6;'>We received a request to reset your account password. Use the 6-digit OTP code below to complete your recovery process:</p>
            <div style='background-color: #f7fafc; padding: 15px; text-align: center; border-radius: 8px; margin: 24px 0;'>
                <span style='font-size: 32px; font-weight: bold; letter-spacing: 6px; color: #009247;'>" . $otp_code . "</span>
            </div>
            <p style='color: #e53e3e; font-weight: bold; font-size: 13px;'>Security Alert: Do NOT share this code with anyone. Our support team will never ask for this code.</p>
            <p style='color: #718096; font-size: 12px; line-height: 1.4; margin-top: 10px;'>This recovery code is valid for exactly 10 minutes. If you did not make this request, your account is secure and you can safely ignore this email.</p>
            <div style='border-top: 1px solid #edf2f7; margin-top: 24px; padding-top: 16px; text-align: center; color: #a0aec0; font-size: 11px;'>
                &copy; " . date('Y') . " Think Rich Naija. All rights reserved.
            </div>
        </div>
    ";

    sendEmail($email, $emailSubject, $emailBody);

    echo json_encode([
        "status" => "success",
        "message" => "Password reset code sent successfully.",
        "email" => $email,
        "debug_otp" => $otp_code
    ]);

} catch(PDOException $e) {
    logSecurityError("Forgot Password Database failure: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Password recovery failed. Please try again."]);
}
?>
