<?php
require_once __DIR__ . '/db.php';

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

$type = $_GET['type'] ?? '';
$q = trim($_GET['q'] ?? '');
$nosiocId = isset($_GET['nosioc_id']) ? (int)$_GET['nosioc_id'] : 0;

if ($type === 'main') {
    if (mb_strlen($q, 'UTF-8') < 2) {
        echo json_encode([]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT 
            id,
            ime_prezime,
            status,
            broj_zvanica,
            nosioc
        FROM zvanice
        WHERE nosioc = 1
        AND LOWER(ime_prezime) LIKE LOWER(?)
        ORDER BY ime_prezime ASC
        LIMIT 10
    ");

    $stmt->execute(['%' . $q . '%']);

    echo json_encode($stmt->fetchAll(), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($type === 'companions') {
    if ($nosiocId <= 0) {
        echo json_encode([]);
        exit;
    }

    $params = [$nosiocId];

    $sql = "
        SELECT 
            id,
            ime_prezime,
            status
        FROM zvanice
        WHERE nosioc = 0
        AND nosioc_id = ?
    ";

    if ($q !== '') {
        $sql .= " AND LOWER(ime_prezime) LIKE LOWER(?) ";
        $params[] = '%' . $q . '%';
    }

    $sql .= " ORDER BY ime_prezime ASC LIMIT 10";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    echo json_encode($stmt->fetchAll(), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($type === 'guest_details') {
    $guestId = isset($_GET['guest_id']) ? (int)$_GET['guest_id'] : 0;

    if ($guestId <= 0) {
        echo json_encode(['success' => false]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT 
            id,
            ime_prezime,
            status,
            broj_zvanica,
            nosioc
        FROM zvanice
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$guestId]);
    $guest = $stmt->fetch();

    if (!$guest) {
        echo json_encode(['success' => false]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT 
            id,
            ime_prezime,
            status
        FROM zvanice
        WHERE nosioc = 0
        AND nosioc_id = ?
        ORDER BY ime_prezime ASC
    ");
    $stmt->execute([$guestId]);
    $companions = $stmt->fetchAll();

    echo json_encode([
        'success' => true,
        'guest' => $guest,
        'companions' => $companions
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([]);
exit;