<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
if (!signed_identity_has_role(['super_admin','clinic_admin'])) {
    access_denied('Only an Administrator or Superuser can manage controlled emergency access.');
}
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
$schemaReady = dental_break_glass_schema_ready();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = trim((string)($_POST['action'] ?? ''));
        if ($action === 'start') {
            $result = dental_break_glass_start($_POST);
            flash('success', 'Emergency access session #' . (int)$result['id'] . ' is active until ' . (string)$result['expires_at'] . '. Every use is logged and requires independent review.');
        } elseif ($action === 'end') {
            dental_break_glass_end('ended_by_user');
            flash('success', 'Emergency access ended and was queued for independent review.');
        } elseif ($action === 'review') {
            dental_break_glass_review_session((int)($_POST['session_id'] ?? 0), (string)($_POST['outcome'] ?? ''), (string)($_POST['notes'] ?? ''));
            flash('success', 'Independent emergency-access review recorded.');
        } elseif ($action === 'revoke') {
            dental_break_glass_revoke_session((int)($_POST['session_id'] ?? 0), (string)($_POST['reason'] ?? ''));
            flash('success', 'The active emergency-access session was revoked and queued for review.');
        } else {
            throw new RuntimeException('The emergency-access action was not recognized.');
        }
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
    }
    header('Location: break_glass.php');
    exit;
}

$activeSession = $schemaReady ? dental_break_glass_active_session(true) : null;
$branches = [];
$rows = [];
$eventCounts = [];
if ($schemaReady) {
    try {
        $branches = $pdo->query('SELECT id,name FROM `' . table('branches') . '` WHERE is_active=1 ORDER BY name')->fetchAll();
    } catch (Throwable) {
        $branches = [];
    }
    try {
        $userId = (int)(current_user()['id'] ?? 0);
        $sql = 'SELECT s.*,u.name actor_name,b.name branch_name,ru.name reviewer_name,'
            . ' EXISTS(SELECT 1 FROM `' . dental_break_glass_notifications_table() . '` n WHERE n.session_id=s.id AND n.reviewer_user_id=?) assigned_to_me '
            . 'FROM `' . dental_break_glass_sessions_table() . '` s '
            . 'JOIN `' . table('users') . '` u ON u.id=s.user_id '
            . 'LEFT JOIN `' . table('branches') . '` b ON b.id=s.branch_id '
            . 'LEFT JOIN `' . table('users') . '` ru ON ru.id=s.reviewer_user_id ';
        $args = [$userId];
        if (actual_role() === 'clinic_admin') {
            $sql .= 'WHERE (s.user_id=? OR s.branch_id=? OR EXISTS(SELECT 1 FROM `' . dental_break_glass_notifications_table() . '` nx WHERE nx.session_id=s.id AND nx.reviewer_user_id=?)) ';
            $args[] = $userId;
            $args[] = signed_user_branch_id();
            $args[] = $userId;
        }
        $sql .= 'ORDER BY s.id DESC LIMIT 100';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($args);
        $rows = $stmt->fetchAll();
        if ($rows) {
            $ids = array_map(static fn(array $row): int => (int)$row['id'], $rows);
            $in = implode(',', array_fill(0,count($ids),'?'));
            $counts = $pdo->prepare('SELECT session_id,COUNT(*) total FROM `' . dental_break_glass_events_table() . '` WHERE session_id IN (' . $in . ') GROUP BY session_id');
            $counts->execute($ids);
            foreach ($counts->fetchAll() as $count) $eventCounts[(int)$count['session_id']] = (int)$count['total'];
        }
    } catch (Throwable $exception) {
        flash('error', 'Emergency-access history could not be loaded: ' . $exception->getMessage());
        $rows = [];
    }
}

$reasonCatalog = dental_break_glass_reason_catalog();
$permissionCatalog = dental_break_glass_permission_catalog();
render_header('Emergency Access Review');
?>
<section class="admin-hero card">
    <div><span class="eyebrow">Controlled administrative bypass</span><h2>Emergency Access Review</h2><p>Use only when normal role access cannot safely complete a time-critical administrative task. Access is MFA re-authenticated, minimum-necessary, time-limited, fully logged, and independently reviewed.</p></div>
    <div class="admin-hero-icon"><?=dental_icon('shield')?></div>
