<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin','receptionist','staff','dentist','dental_assistant','cashier','inventory_officer']);
require_once DENTAL_ROOT . '/app/reconciliation_center.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

try {
    if (!reconciliation_schema_ready()) throw new RuntimeException('Reconciliation update pending.');
    $pdo=db();$actual=actual_role();$role=active_role();$revisionRole=in_array($actual,['super_admin','clinic_admin'],true)?$actual:$role;$userId=(int)(current_user()['id']??0);
    $branchId=$actual==='super_admin'?max(0,(int)($_GET['branch_id']??0)):signed_user_branch_id();
    if(in_array($actual,['super_admin','clinic_admin'],true)&&!app_demo_read_only()){
        $key='reconciliation_last_scan_'.($branchId>0?$branchId:'all');$last=(int)setting_get('system',$key,0);
        if($last<time()-30){reconciliation_scan_all($pdo,$branchId);setting_set('system',$key,(string)time());}
    }
    echo json_encode(['ok'=>true,'revision'=>reconciliation_revision($pdo,$branchId,$revisionRole,$userId),'checked_at'=>date(DATE_ATOM)],JSON_UNESCAPED_SLASHES);
} catch(Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>$e->getMessage()],JSON_UNESCAPED_SLASHES);
}
