<?php

declare(strict_types=1);
require dirname(__DIR__) . '/app/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');

if (!current_user()) {
    http_response_code(401);
    echo json_encode(['ok'=>false,'results'=>[],'message'=>'Your session has expired. Sign in again.']);
    exit;
}
if (!in_array(active_role(), ['dentist','dental_assistant','super_admin','clinic_admin'], true)) {
    http_response_code(403);
    echo json_encode(['ok'=>false,'results'=>[],'message'=>'This task view cannot search clinical diagnoses.']);
    exit;
}
if (!schema_table_exists(table('diagnosis_catalog'))) {
    http_response_code(503);
    echo json_encode(['ok'=>false,'results'=>[],'message'=>'Apply the pending DentalCare update to enable diagnosis search.']);
    exit;
}

try {
    $q = trim((string)($_GET['q'] ?? ''));
    if (mb_strlen($q) < 1) {
        echo json_encode(['ok'=>true,'results'=>[],'message'=>'Type a diagnosis name or code.']);
        exit;
    }
    $like = '%' . $q . '%';
    $stmt = db()->prepare(
        'SELECT id,code,name,category,default_status FROM `' . table('diagnosis_catalog') . '` '
        . 'WHERE is_active=1 AND (name LIKE ? OR code LIKE ? OR category LIKE ?) '
        . 'ORDER BY CASE WHEN code=? THEN 0 WHEN name LIKE ? THEN 1 ELSE 2 END,name LIMIT 20'
    );
    $stmt->execute([$like,$like,$like,$q,$q.'%']);
    $rows=[];
    foreach ($stmt->fetchAll() as $row) {
        $rows[]=[
            'id'=>(int)$row['id'],
            'code'=>(string)($row['code']??''),
            'name'=>(string)$row['name'],
            'category'=>(string)($row['category']??''),
            'default_status'=>(string)($row['default_status']??'provisional'),
            'label'=>trim(((string)($row['code']??'')!==''?(string)$row['code'].' · ':'').(string)$row['name']),
        ];
    }
    echo json_encode(['ok'=>true,'results'=>$rows,'message'=>$rows?'':'No known diagnosis matched. You may enter a custom diagnosis.'],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
    http_response_code(422);
    echo json_encode(['ok'=>false,'results'=>[],'message'=>$exception->getMessage()],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
