<?php
// submit-contact.php - AJAX PROCESSOR ONLY
session_start();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include database configuration
require_once 'database.php';

// Initialize response array
$response = ['success' => false, 'message' => '', 'errors' => []];

// Check if form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Always output JSON
    header('Content-Type: application/json');
    
    // Validate CSRF token
    $csrf_token = $_POST['csrf_token'] ?? '';
    if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $csrf_token)) {
        $response['message'] = 'Security token invalid. Please refresh the page and try again.';
        echo json_encode($response);
        exit;
    }

    // Honeypot check (anti-bot)
    if (!empty($_POST['website'])) {
        $response['success'] = true;
        $response['message'] = 'Thank you for your submission!';
        echo json_encode($response);
        exit;
    }

    // Sanitize and validate inputs
    $errors = [];
    
    // Get and sanitize all inputs
    $full_name = sanitizeInput($_POST['full_name'] ?? '');
    $email = sanitizeInput($_POST['email'] ?? '');
    $phone = sanitizeInput($_POST['phone_number'] ?? '');
    $inquiry_type = sanitizeInput($_POST['inquiry_type'] ?? '');
    $message = sanitizeInput($_POST['message'] ?? '');
    $urgency = sanitizeInput($_POST['urgency'] ?? 'normal');
    $case_reference = sanitizeInput($_POST['case_reference'] ?? '');
    
    // Validate required fields
    if (empty($full_name)) {
        $errors[] = 'Full name is required';
    }
    
    if (empty($email)) {
        $errors[] = 'Email is required';
    } elseif (!validateEmail($email)) {
        $errors[] = 'Invalid email format';
    }
    
    if (empty($phone)) {
        $errors[] = 'Phone number is required';
    } elseif (!validatePhone($phone)) {
        $errors[] = 'Invalid phone number format';
    }
    
    if (empty($inquiry_type)) {
        $errors[] = 'Please select inquiry type';
    }
    
    if (empty($message)) {
        $errors[] = 'Please describe your situation';
    }
    
    // Check consent checkboxes
    if (empty($_POST['confidentiality'])) {
        $errors[] = 'You must agree to confidentiality terms';
    }
    
    if (empty($_POST['consent'])) {
        $errors[] = 'You must give consent to process your information';
    }
    
    // If there are errors, return them
    if (!empty($errors)) {
        $response['errors'] = $errors;
        $response['message'] = 'Please correct the errors below';
        echo json_encode($response);
        exit;
    }
    
    try {
        // Generate case reference if not provided
        if (empty($case_reference)) {
            $case_reference = generateCaseRef($inquiry_type);
        }
        
        // Get priority based on urgency
        $priority = getPriority($urgency);
        
        // Prepare SQL statement
        $sql = "INSERT INTO contacts (
            full_name, email, phone_number, inquiry_type, 
            case_reference, urgency, message, confidentiality_agreed, 
            consent_given, ip_address, user_agent, status, priority
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?)";
        
        $stmt = $pdo->prepare($sql);
        
        // Execute with values
        $stmt->execute([
            $full_name,
            $email,
            $phone,
            $inquiry_type,
            $case_reference,
            $urgency,
            $message,
            !empty($_POST['confidentiality']),
            !empty($_POST['consent']),
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? '',
            $priority
        ]);
        
        // Get the last inserted ID
        $contactId = $pdo->lastInsertId();
        
        // Log the activity
        logActivity('contact_submitted', "New contact form submission from $email", $contactId);
        
        // Generate new CSRF token for next form submission
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        
        // Send success response
        $response['success'] = true;
        $response['message'] = "Thank you for your submission! Your case reference is: <strong>$case_reference</strong>";
        $response['case_ref'] = $case_reference;
        
    } catch (PDOException $e) {
        error_log("Database error: " . $e->getMessage());
        $response['message'] = 'An error occurred while processing your submission. Please try again.';
        $response['debug'] = $e->getMessage(); // Remove this in production
    }
    
    echo json_encode($response);
    exit;
}

// If not POST request, redirect to contact page
header('Location: contact.php');
exit;
?>