<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
header('Content-Type: application/json');

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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['results' => []]);
    exit();
}

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

    // Base query - only active codes
    $sql = "SELECT icd10_id, code, short_description, full_description, category, is_ent_related, commonly_used
            FROM icd10_codes 
            WHERE is_active = 1";
    
    $params = [];
    $types = '';

    // Add search conditions
    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);
    }

    // Order by relevance: commonly used first, then ENT-related, then by code
    $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()) {
        // Format the text display
        $text = $row['code'] . ' - ' . $row['short_description'];
        
        // Add category badge
        if ($row['category']) {
            $text .= ' [' . $row['category'] . ']';
        }
        
        // Add flags
        $flags = [];
        if ($row['is_ent_related']) {
            $flags[] = 'ENT';
        }
        if ($row['commonly_used']) {
            $flags[] = 'Common';
        }
        if (!empty($flags)) {
            $text .= ' (' . implode(', ', $flags) . ')';
        }

        $results[] = [
            'id' => $row['code'], // Use the code as the value
            'text' => $text,
            'code' => $row['code'],
            'description' => $row['short_description'],
            'full_description' => $row['full_description'],
            'category' => $row['category'],
            'is_ent_related' => $row['is_ent_related'],
            'commonly_used' => $row['commonly_used']
        ];
    }

    // Check if there are more results
    $count_sql = "SELECT COUNT(*) as total FROM icd10_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_types = str_repeat('s', 5);
        $count_stmt->bind_param($count_types, ...$count_params);
    }
    $count_stmt->execute();
    $total = $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' => [],
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>