<?php
session_start();
include 'layouts/dbconn.php';

header('Content-Type: application/json');

try {
    $search = $_POST['search'] ?? '';
    
    if (strlen($search) < 2) {
        throw new Exception('Please enter at least 2 characters');
    }

    $sql = "SELECT id, code, description 
            FROM icd10_codes 
            WHERE status = 1 
            AND (code LIKE ? OR description LIKE ?) 
            ORDER BY code 
            LIMIT 10";
            
    $stmt = $conn->prepare($sql);
    $search = "%$search%";
    $stmt->bind_param('ss', $search, $search);
    $stmt->execute();
    
    $result = $stmt->get_result();
    $diagnoses = [];
    while ($row = $result->fetch_assoc()) {
        $diagnoses[] = $row;
    }

    echo json_encode([
        'success' => true,
        'diagnoses' => $diagnoses
    ]);

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

$conn->close();
?>