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

// Start output buffering
ob_start();

// Include database configuration
require_once __DIR__ . '/admin/includes/config.php';

// Initialize response array
$response = [
    'success' => false,
    'message' => 'An error occurred. Please try again.'
];

// Function to log errors
function logError($message) {
    $logFile = __DIR__ . '/error_log.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Log the POST data for debugging
    logError('Form submitted with data: ' . print_r($_POST, true));
    
    // Sanitize inputs
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    $inquiry_type = filter_input(INPUT_POST, 'inquiry_type', FILTER_SANITIZE_STRING);
    $location = filter_input(INPUT_POST, 'location', FILTER_SANITIZE_STRING);
    $property_type = filter_input(INPUT_POST, 'property_type', FILTER_SANITIZE_STRING);
    
    // Basic validation
    $required = [
        'name' => 'Name',
        'email' => 'Email',
        'phone' => 'Phone',
        'inquiry_type' => 'Inquiry Type',
        'location' => 'Location',
        'property_type' => 'Property Type'
    ];
    
    $errors = [];
    foreach ($required as $field => $label) {
        if (empty($_POST[$field])) {
            $errors[] = "$label is required";
        }
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email format';
    }
    
    if (!empty($errors)) {
        $response['message'] = implode('<br>', $errors);
    } else {
        // Prepare an insert statement
        $sql = "INSERT INTO inquiries 
                (inquiry_type, name, phone, email, location, property_type, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = $conn->prepare($sql)) {
            logError('SQL prepared successfully');
            
            // Bind variables to the prepared statement
            $stmt->bind_param(
                "ssssss", 
                $inquiry_type,
                $name,
                $phone,
                $email,
                $location,
                $property_type
            );
            
            // Attempt to execute the prepared statement
            if ($stmt->execute()) {
                logError('Query executed successfully');
                $response = [
                    'success' => true,
                    'message' => 'Your visit request has been submitted successfully! We will get back to you soon.'
                ];
            } else {
                $errorMsg = 'Database execution error: ' . $stmt->error;
                logError($errorMsg);
                $response['message'] = 'Oops! Something went wrong. Please try again later.';
                $response['error'] = $errorMsg;
            }
            
            // Close statement
            $stmt->close();
        } else {
            $errorMsg = 'Database preparation error: ' . $conn->error;
            logError($errorMsg);
            $response['message'] = 'Database error. Please try again later.';
            $response['error'] = $errorMsg;
        }
    }
} else {
    $response['message'] = 'Invalid request method';
}

// Close connection
if (isset($conn)) {
    $conn->close();
}

// Get any output that might have been generated
$output = ob_get_clean();

// Log any unexpected output
if (!empty($output)) {
    logError('Unexpected output: ' . $output);
}

// Return JSON response
header('Content-Type: application/json');
// Add debug info if in development
if (isset($_GET['debug'])) {
    $response['debug'] = [
        'post_data' => $_POST,
        'sql' => $sql ?? null
    ];
}
echo json_encode($response);
?>