<?php
/**
 * AJAX search for ICD-11 codes - PRODIGY NOTES Item #2
 * Mirrors search_icd10.php structure for consistency
 */
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

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

$response = ['success' => true, 'results' => []];

try {
    $search = '';
    if (isset($_GET['term'])) {
        $search = trim($_GET['term']);
    } elseif (isset($_POST['term'])) {
        $search = trim($_POST['term']);
    } elseif (isset($_POST['query'])) {
        $search = trim($_POST['query']);
    } elseif (isset($_GET['query'])) {
        $search = trim($_GET['query']);
    }

    if (strlen($search) < 2) {
        echo json_encode($response);
        exit();
    }

    $search_param = "%{$search}%";
    $search_start = "{$search}%";

    // Check if icd11_codes table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'icd11_codes'");
    if (!$table_check || $table_check->num_rows === 0) {
        echo json_encode($response);
        exit();
    }

    $sql = "SELECT 
                icd11_id,
                code,
                short_description,
                full_description,
                category,
                is_ent_related,
                commonly_used
            FROM icd11_codes
            WHERE is_active = 1
              AND (
                    code LIKE ?
                 OR short_description LIKE ?
                 OR full_description LIKE ?
                 OR synonyms LIKE ?
                )
            ORDER BY 
                CASE 
                    WHEN code LIKE ? THEN 1
                    WHEN short_description LIKE ? THEN 2
                    WHEN commonly_used = 1 THEN 3
                    WHEN is_ent_related = 1 THEN 4
                    ELSE 5
                END,
                code ASC
            LIMIT 15";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("ssssss", $search_param, $search_param, $search_param, $search_param, $search_start, $search_start);

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $conn->error);
    }

    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $display = $row['code'] . ' - ' . $row['short_description'];
        if (!empty($row['category'])) {
            $display .= ' [' . $row['category'] . ']';
        }

        $response['results'][] = [
            'id' => $row['code'],
            'text' => $display,
            'code' => $row['code'],
            'short_description' => $row['short_description'],
            'full_description' => $row['full_description'] ?? '',
            'category' => $row['category'] ?? '',
            'is_ent_related' => (bool)($row['is_ent_related'] ?? 0),
            'commonly_used' => (bool)($row['commonly_used'] ?? 0)
        ];
    }

    $stmt->close();

} catch (Exception $e) {
    $response['success'] = false;
    $response['error'] = $e->getMessage();
    error_log("ICD-11 search error: " . $e->getMessage());
}

$conn->close();
echo json_encode($response);
exit();
