<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
header('Content-Type: application/json');

$q = trim((string)($_GET['q'] ?? ''));
if (strlen($q) < 2 || gp_current_user_id() <= 0) {
    echo json_encode([]);
    exit;
}

$pdo = crm_pdo();
$results = [];
$term = '%' . $q . '%';

try {
    $stmt = $pdo->prepare("SELECT id, title, code FROM projects WHERE title LIKE ? OR code LIKE ? LIMIT 5");
    $stmt->execute([$term, $term]);
    foreach ($stmt->fetchAll() as $row) {
        $results[] = [
            'type' => 'Project',
            'label' => $row['title'] . ' (' . $row['code'] . ')',
            'url' => '/gopools/public/projects/edit.php?id=' . $row['id']
        ];
    }
} catch (Throwable $e) {}

try {
    $stmt = $pdo->prepare("SELECT id, name FROM customers WHERE name LIKE ? LIMIT 5");
    $stmt->execute([$term]);
    foreach ($stmt->fetchAll() as $row) {
        $results[] = [
            'type' => 'Customer',
            'label' => $row['name'],
            'url' => '/gopools/public/customers/edit.php?id=' . $row['id']
        ];
    }
} catch (Throwable $e) {}

try {
    $stmt = $pdo->prepare("SELECT id, full_name FROM employees WHERE full_name LIKE ? LIMIT 3");
    $stmt->execute([$term]);
    foreach ($stmt->fetchAll() as $row) {
        $results[] = [
            'type' => 'Employee',
            'label' => $row['full_name'],
            'url' => '/gopools/public/employees/edit.php?id=' . $row['id']
        ];
    }
} catch (Throwable $e) {}

echo json_encode($results);