</section>

<?php if (!$schemaReady): ?>
<div class="alert warning"><strong>Database update required.</strong> Apply v0.9.0.5 before using emergency access.</div>
<?php if (actual_role()==='super_admin'): ?><a class="btn primary" href="system_setup.php?tab=updates">Open Updates &amp; Database</a><?php endif; ?>
<?php else: ?>
<section class="stats mini-stats">
    <?php stat_card('Active session', $activeSession ? '#' . (int)$activeSession['id'] : 'None', $activeSession ? 'Expires ' . (string)$activeSession['expires_at'] : 'Normal role controls active'); ?>
    <?php stat_card('Assigned reviews', dental_break_glass_pending_review_count(), 'Independent review queue'); ?>
    <?php stat_card('Maximum duration', '30 min', 'Automatic expiry'); ?>
    <?php stat_card('Hard exclusions', 'Always on', 'No clinical authorship or self-approval'); ?>
</section>

<?php if ($activeSession): ?>
<section class="card">
    <div class="card-head"><div><span class="eyebrow">Emergency session active</span><h2>Session #<?=(int)$activeSession['id']?></h2><p>Expires <?=e((string)$activeSession['expires_at'])?>. Every permission use is recorded in the protected emergency-access event trail.</p></div><span class="badge warning">Active</span></div>
    <dl class="summary-list">
        <div><dt>Reason</dt><dd><?=e((string)($reasonCatalog[$activeSession['reason_code']] ?? $activeSession['reason_code']))?></dd></div>
        <div><dt>Explanation</dt><dd><?=e((string)$activeSession['reason_text'])?></dd></div>
        <div><dt>Branch scope</dt><dd><?=e((string)($activeSession['branch_id'] ?: 'All authorized branches'))?></dd></div>
        <div><dt>Entity scope</dt><dd><?=e(trim((string)($activeSession['entity_type'] ?? '') . ' ' . (string)($activeSession['entity_id'] ?? '')) ?: 'No single-record restriction')?></dd></div>
        <div><dt>Permissions</dt><dd><?=e(implode(', ', (array)$activeSession['scope_permissions']))?></dd></div>
    </dl>
    <form method="post" class="status-actions"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="end"><button class="btn danger" type="submit">End emergency access</button></form>
</section>
<?php else: ?>
<section class="card">
    <div class="card-head"><div><h2>Start controlled emergency access</h2><p>Another active Administrator or Superuser must exist to receive and complete the independent review.</p></div><span class="badge neutral">MFA required</span></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="start">
        <label>Approved reason<select name="reason_code" required><option value="">Select reason</option><?php foreach($reasonCatalog as $code=>$label): ?><option value="<?=e($code)?>"><?=e($label)?></option><?php endforeach; ?></select></label>
        <label>Duration<select name="duration_minutes" required><option value="15">15 minutes</option><option value="30">30 minutes</option></select></label>
        <?php if(actual_role()==='super_admin'): ?><label>Branch scope<select name="branch_id" required><option value="">Select clinic branch</option><?php foreach($branches as $branch): ?><option value="<?=(int)$branch['id']?>"><?=e((string)$branch['name'])?></option><?php endforeach; ?></select></label><?php else: ?><input type="hidden" name="branch_id" value="<?=signed_user_branch_id()?>"><?php endif; ?>
        <label>Optional record type<select name="entity_type"><option value="">No single-record restriction</option><option value="patient">Patient</option><option value="appointment">Appointment</option><option value="encounter">Encounter</option><option value="invoice">Invoice</option><option value="queue_entry">Queue entry</option><option value="document">Document</option></select></label>
        <label>Optional record ID<input type="number" min="1" name="entity_id" inputmode="numeric" placeholder="Use with record type"></label>
        <label class="full">Specific explanation<textarea name="reason_text" rows="3" minlength="20" maxlength="1000" required placeholder="Describe the emergency, the task, and why normal access cannot be used."></textarea></label>
        <fieldset class="full"><legend>Minimum-necessary permissions — select no more than 8</legend><div class="permission-checkbox-grid"><?php foreach($permissionCatalog as $code=>$label): ?><label class="check-row"><input type="checkbox" name="permissions[]" value="<?=e($code)?>"><span><strong><?=e($label)?></strong><small><?=e($code)?></small></span></label><?php endforeach; ?></div></fieldset>
        <label>Current password<input type="password" name="password" autocomplete="current-password" required></label>
        <label>Authenticator or recovery code<input type="text" name="mfa_code" inputmode="numeric" autocomplete="one-time-code" required></label>
        <div class="full alert warning"><strong>Cannot be bypassed:</strong> clinical authorship, prescriptions, signatures, self-approval, sterilization release segregation, audit controls, permission/role changes, production restore, or patient/provider/chair schedule conflicts.</div>
        <div class="full status-actions"><button class="btn danger" type="submit">Start emergency access</button></div>
    </form>
