<?php
/**
 * Search Plots AJAX Endpoint
 * LandSales Pro - Search available plots with autocomplete
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

initSecureSession();

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
$search = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? 'available';
$limit = min(intval($_GET['limit'] ?? 20), 50);

if (strlen($search) < 1) {
    echo json_encode(['success' => true, 'results' => []]);
    exit;
}

// Build search query
$searchTerm = "%{$search}%";
$statusClause = $status ? "AND p.status = ?" : "";

$sql = "SELECT p.id, p.plot_number, p.size, p.size_unit, p.price, p.status, p.block,
               pr.name as project_name, pr.location as project_location
        FROM plots p
        JOIN projects pr ON p.project_id = pr.id
        WHERE p.user_id = ?
        AND (p.plot_number LIKE ? OR pr.name LIKE ? OR p.block LIKE ?)
        {$statusClause}
        ORDER BY pr.name, p.plot_number
        LIMIT ?";

if ($status) {
    $results = db_fetch_all($sql, 'issss' . 'i', [$userId, $searchTerm, $searchTerm, $searchTerm, $status, $limit]);
} else {
    $sql = str_replace($statusClause, '', $sql);
    $results = db_fetch_all($sql, 'isss' . 'i', [$userId, $searchTerm, $searchTerm, $searchTerm, $limit]);
}

$formatted = [];
foreach ($results as $plot) {
    $formatted[] = [
        'id' => $plot['id'],
        'text' => "Plot {$plot['plot_number']} - {$plot['project_name']}",
        'plot_number' => $plot['plot_number'],
        'project_name' => $plot['project_name'],
        'size' => number_format($plot['size']) . ' ' . $plot['size_unit'],
        'price' => $plot['price'],
        'price_formatted' => 'TZS ' . number_format($plot['price']),
        'status' => $plot['status'],
        'block' => $plot['block']
    ];
}

echo json_encode([
    'success' => true,
    'results' => $formatted
]);
