<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../services/crm/CustomerService.php';

require_login();
require_permission('module.crm');

header('Content-Type: application/json; charset=utf-8');

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
if (mb_strlen($q) < 2) {
    echo json_encode(array());
    exit;
}

try {
    $service = new CustomerService();
    $rows = array_map(function ($customer) use ($service) {
        return $service->publicPayload($customer);
    }, $service->search($q, 12));

    echo json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    echo json_encode(array());
}
