<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

if (!current_user()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'message' => 'Your session has expired.'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = db();
    $requestedBranchId = max(0, (int)($_GET['branch_id'] ?? 0));
    $superAdminAllBranches = actual_role() === 'super_admin' && $requestedBranchId < 1;
    $branchId = actual_role() === 'super_admin'
        ? $requestedBranchId
        : (int)(current_user()['branch_id'] ?? 0);
    if (!$superAdminAllBranches && $branchId < 1) {
        $branchId = (int)($pdo->query('SELECT id FROM `' . table('branches') . '` WHERE is_active=1 ORDER BY id LIMIT 1')->fetchColumn() ?: 0);
    }
    if (!$superAdminAllBranches && $branchId < 1) throw new RuntimeException('No active clinic branch is available.');

    $parts = [];
    $queueWhere = $superAdminAllBranches ? 'DATE(checked_in_at)=CURDATE()' : 'branch_id=? AND DATE(checked_in_at)=CURDATE()';
    $queueStmt = $pdo->prepare(
        'SELECT id,status,patient_id,appointment_id,dentist_user_id,inhouse_provider_user_id,chair_id,queue_no,updated_at '
        . 'FROM `' . table('queue_entries') . '` WHERE ' . $queueWhere . ' ORDER BY id'
    );
    $queueStmt->execute($superAdminAllBranches ? [] : [$branchId]);
    $queueIds = [];
    foreach ($queueStmt->fetchAll() as $row) {
        $queueIds[] = (int)$row['id'];
        $parts[] = 'q:' . implode(':', [
            (int)$row['id'], (string)$row['status'], (int)$row['patient_id'], (int)($row['appointment_id'] ?? 0),
            (int)($row['dentist_user_id'] ?? 0), (int)($row['inhouse_provider_user_id'] ?? 0), (int)($row['chair_id'] ?? 0),
            (string)$row['queue_no'], (string)($row['updated_at'] ?? ''),
        ]);
    }

    if (schema_table_exists(table('appointments'))) {
        $appointmentWhere = $superAdminAllBranches ? 'DATE(start_at)=CURDATE()' : 'branch_id=? AND DATE(start_at)=CURDATE()';
        $appointmentStmt = $pdo->prepare(
            'SELECT id,status,dentist_user_id,inhouse_provider_user_id,chair_id,start_at,updated_at '
            . 'FROM `' . table('appointments') . '` WHERE ' . $appointmentWhere . ' ORDER BY id'
        );
        $appointmentStmt->execute($superAdminAllBranches ? [] : [$branchId]);
        foreach ($appointmentStmt->fetchAll() as $row) {
            $parts[] = 'a:' . implode(':', [
                (int)$row['id'], (string)$row['status'], (int)($row['dentist_user_id'] ?? 0),
                (int)($row['inhouse_provider_user_id'] ?? 0), (int)($row['chair_id'] ?? 0),
                (string)$row['start_at'], (string)($row['updated_at'] ?? ''),
            ]);
        }
    }

    if ($queueIds && schema_table_exists(table('clinical_encounters'))) {
        $marks = implode(',', array_fill(0, count($queueIds), '?'));
        $encounterTable = table('clinical_encounters');
        $assistantSelect = schema_column_exists($encounterTable, 'assistant_user_id') ? 'assistant_user_id' : 'NULL assistant_user_id';
        $pausedSelect = schema_column_exists($encounterTable, 'paused_at') ? 'paused_at' : 'NULL paused_at';
        $finalizedSelect = schema_column_exists($encounterTable, 'finalized_at') ? 'finalized_at' : 'NULL finalized_at';
        $updatedSelect = schema_column_exists($encounterTable, 'updated_at') ? 'updated_at' : 'created_at updated_at';
        $encounterStmt = $pdo->prepare(
            'SELECT id,queue_entry_id,status,dentist_user_id,' . $assistantSelect . ',' . $pausedSelect . ',' . $finalizedSelect . ',' . $updatedSelect . ' '
            . 'FROM `' . $encounterTable . '` WHERE queue_entry_id IN (' . $marks . ') ORDER BY id'
        );
        $encounterStmt->execute($queueIds);
        foreach ($encounterStmt->fetchAll() as $row) {
            $parts[] = 'e:' . implode(':', [
                (int)$row['id'], (int)$row['queue_entry_id'], (string)$row['status'], (int)($row['dentist_user_id'] ?? 0),
                (int)($row['assistant_user_id'] ?? 0), (string)($row['paused_at'] ?? ''),
                (string)($row['finalized_at'] ?? ''), (string)($row['updated_at'] ?? ''),
            ]);
        }
    }

    if ($queueIds && schema_table_exists(table('invoices'))) {
        $marks = implode(',', array_fill(0, count($queueIds), '?'));
        $invoiceStmt = $pdo->prepare(
            'SELECT id,queue_entry_id,status,amount,paid_amount,updated_at FROM `' . table('invoices') . '` '
            . 'WHERE queue_entry_id IN (' . $marks . ') ORDER BY id'
        );
        $invoiceStmt->execute($queueIds);
        foreach ($invoiceStmt->fetchAll() as $row) {
            $parts[] = 'i:' . implode(':', [
                (int)$row['id'], (int)($row['queue_entry_id'] ?? 0), (string)$row['status'],
                number_format((float)$row['amount'], 2, '.', ''), number_format((float)$row['paid_amount'], 2, '.', ''),
                (string)($row['updated_at'] ?? ''),
            ]);
        }
    }

    echo json_encode([
        'ok' => true,
        'branch_id' => $branchId,
        'revision' => hash('sha256', implode('|', $parts)),
        'queue_count' => count($queueIds),
        'server_time' => date(DATE_ATOM),
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $exception) {
    error_log('DentalCare live queue revision failure: ' . $exception->getMessage());
    http_response_code(503);
    echo json_encode(['ok' => false, 'message' => 'Live queue synchronization is temporarily unavailable.'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
