<?php
/**
 * Contact Form Processing Endpoint
 * Secure AJAX handler for contact form submissions
 */

// Security headers
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Allow email handler access
define('EMAIL_HANDLER_ALLOWED', true);

// Load dependencies
require_once __DIR__ . '/inc/utils.php';
require_once __DIR__ . '/inc/email.php';

// Handle CSRF token request
if (isset($_GET['action']) && $_GET['action'] === 'csrf') {
    $token = generateCSRFToken();
    echo json_encode(['token' => $token], JSON_UNESCAPED_UNICODE);
    exit;
}

// Mail capability diagnostics (no CSRF required; read-only by default)
if (isset($_GET['action']) && $_GET['action'] === 'mailcheck') {
    $supportsMail = function_exists('mail');
    $disabled = ini_get('disable_functions');
    $disabledList = array_filter(array_map('trim', explode(',', (string)$disabled)));
    $info = [
        'supports_mail' => $supportsMail,
        'disabled_functions' => $disabledList,
        'ini' => [
            'sendmail_path' => ini_get('sendmail_path'),
            'SMTP' => ini_get('SMTP'),
            'smtp_port' => ini_get('smtp_port'),
            'sendmail_from' => ini_get('sendmail_from'),
        ],
    ];
    // Optional live test when confirm=1 (may send a real email)
    if (!empty($_GET['confirm']) && $_GET['confirm'] === '1' && $supportsMail) {
        $to = 'ahmed123hosssam2001@gmail.com';
        $subject = '[Diag] Mail test from Altoukhi site ' . date('Y-m-d H:i:s');
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/plain; charset=UTF-8',
            'From: Altoukhi MailCheck <noreply@altoukhi.com>',
            'X-Mailer: PHP/' . PHP_VERSION,
        ];
        $result = @mail($to, $subject, "This is a diagnostic test email.", implode("\r\n", $headers));
        $info['live_test'] = [ 'attempted' => true, 'success' => (bool)$result ];
    } else {
        $info['live_test'] = [ 'attempted' => false ];
    }
    echo json_encode($info, JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    // Initialize secure email handler
    $emailHandler = new SecureEmailHandler('ahmed123hosssam2001@gmail.com');
    
    // Process the contact form
    $result = $emailHandler->processContactForm();
    
    // Return JSON response
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    // Log error and return generic error message
    error_log('Contact form error: ' . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في النظام. يرجى المحاولة مرة أخرى لاحقاً.'
    ], JSON_UNESCAPED_UNICODE);
}
?>
