<?php
// File: request_password_reset.php
// Request password reset - send verification code

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, User-Agent');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';
require_once 'send_email.php';

// API Security Configuration
define('API_KEY', 'ensi_app_2025_secure_key_v1');
define('ALLOWED_USER_AGENTS', [
    'Dart/',
    'ensi-flutter-app',
]);

// Helper: Validate API access
function validateApiAccess() {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid API key.',
            'status_code' => 403
        ]);
        exit;
    }
    
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isValidUserAgent = false;
    
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $isValidUserAgent = true;
            break;
        }
    }
    
    if (!$isValidUserAgent) {
        http_response_code(403);
        echo json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid client.',
            'status_code' => 403
        ]);
        exit;
    }
    
    error_log("Password Reset Request API Access: " . $userAgent . " from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
}

validateApiAccess();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

$input = getJsonInput();

// Validate input
if (empty($input['email'])) {
    sendResponse(false, 'Email is required');
}

$email = sanitizeInput($input['email']);

// Validate email format
if (!validateEmail($email)) {
    sendResponse(false, 'Invalid email format');
}

try {
    $conn = getDBConnection();
    if (!$conn) {
        sendResponse(false, 'Database connection failed', null, 500);
    }
    
    // Check if user exists and is verified
    $stmt = $conn->prepare("SELECT id, is_verified, is_deleted, user_name FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if (!$user) {
        // Don't reveal if email exists or not (security)
        sendResponse(true, 'If the email exists, a verification code has been sent.');
        exit();
    }
    
    if ($user['is_deleted'] == 1) {
        sendResponse(false, 'This account has been deleted.');
    }
    
    if ($user['is_verified'] != 1 || !$user['user_name']) {
        sendResponse(false, 'Please complete your registration first.');
    }
    
    // Check rate limiting
    $stmt = $conn->prepare("
        SELECT COUNT(*) as count 
        FROM verification_codes 
        WHERE email = ? 
        AND purpose = 'password_reset' 
        AND created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
    ");
    $stmt->execute([$email]);
    $result = $stmt->fetch();
    
    if ($result['count'] >= 3) {
        sendResponse(false, 'Too many requests. Please wait 10 minutes before requesting another code.');
    }
    
    // Generate verification code
    $code = generateVerificationCode();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));
    
    // Delete old unused codes
    $stmt = $conn->prepare("DELETE FROM verification_codes WHERE email = ? AND purpose = 'password_reset' AND is_used = 0");
    $stmt->execute([$email]);
    
    // Insert new verification code
    $stmt = $conn->prepare("INSERT INTO verification_codes (email, code, purpose, expires_at) VALUES (?, ?, 'password_reset', ?)");
    $stmt->execute([$email, $code, $expiresAt]);
    
    // Send email
    $subject = "ensi.lk - Password Reset Code";
    $bodyHTML = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: linear-gradient(135deg, #4ECDC4 0%, #FFC947 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { background: #f8f9fa; padding: 30px; border-radius: 0 0 10px 10px; }
                .code { font-size: 32px; font-weight: bold; color: #4ECDC4; text-align: center; letter-spacing: 10px; padding: 20px; background: white; border-radius: 10px; margin: 20px 0; }
                .footer { text-align: center; color: #636E72; padding: 20px; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Password Reset Request 🔒</h1>
                </div>
                <div class='content'>
                    <h2>Reset Your Password</h2>
                    <p>We received a request to reset your password. Use the following verification code:</p>
                    <div class='code'>$code</div>
                    <p><strong>This code will expire in 15 minutes.</strong></p>
                    <p>If you didn't request a password reset, please ignore this email and your password will remain unchanged.</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2025 ensi.lk - Master English with Fun!</p>
                </div>
            </div>
        </body>
        </html>
    ";
    
    $emailSent = sendIdeasEmail($email, $subject, $bodyHTML);
    
    if ($emailSent) {
        logActivity("Password reset code sent to: $email");
        sendResponse(true, 'Verification code sent to your email.');
    } else {
        logActivity("Failed to send password reset email to: $email");
        sendResponse(false, 'Failed to send verification email. Please try again later.', null, 500);
    }
    
} catch (Exception $e) {
    logActivity("Password reset request error: " . $e->getMessage());
    sendResponse(false, 'An error occurred. Please try again later.', null, 500);
}
?>
