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

require_login();

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

if (!user_can('module.crm') && !user_can('module.billing') && !user_can('billing.manual.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array());
    exit;
}

$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());
}
