<?php
require_once '../config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

try {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!is_array($data)) {
        $data = $_POST;
    }

    // Validate required fields
    $full_name = trim($data['full_name'] ?? '');
    $email = trim($data['email'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $message = trim($data['message'] ?? '');
    $property_id = isset($data['property_id']) ? (int)$data['property_id'] : 0;

    // Validation
    if (empty($full_name) || strlen($full_name) < 2) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Please enter a valid name']);
        exit;
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Please enter a valid email']);
        exit;
    }

    if (empty($phone) || strlen($phone) < 7) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Please enter a valid phone number']);
        exit;
    }

    if (empty($message) || strlen($message) < 10) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Message must be at least 10 characters']);
        exit;
    }

    if ($property_id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid property ID']);
        exit;
    }

    // Ensure inquiries table exists and has required columns
    $conn->query("CREATE TABLE IF NOT EXISTS inquiries (
        id INT AUTO_INCREMENT PRIMARY KEY,
        customer_id INT,
        property_id INT,
        assigned_to INT,
        broker_id INT,
        status VARCHAR(50) DEFAULT 'pending',
        message TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");

    // Add missing columns if they don't exist
    $columns_to_add = [
        'customer_name' => "ALTER TABLE inquiries ADD COLUMN customer_name VARCHAR(255) AFTER customer_id",
        'customer_email' => "ALTER TABLE inquiries ADD COLUMN customer_email VARCHAR(255) AFTER customer_name",
        'customer_phone' => "ALTER TABLE inquiries ADD COLUMN customer_phone VARCHAR(20) AFTER customer_email"
    ];

    foreach ($columns_to_add as $col_name => $alter_query) {
        $check = $conn->query("SHOW COLUMNS FROM inquiries LIKE '$col_name'");
        if (!$check || $check->num_rows === 0) {
            @$conn->query($alter_query);
        }
    }

    // Add indexes if needed
    @$conn->query("ALTER TABLE inquiries ADD INDEX idx_property_id (property_id)");
    @$conn->query("ALTER TABLE inquiries ADD INDEX idx_status (status)");
    @$conn->query("ALTER TABLE inquiries ADD INDEX idx_created_at (created_at)");

    // Get customer ID from session if logged in
    $customer_id = isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'customer' ? (int)$_SESSION['user_id'] : NULL;

    // Prepare insert statement
    $stmt = $conn->prepare("
        INSERT INTO inquiries (
            customer_id, customer_name, customer_email, customer_phone, 
            property_id, message
        ) VALUES (?, ?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param(
        'issssi',
        $customer_id,
        $full_name,
        $email,
        $phone,
        $property_id,
        $message
    );

    if (!$stmt->execute()) {
        throw new Exception('Failed to save inquiry');
    }

    $inquiry_id = $stmt->insert_id;
    $stmt->close();

    echo json_encode([
        'success' => true,
        'message' => 'Thank you for your inquiry! We will contact you soon.',
        'inquiry_id' => $inquiry_id
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
