<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, private');

$ticketId = filter_var($_GET['ticket_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$createContext = is_scalar($_GET['context'] ?? '') && (string)$_GET['context'] === 'create';
if ($ticketId !== false) {
    $ticketStmt = db()->prepare('SELECT id, user_id, assigned_to, responsible_role_code FROM tickets WHERE id = ? LIMIT 1');
    $ticketStmt->execute([(int)$ticketId]);
    $ticket = $ticketStmt->fetch();
    if (!$ticket) {
        http_response_code(404);
        echo json_encode(['results' => [], 'error' => 'Tiket nije pronađen.'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    if (!can_manage_ticket_participants($ticket, $user)) {
        security_log_event('participant_search_forbidden', [
            'ticket_id' => (int)$ticketId,
            'user_id' => (int)$user['id'],
        ]);
        http_response_code(403);
        echo json_encode(['results' => [], 'error' => 'Nemate pravo da pretražujete učesnike za ovaj tiket.'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
} elseif ($createContext) {
    $createCsrf = is_scalar($_GET['csrf_token'] ?? '') ? (string)$_GET['csrf_token'] : '';
    if (!can_create_ticket($user) || !csrf_token_is_valid($createCsrf)) {
        security_log_event('participant_search_create_forbidden', ['user_id' => (int)$user['id']]);
        http_response_code(403);
        echo json_encode(['results' => [], 'error' => 'Nemate pravo na pretragu učesnika.'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
} else {
    http_response_code(400);
    echo json_encode(['results' => [], 'error' => 'Nedostaje validan kontekst tiketa.'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$query = is_scalar($_GET['q'] ?? '') ? trim((string)$_GET['q']) : '';
if (mb_strlen($query) < 2) {
    echo json_encode(['results' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

try {
    $term = mb_substr($query, 0, 100);
    $stmt = db()->prepare('SELECT id, name, email
        FROM users
        WHERE is_active = 1 AND (LOCATE(?, name) > 0 OR LOCATE(?, email) > 0)
        ORDER BY name ASC, email ASC
        LIMIT 10');
    $stmt->execute([$term, $term]);
    $results = array_map(static function (array $row): array {
        return [
            'id' => (int)$row['id'],
            'name' => (string)$row['name'],
            'email' => (string)$row['email'],
        ];
    }, $stmt->fetchAll());
    echo json_encode(['results' => $results], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['results' => [], 'error' => 'Pretraga trenutno nije dostupna.'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