</section>
<?php endif; ?>

<section class="card">
    <div class="card-head"><div><h2>Emergency-access sessions</h2><p>Independent reviewers can close an active session, then record the retrospective outcome. The access user cannot review their own session.</p></div></div>
    <?php if(!$rows): ?><p class="muted">No emergency-access sessions are available.</p><?php else: ?>
    <div class="table-wrap"><table><thead><tr><th>Session</th><th>User / scope</th><th>Reason</th><th>Status</th><th>Events</th><th>Independent review</th></tr></thead><tbody>
    <?php foreach($rows as $row): $id=(int)$row['id']; $assigned=!empty($row['assigned_to_me']); $own=(int)$row['user_id']===(int)(current_user()['id']??0); ?>
    <tr><td><strong>#<?=$id?></strong><small><?=e((string)$row['started_at'])?> → <?=e((string)$row['expires_at'])?></small></td>
    <td><strong><?=e((string)$row['actor_name'])?></strong><small><?=e((string)($row['branch_name'] ?: 'All authorized branches'))?><?=!empty($row['entity_type'])?' · '.e((string)$row['entity_type']).' #'.e((string)$row['entity_id']):''?></small></td>
    <td><?=e((string)($reasonCatalog[$row['reason_code']] ?? $row['reason_code']))?><small><?=e((string)$row['reason_text'])?></small></td>
    <td><span class="badge <?=($row['status']==='active'?'warning':($row['status']==='reviewed'?'success':'neutral'))?>"><?=e((string)$row['status'])?></span><small><?=e((string)($row['ended_reason'] ?? ''))?></small></td>
    <td><?=(int)($eventCounts[$id]??0)?></td>
    <td>
        <?php if($row['status']==='reviewed'): ?><strong><?=e((string)$row['review_outcome'])?></strong><small><?=e((string)($row['reviewer_name'] ?? 'Reviewer'))?> · <?=e((string)$row['reviewed_at'])?></small><small><?=e((string)$row['review_notes'])?></small>
        <?php elseif($assigned && !$own): ?>
            <?php if($row['status']==='active'): ?><form method="post" class="compact-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="revoke"><input type="hidden" name="session_id" value="<?=$id?>"><input type="text" name="reason" minlength="10" maxlength="500" placeholder="Revocation reason" required><button class="btn danger compact" type="submit">Revoke now</button></form><?php endif; ?>
            <form method="post" class="compact-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="review"><input type="hidden" name="session_id" value="<?=$id?>"><select name="outcome" required><option value="approved">Appropriate</option><option value="concerning">Concerning</option><option value="escalated">Escalated</option></select><input type="text" name="notes" minlength="10" maxlength="1000" placeholder="Independent review notes" required><button class="btn primary compact" type="submit">Record review</button></form>
        <?php elseif($own): ?><span class="muted">Independent reviewer required</span><?php else: ?><span class="muted">Not assigned to you</span><?php endif; ?>
    </td></tr>
    <?php endforeach; ?>
    </tbody></table></div>
    <?php endif; ?>
</section>
<?php endif; ?>
<?php render_footer();
