<?php
/**
 * Search Buyers AJAX Endpoint
 * LandSales Pro - Search buyers 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'] ?? '');
$limit = min(intval($_GET['limit'] ?? 20), 50);

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

// Build search query
$searchTerm = "%{$search}%";

$sql = "SELECT id, full_name, phone, email, id_type, id_number
        FROM buyers
        WHERE user_id = ?
        AND (full_name LIKE ? OR phone LIKE ? OR email LIKE ? OR id_number LIKE ?)
        ORDER BY full_name
        LIMIT ?";

$results = db_fetch_all($sql, 'issss' . 'i', [$userId, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $limit]);

$formatted = [];
foreach ($results as $buyer) {
    $formatted[] = [
        'id' => $buyer['id'],
        'text' => $buyer['full_name'] . ' (' . $buyer['phone'] . ')',
        'full_name' => $buyer['full_name'],
        'phone' => $buyer['phone'],
        'email' => $buyer['email'] ?? '',
        'id_type' => $buyer['id_type'] ?? '',
        'id_number' => $buyer['id_number'] ?? ''
    ];
}

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