<?php
declare(strict_types=1);

if (!isset($_GET['action'])) {
    http_response_code(400);
    echo "File not found.";
    exit;
}

while (ob_get_level()) { ob_end_clean(); }
header('Content-Type: application/json; charset=utf-8');

global $db, $conn, $pdo;
$db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);

if (!$db_obj) {
    $db_path = realpath(__DIR__ . '/../core/db.php');
    if ($db_path && file_exists($db_path)) require_once $db_path;
    $db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);
}

try {
    $action = (string)($_GET['action'] ?? '');

    // ✅ DışLab katalog arama (modal burayı kullanacak)
  if ($action === 'search_catalog') {
    $q = trim((string)($_GET['q'] ?? ''));
    $limit = (int)($_GET['limit'] ?? 60);
    $limit = max(10, min(200, $limit));

    $sql = "SELECT id, dislab_kodu, dislab_adi, sut_kodu, ornek_tur_adi, kap_adi, is_active
            FROM dislab_test_listesi
            WHERE 1=1";
    $params = [];

    if ($q !== '') {
        $sql .= " AND (
            dislab_adi  LIKE :q1
            OR dislab_kodu LIKE :q2
            OR sut_kodu LIKE :q3
        )";
        $like = "%{$q}%";
        $params[':q1'] = $like;
        $params[':q2'] = $like;
        $params[':q3'] = $like;
    }

    $sql .= " ORDER BY is_active DESC, dislab_adi ASC LIMIT {$limit}";

    $st = $db_obj->prepare($sql);
    foreach ($params as $k => $v) $st->bindValue($k, $v);
    $st->execute();

    $items = $st->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'items' => $items], JSON_UNESCAPED_UNICODE);
    exit;
    }

    echo json_encode(['success' => false, 'error' => 'Bilinmeyen action.'], JSON_UNESCAPED_UNICODE);
    exit;

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}
