<?php
/**
 * Secure form processor with all security measures
 */

// Load configuration and services
require_once 'config_loader.php';
require_once 'Logger.php';

$autoloadPath = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoloadPath)) {
    require_once $autoloadPath;
} else {
    Logger::error('Composer autoload not found', ['path' => $autoloadPath]);
    throw new Exception('Server configuration error. Please try again later.');
}

require_once 'RecaptchaService.php';
require_once 'EmailService.php';
require_once 'CsrfProtection.php';
require_once 'RateLimiter.php';
require_once 'InputSanitizer.php';
require_once 'csp_config.php';
require_once 'Database.php';
require_once 'SubmissionTracker.php';

// Set headers
header('Content-Type: application/json');
send_security_headers();

// Start session for CSRF protection
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

try {
    // Check request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }
    
    // Rate limiting check
    if (!RateLimiter::isAllowed()) {
        $remainingTime = RateLimiter::getTimeUntilReset();
        throw new Exception('Too many requests. Please try again in ' . ceil($remainingTime) . ' seconds.');
    }
    
    // CSRF token validation
    $csrfToken = $_POST['csrf_token'] ?? '';
    if (!CsrfProtection::validateToken($csrfToken)) {
        Logger::warning('CSRF token validation failed', [
            'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ]);
        throw new Exception('Security token expired. Please refresh the page and try again.');
    }
    
    // reCAPTCHA verification
    $recaptchaToken = $_POST['g-recaptcha-response'] ?? '';
    $recaptchaService = new RecaptchaService();
    $recaptchaResult = $recaptchaService->verifyToken($recaptchaToken);
    
    if (!$recaptchaResult['success']) {
        throw new Exception($recaptchaResult['message']);
    }
    
    // Sanitize and validate input
    $name = InputSanitizer::sanitizeName($_POST['name'] ?? '');
    $email = InputSanitizer::sanitizeEmail($_POST['email'] ?? '');
    $message = InputSanitizer::sanitizeMessage($_POST['message'] ?? '');
    
    // Validate required fields
    $requiredErrors = InputSanitizer::validateRequired([
        'name' => $name,
        'email' => $email,
        'message' => $message
    ], ['name', 'email', 'message']);
    
    if (!empty($requiredErrors)) {
        throw new Exception('Please fill in all required fields');
    }
    
    // Validate email format
    if (!InputSanitizer::validateEmail($email)) {
        throw new Exception('Please enter a valid email address');
    }
    
    // Validate field lengths
    $lengthErrors = InputSanitizer::validateLengths([
        'name' => $name,
        'email' => $email,
        'message' => $message
    ], [
        'name' => 100,
        'email' => 255,
        'message' => 5000
    ]);
    
    if (!empty($lengthErrors)) {
        throw new Exception(implode('. ', $lengthErrors));
    }
    
    // Initialize submission tracker
    $submissionTracker = new SubmissionTracker();
    
    // Check if IP is blocked
    $clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
    if ($submissionTracker->isIpBlocked($clientIp)) {
        throw new Exception('Access denied. Your IP address has been blocked due to suspicious activity.');
    }
    
    // Get client information for tracking
    $submissionData = [
        'name' => $name,
        'email' => $email,
        'message' => $message,
        'ip_address' => $clientIp,
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'referrer' => $_SERVER['HTTP_REFERER'] ?? ''
    ];
    
    // Save submission to database
    $submissionId = $submissionTracker->saveSubmission($submissionData);
    
    // Send email
    $emailService = new EmailService();
    $emailSent = $emailService->sendContactForm($name, $email, $message);
    
    if ($emailSent) {
        // Update submission status and mark email as sent
        $submissionTracker->updateSubmissionStatus($submissionId, 'processed', 'Email sent successfully');
        $submissionTracker->markEmailSent($submissionId, 'notification');
        
        Logger::info('Contact form submitted successfully', [
            'name' => $name,
            'email' => $email,
            'recaptcha_score' => $recaptchaResult['score']
        ]);
        
        // Clear CSRF token after successful submission
        CsrfProtection::clearToken();
        
        echo json_encode([
            'success' => true,
            'message' => 'Thank you for your message! We will get back to you soon.'
        ]);
    } else {
        // Update submission status to error
        $submissionTracker->updateSubmissionStatus($submissionId, 'error', 'Email sending failed');
        $submissionTracker->logEmailFailure($submissionId, 'notification', 'Email service failed');
        
        Logger::error('Failed to send contact form email', [
            'name' => $name,
            'email' => $email,
            'submission_id' => $submissionId
        ]);
        
        throw new Exception('Failed to send message. Please try again later.');
    }
    
} catch (Exception $e) {
    Logger::error('Form submission error', [
        'error' => $e->getMessage(),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
    ]);
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
