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

$sessionRole = $_SESSION['user_role'] ?? ($_SESSION['role'] ?? '');
// Check if user is logged in as customer
if (!isset($_SESSION['user_id']) || $sessionRole !== 'customer') {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$customer_id = $_SESSION['user_id'];
$property_id = intval($input['property_id'] ?? 0);
$message = trim($input['message'] ?? '');

if ($property_id <= 0 || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

try {
    // Ensure inquiries table has required columns
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS customer_id INT AFTER id");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS property_id INT AFTER customer_id");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS assigned_to INT AFTER property_id");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS broker_id INT AFTER assigned_to");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS status VARCHAR(50) DEFAULT 'pending' AFTER broker_id");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS message TEXT AFTER status");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
    $conn->query("ALTER TABLE inquiries ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");

    // Ensure properties table has agent_id column
    $conn->query("ALTER TABLE properties ADD COLUMN IF NOT EXISTS agent_id INT AFTER broker_id");

    // Resolve a valid broker user id for inquiries.broker_id FK -> users.id.
    // Some installs store properties.broker_id as users.id, others as brokers.id.
    $prop_stmt = $conn->prepare("
        SELECT
            p.broker_id AS property_broker_id,
            u_direct.id AS direct_user_broker_id,
            u_from_broker.id AS mapped_user_broker_id
        FROM properties p
        LEFT JOIN users u_direct
            ON u_direct.id = p.broker_id
           AND u_direct.role = 'broker'
           AND COALESCE(u_direct.status, 'active') = 'active'
        LEFT JOIN brokers b
            ON b.id = p.broker_id
        LEFT JOIN users u_from_broker
            ON u_from_broker.email = b.email
           AND u_from_broker.role = 'broker'
           AND COALESCE(u_from_broker.status, 'active') = 'active'
        WHERE p.id = ?
        LIMIT 1
    ");
    if (!$prop_stmt) {
        throw new Exception('Failed to prepare broker lookup query');
    }
    $prop_stmt->bind_param('i', $property_id);
    $prop_stmt->execute();
    $prop_result = $prop_stmt->get_result();
    $property = $prop_result->fetch_assoc();
    $prop_stmt->close();

    if (!$property) {
        echo json_encode(['success' => false, 'message' => 'Property not found']);
        exit;
    }

    $broker_id = 0;
    if (!empty($property['direct_user_broker_id'])) {
        $broker_id = (int)$property['direct_user_broker_id'];
    } elseif (!empty($property['mapped_user_broker_id'])) {
        $broker_id = (int)$property['mapped_user_broker_id'];
    }

    // Insert inquiry without assigned_to to avoid foreign key issues.
    // If broker cannot be mapped to users.id, save NULL broker_id instead of invalid FK value.
    if ($broker_id > 0) {
        $stmt = $conn->prepare("
            INSERT INTO inquiries (customer_id, property_id, broker_id, message, status)
            VALUES (?, ?, ?, ?, 'pending')
        ");
        if (!$stmt) {
            throw new Exception('Failed to prepare inquiry insert query');
        }
        $stmt->bind_param('iiis', $customer_id, $property_id, $broker_id, $message);
    } else {
        $stmt = $conn->prepare("
            INSERT INTO inquiries (customer_id, property_id, broker_id, message, status)
            VALUES (?, ?, NULL, ?, 'pending')
        ");
        if (!$stmt) {
            throw new Exception('Failed to prepare inquiry insert query');
        }
        $stmt->bind_param('iis', $customer_id, $property_id, $message);
    }
    $result = $stmt->execute();
    $stmt->close();

    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Inquiry submitted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to submit inquiry']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
