<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
    exit();
}

try {
    $search = isset($_GET['q']) ? trim($_GET['q']) : '';
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $per_page = 30;
    $offset = ($page - 1) * $per_page;

    // Table may not exist yet (migration not run)
    $table_check = $conn->query("SHOW TABLES LIKE 'icd11_codes'");
    if (!$table_check || $table_check->num_rows === 0) {
        echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
        exit();
    }

    $sql = "SELECT icd11_id, code, short_description, full_description, category, is_ent_related, commonly_used
            FROM icd11_codes
            WHERE is_active = 1";

    $params = [];
    $types = '';

    if (!empty($search)) {
        $sql .= " AND (
            code LIKE ?
            OR short_description LIKE ?
            OR full_description LIKE ?
            OR synonyms LIKE ?
            OR category LIKE ?
        )";
        $search_term = "%{$search}%";
        $params = array_fill(0, 5, $search_term);
        $types = str_repeat('s', 5);
    }

    $sql .= " ORDER BY commonly_used DESC, is_ent_related DESC, code ASC
              LIMIT ? OFFSET ?";
    $params[] = $per_page;
    $params[] = $offset;
    $types .= 'ii';

    $stmt = $conn->prepare($sql);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();

    $results = [];
    while ($row = $result->fetch_assoc()) {
        $text = $row['code'] . ' - ' . $row['short_description'];
        if (!empty($row['category'])) {
            $text .= ' [' . $row['category'] . ']';
        }
        $flags = [];
        if ($row['is_ent_related']) $flags[] = 'ENT';
        if ($row['commonly_used']) $flags[] = 'Common';
        if (!empty($flags)) {
            $text .= ' (' . implode(', ', $flags) . ')';
        }
        $results[] = [
            'id' => $row['code'],
            'text' => $text,
            'code' => $row['code'],
            'short_description' => $row['short_description'],
            'description' => $row['short_description'],
            'full_description' => $row['full_description'],
            'category' => $row['category'],
            'is_ent_related' => $row['is_ent_related'],
            'commonly_used' => $row['commonly_used']
        ];
    }

    $count_sql = "SELECT COUNT(*) as total FROM icd11_codes WHERE is_active = 1";
    if (!empty($search)) {
        $count_sql .= " AND (
            code LIKE ? OR short_description LIKE ? OR full_description LIKE ?
            OR synonyms LIKE ? OR category LIKE ?
        )";
    }
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($search)) {
        $count_params = array_fill(0, 5, $search_term);
        $count_stmt->bind_param('sssss', ...$count_params);
    }
    $count_stmt->execute();
    $total = (int)$count_stmt->get_result()->fetch_assoc()['total'];

    echo json_encode([
        'results' => $results,
        'pagination' => ['more' => ($offset + $per_page) < $total]
    ]);

} catch (Exception $e) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false], 'error' => $e->getMessage()]);
}

$conn->close();
