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

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

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

try {
    // Get search term - support both GET and POST, and both 'term' and 'query' parameters
    $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']);
    }

    // Require at least 2 characters
    if (strlen($search) < 2) {
        echo json_encode($response);
        exit();
    }

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

    // Search query - prioritize ENT-related and commonly used codes
    $sql = "SELECT 
                icd10_id,
                code,
                short_description,
                full_description,
                category,
                is_ent_related,
                commonly_used
            FROM icd10_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);
    }

    // Bind 6 parameters (4 for WHERE, 2 for ORDER BY)
    $stmt->bind_param(
        "ssssss",
        $search_param,  // code LIKE
        $search_param,  // short_description LIKE
        $search_param,  // full_description LIKE
        $search_param,  // synonyms LIKE
        $search_start,  // ORDER BY code exact match
        $search_start   // ORDER BY short_description starts with
    );

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

    $result = $stmt->get_result();

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

        $response['results'][] = [
            'id' => $row['code'],  // Use code as ID for easy insertion
            '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'],
            'commonly_used' => (bool)$row['commonly_used']
        ];
    }

    $stmt->close();

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

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