<?php
/**
 * Prince VIP System - Global Search AJAX
 */
require_once __DIR__ . '/../config/database.php';
if (!isLoggedIn()) { echo json_encode([]); exit; }

$db = getDB();
$query = clean($_POST['query'] ?? '');
if (strlen($query) < 2) { echo json_encode([]); exit; }

$results = [];
$params = ["%$query%", "%$query%"];

// بحث في العقود
$whereAgent = !isAdmin() ? "AND c.agent_id = " . (int)$_SESSION['user_id'] : "";
$contracts = $db->prepare("SELECT c.id, c.contract_number, cl.full_name as client_name, c.car_number 
    FROM contracts c JOIN clients cl ON c.client_id = cl.id 
    WHERE (c.contract_number LIKE ? OR cl.full_name LIKE ? OR c.car_number LIKE ?) $whereAgent LIMIT 5");
$contracts->execute(["%$query%", "%$query%", "%$query%"]);
foreach ($contracts->fetchAll() as $c) {
    $results[] = [
        'type' => 'contract',
        'title' => 'عقد: ' . $c['contract_number'],
        'subtitle' => $c['client_name'] . ' - ' . ($c['car_number'] ?? ''),
        'url' => 'contract_view.php?id=' . $c['id']
    ];
}

// بحث في العملاء
$clients = $db->prepare("SELECT id, full_name, id_number FROM clients WHERE full_name LIKE ? OR id_number LIKE ? LIMIT 5");
$clients->execute($params);
foreach ($clients->fetchAll() as $cl) {
    $results[] = [
        'type' => 'client',
        'title' => 'عميل: ' . $cl['full_name'],
        'subtitle' => $cl['id_number'],
        'url' => 'clients.php'
    ];
}

echo json_encode($results);
