<?php
/**
 * Process Enquiry Form Submissions
 * Saves quotes/messages to the database and redirects back.
 */

// 1. Database Connection
require_once '../config/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 2. Data Collection & Sanitization
    $first_name = filter_input(INPUT_POST, 'first_name', FILTER_SANITIZE_SPECIAL_CHARS);
    $last_name  = filter_input(INPUT_POST, 'last_name', FILTER_SANITIZE_SPECIAL_CHARS);
    
    if (!empty($first_name)) {
        $full_name = trim($first_name . ' ' . ($last_name ?? ''));
    } else {
        $full_name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
    }

    $phone     = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_SPECIAL_CHARS);
    $email     = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $interest  = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_SPECIAL_CHARS);
    $message   = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_SPECIAL_CHARS);
    $location  = filter_input(INPUT_POST, 'location', FILTER_SANITIZE_SPECIAL_CHARS);
    
    // If location is provided, append it to the message or handle it separately if a column existed
    // Since 'location' is not in our current enquiries table, we'll prefix it to the message
    if (!empty($location)) {
        $message = "Project Location: " . $location . "\n\n" . $message;
    }

    // 3. Validation
    if (empty($full_name) || empty($phone)) {
        header("Location: ../../get-a-free-quote.php?error=missing_fields");
        exit;
    }

    try {
        // 4. Database Insertion
        $sql = "INSERT INTO enquiries (full_name, phone, email, interest, message, status) VALUES (?, ?, ?, ?, ?, 'pending')";
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$full_name, $phone, $email, $interest, $message]);

        if (!$result) {
            error_log("Enquiry Insert Failed: " . print_r($stmt->errorInfo(), true));
            header("Location: ../../get-a-free-quote.php?error=insert_failed");
            exit;
        }

        // 5. Redirect on Success
        if (isset($_POST['source']) && $_POST['source'] == 'quote_page') {
            header("Location: ../../get-a-free-quote.php?success=1");
        } else {
            header("Location: ../../contact-us.php?success=1");
        }
        exit;
        
    } catch (PDOException $e) {
        // 6. Handle Errors
        error_log("Enquiry Exception: " . $e->getMessage());
        header("Location: ../../get-a-free-quote.php?error=exception");
        exit;
    }
} else {
    // Direct access not allowed
    header("Location: ../../index.php");
    exit;
}
?>
