<?php
use App\Core\Csrf;
use App\Core\Session;

$center = is_array($center ?? null) ? $center : [];
$hospitalName = $hospital['name'] ?? strtoupper((string)($hospitalCode ?? 'NJCH'));
$isAr = current_lang() === 'ar';
$txt = function (string $en, string $ar = '') use ($isAr): string { return $isAr && $ar !== '' ? $ar : $en; };
$getText = function (array $item, string $key, string $fallback = '') use ($isAr): string {
    $arKey = $key . '_ar';
    if ($isAr && isset($item[$arKey]) && (string)$item[$arKey] !== '') { return (string)$item[$arKey]; }
    return isset($item[$key]) && (string)$item[$key] !== '' ? (string)$item[$key] : $fallback;
};
$metric = function ($value): string {
    if ($value === null || $value === '') { return '—'; }
    return is_numeric($value) ? number_format((float)$value, 0) : (string)$value;
};
$clip = function ($value, int $limit = 180): string {
    $text = trim((string)$value);
    if ($text === '') { return ''; }
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '…' : $text;
    }
    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
};
$statusLabel = function (string $value) use ($txt): string {
    $value = strtolower(trim($value));
    if ($value === 'reviewed') { return $txt('Reviewed', 'تمت المراجعة'); }
    if ($value === 'deferred') { return $txt('Deferred', 'مؤجل'); }
    if ($value === 'open') { return $txt('Open', 'مفتوح'); }
    return $value !== '' ? $value : '—';
};
$governanceStatusLabel = function (string $value) use ($txt): string {
    $map = [
        'unassigned' => $txt('Unassigned', 'غير مسند'),
        'assigned' => $txt('Assigned', 'مسند'),
        'due_soon' => $txt('Due soon', 'استحقاق قريب'),
        'follow_up_due' => $txt('Follow-up due', 'متابعة مستحقة'),
        'overdue' => $txt('Overdue', 'متأخر'),
        'escalated' => $txt('Escalated', 'مصعّد'),
        'resolved' => $txt('Resolved', 'مغلق'),
        'on_track' => $txt('On track', 'على المسار'),
    ];
    $value = strtolower(trim($value));
    return $map[$value] ?? ($value !== '' ? ucwords(str_replace('_', ' ', $value)) : '—');
};
$actionUrl = function (array $item): string {
    $type = (string)($item['link_type'] ?? $item['type'] ?? 'page');
    $target = (string)($item['target'] ?? 'dashboard');
    if ($type === 'public') { return $target; }
    return 'index.php?page=' . rawurlencode($target) . '&lang=' . current_lang();
};
$action = is_array($action ?? null) ? $action : null;
$operational = is_array($center['operational'] ?? null) ? $center['operational'] : [];
$metrics = is_array($center['metrics'] ?? null) ? $center['metrics'] : [];
$review = $action && is_array($action['review'] ?? null) ? $action['review'] : ['status' => 'open', 'note' => '', 'updated_at' => '', 'updated_by' => ''];
$workflow = is_array($center['review_workflow'] ?? null) ? $center['review_workflow'] : [];
$auditHistory = is_array($auditHistory ?? null) ? $auditHistory : [];
$reviewDiagnostics = is_array($reviewDiagnostics ?? null) ? $reviewDiagnostics : [];
$previousReview = is_array($previousReview ?? null) ? $previousReview : [];
$allowedTransitions = is_array($allowedTransitions ?? null) ? array_values($allowedTransitions) : ['open', 'reviewed', 'deferred'];
$governance = is_array($governance ?? null) ? $governance : [];
$governanceHistory = is_array($governanceHistory ?? null) ? $governanceHistory : [];
$governanceDiagnostics = is_array($governanceDiagnostics ?? null) ? $governanceDiagnostics : [];
$governanceStorage = (string)($governance['storage'] ?? $governanceDiagnostics['storage_mode'] ?? 'json_fallback');
$governanceStatus = strtolower((string)($governance['accountability_status'] ?? 'unassigned'));
$reviewStorage = (string)($review['storage'] ?? $workflow['storage'] ?? 'json_fallback');
$reviewCount = (int)($review['review_count'] ?? 0);
$status = strtolower((string)($review['status'] ?? 'open'));
if (!in_array($status, ['open', 'reviewed', 'deferred'], true)) { $status = 'open'; }
$success = Session::flash('review_success');
$error = Session::flash('review_error');
$governanceSuccess = Session::flash('governance_success');
$governanceError = Session::flash('governance_error');
$severity = $action ? strtolower((string)($action['severity'] ?? 'routine')) : 'routine';
$ruleId = $action ? (string)($action['rule_id'] ?? $ruleId ?? '') : (string)($ruleId ?? '');
$historicalOnly = $action ? !empty($action['historical_only']) : false;
$historicalOperationalDate = $action ? (string)($action['historical_operational_date'] ?? '') : '';
$hasActionTarget = $action ? trim((string)($action['target'] ?? '')) !== '' : false;
?>

<section class="action-center action-review-page action-review-<?= e($severity) ?>">
    <section class="review-hero">
        <div>
            <span class="action-overline">Phase 10.6.6</span>
            <h2><?= e($txt('Action Review, Governance & Cross-Day Accountability', 'مراجعة الإجراء والحوكمة والمساءلة عبر الأيام')) ?></h2>
            <p><?= e($txt('Review the action, assign accountable ownership, control due dates and follow-up, escalate when needed, and preserve immutable leadership history across operational days.', 'راجع الإجراء وحدد المسؤول والمنفذ وتاريخ الاستحقاق والمتابعة والتصعيد عند الحاجة مع حفظ سجل قيادة غير قابل للفقد عبر الأيام التشغيلية.')) ?></p>
            <div class="action-hero-tags">
                <span><?= e($txt('Branch', 'الفرع')) ?>: <b><?= e((string)$hospitalName) ?></b></span>
                <span><?= e($txt('Operational Day', 'اليوم التشغيلي')) ?>: <b><?= e((string)($operational['operational_date'] ?? '—')) ?></b></span>
                <span><?= e($txt('Last Updated', 'آخر تحديث')) ?>: <b><?= e((string)($center['last_updated'] ?? '—')) ?></b></span>
            </div>
        </div>
        <a class="review-back" href="index.php?page=action-center&lang=<?= e(current_lang()) ?>">← <?= e($txt('Back to Action Center', 'العودة لمركز الإجراءات')) ?></a>
    </section>

    <?php if ($success): ?><div class="review-flash success"><?= e($success) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="review-flash error"><?= e($error) ?></div><?php endif; ?>
    <?php if ($governanceSuccess): ?><div class="review-flash success governance-flash"><?= e($governanceSuccess) ?></div><?php endif; ?>
    <?php if ($governanceError): ?><div class="review-flash error governance-flash"><?= e($governanceError) ?></div><?php endif; ?>
    <?php if (!empty($centerError)): ?><div class="review-flash error"><?= e((string)$centerError) ?></div><?php endif; ?>

    <?php if (!$action): ?>
        <section class="review-not-found">
            <strong><?= e($txt('Action not found in the current worklist.', 'الإجراء غير موجود في قائمة اليوم الحالية.')) ?></strong>
            <p><?= e($txt('The alert may have cleared after the latest refresh. Return to the Action Center to review active actions.', 'ربما اختفى التنبيه بعد آخر تحديث. عد إلى مركز الإجراءات لمراجعة الإجراءات النشطة.')) ?></p>
        </section>
    <?php else: ?>
        <?php if ($historicalOnly): ?>
            <div class="review-historical-banner">
                <b><?= e($txt('Historical action review', 'مراجعة تاريخية للإجراء')) ?></b>
                <span><?= e($txt('This action is no longer in the current worklist, but its leadership review and complete audit history remain available.', 'هذا الإجراء لم يعد موجودًا في قائمة العمل الحالية، لكن مراجعة القيادة وسجل التدقيق الكامل ما زالا متاحين.')) ?></span>
                <?php if ($historicalOperationalDate !== ''): ?><em><?= e($txt('Last operational day', 'آخر يوم تشغيلي')) ?>: <?= e($historicalOperationalDate) ?></em><?php endif; ?>
            </div>
        <?php endif; ?>
        <section class="review-grid review-grid-stable">
            <div class="review-main-column">
                <article class="review-main-card">
                <div class="review-title-line">
                    <span class="review-severity review-severity-<?= e($severity) ?>"><?= e(strtoupper($severity)) ?></span>
                    <span class="review-status review-status-<?= e($status) ?>"><?= e($status === 'reviewed' ? $txt('Reviewed', 'تمت المراجعة') : ($status === 'deferred' ? $txt('Deferred', 'مؤجل') : $txt('Open', 'مفتوح'))) ?></span>
                    <span class="governance-state-badge governance-status-<?= e($governanceStatus) ?>"><?= e($governanceStatusLabel($governanceStatus)) ?></span>
                </div>
                <h3><?= e($getText($action, 'title', 'Action')) ?></h3>
                <p><?= e($getText($action, 'text', '')) ?></p>

                <div class="review-rule-grid">
                    <div><small><?= e($txt('Metric', 'المؤشر')) ?></small><strong><?= e((string)($action['metric'] ?? '—')) ?></strong></div>
                    <div><small><?= e($txt('Observed', 'المشاهد')) ?></small><strong><?= e((string)($action['observed'] ?? '—')) ?></strong></div>
                    <div><small><?= e($txt('Threshold', 'الحد')) ?></small><strong><?= e((string)($action['threshold'] ?? '—')) ?></strong></div>
                    <div><small><?= e($txt('Category', 'الفئة')) ?></small><strong><?= e((string)($action['category'] ?? 'action')) ?></strong></div>
                </div>

                <div class="review-explain-block">
                    <div><b><?= e($txt('Why this appeared', 'لماذا ظهر؟')) ?></b><span><?= e($getText($action, 'why', $getText($action, 'text', ''))) ?></span></div>
                    <div><b><?= e($txt('Recommended next step', 'الخطوة المقترحة')) ?></b><span><?= e($getText($action, 'recommendation', $txt('Open the source dashboard and validate the number.', 'افتح لوحة المصدر وتحقق من الرقم.'))) ?></span></div>
                    <div><b><?= e($txt('Review source', 'مصدر المراجعة')) ?></b><span><?= e($getText($action, 'review_source', $getText($action, 'link_label', 'Source dashboard'))) ?></span></div>
                </div>

                <div class="review-actions-row">
                    <?php if ($hasActionTarget): ?><a href="<?= e($actionUrl($action)) ?>"><?= e($getText($action, 'link_label', $txt('Open source dashboard', 'فتح اللوحة المصدر'))) ?> →</a><?php endif; ?>
                    <a class="secondary" href="executive-alert-rules-check.php?hospital=<?= e(strtolower((string)$hospitalCode)) ?>"><?= e($txt('Rules check', 'فحص القواعد')) ?> →</a>
                </div>
            </article>

                <section class="review-audit-timeline">
            <header>
                <div>
                    <small><?= e($txt('Cross-Day Oracle Audit History', 'تاريخ التدقيق على Oracle عبر الأيام')) ?></small>
                    <h3><?= e($txt('Complete saved review history for this action', 'السجل الكامل لتغييرات المراجعة لهذا الإجراء')) ?></h3>
                </div>
                <span><?= e($txt('Action history rows', 'صفوف سجل الإجراء')) ?>: <?= e((string)count($auditHistory)) ?> · <?= e($txt('Today total audit rows', 'إجمالي صفوف تدقيق اليوم')) ?>: <?= e((string)($reviewDiagnostics['audit_count_for_date'] ?? 0)) ?></span>
            </header>
            <?php if (!$auditHistory): ?>
                <div class="review-audit-empty">
                    <b><?= e($txt('No audit entries for this action yet.', 'لا توجد إدخالات تدقيق لهذا الإجراء حتى الآن.')) ?></b>
                    <span><?= e($txt('Save the review form once, then refresh this page or the workflow QA check to confirm Oracle audit insertion.', 'احفظ نموذج المراجعة مرة واحدة، ثم حدّث هذه الصفحة أو صفحة فحص سير المراجعة لتأكيد إدخال التدقيق في Oracle.')) ?></span>
                </div>
            <?php else: ?>
                <div class="review-audit-list">
                    <?php foreach ($auditHistory as $row): ?>
                        <?php
                        $oldStatus = (string)($row['old_status'] ?? '');
                        $newStatus = (string)($row['new_status'] ?? '');
                        $newNote = $clip((string)($row['new_note'] ?? ''), 240);
                        ?>
                        <article>
                            <div>
                                <strong><?= e($statusLabel($oldStatus)) ?> → <?= e($statusLabel($newStatus)) ?></strong>
                                <small><?= e((string)($row['operational_date'] ?? '—')) ?> · <?= e((string)($row['changed_at'] ?? '—')) ?> · <?= e((string)($row['changed_by'] ?? '—')) ?> · <?= e((string)($row['storage'] ?? $reviewStorage)) ?></small>
                            </div>
                            <?php if ($newNote !== ''): ?><p><?= e($newNote) ?></p><?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
            </div>

                        <aside class="review-side-card">
                <h3><?= e($txt('Review status', 'حالة المراجعة')) ?></h3>
                <?php if ($historicalOnly): ?>
                    <div class="review-historical-readonly">
                        <small><?= e($txt('Saved historical status', 'الحالة التاريخية المحفوظة')) ?></small>
                        <strong><?= e($statusLabel($status)) ?></strong>
                        <span><?= e($txt('Historical records are read-only here to protect the original operational-day decision.', 'السجلات التاريخية للقراءة فقط هنا لحماية قرار اليوم التشغيلي الأصلي.')) ?></span>
                    </div>
                <?php else: ?>
                    <form method="post" action="index.php?page=action-review&lang=<?= e(current_lang()) ?>">
                        <?= Csrf::field() ?>
                        <input type="hidden" name="action" value="<?= e($ruleId) ?>">
                        <label><?= e($txt('Status', 'الحالة')) ?></label>
                        <div class="review-status-options">
                            <?php
                            $statusOptions = [
                                'open' => $status === 'reviewed' ? $txt('Reopen', 'إعادة الفتح') : $txt('Open', 'مفتوح'),
                                'reviewed' => $txt('Reviewed', 'تمت المراجعة'),
                                'deferred' => $txt('Deferred', 'مؤجل'),
                            ];
                            ?>
                            <?php foreach ($statusOptions as $value => $label): ?>
                                <?php if (!in_array($value, $allowedTransitions, true)) { continue; } ?>
                                <label><input type="radio" name="status" value="<?= e($value) ?>" <?= $status === $value ? 'checked' : '' ?>> <span><?= e($label) ?></span></label>
                            <?php endforeach; ?>
                        </div>
                        <div class="review-transition-note">
                            <?= e($txt('Allowed workflow', 'المسار المسموح')) ?>:
                            <b><?= e($statusLabel($status)) ?></b>
                            <span>→ <?= e(implode(' / ', array_map($statusLabel, array_filter($allowedTransitions, function ($v) use ($status) { return $v !== $status; })))) ?: e($txt('Update note only', 'تحديث الملاحظة فقط')) ?></span>
                        </div>
                        <label for="review-note"><?= e($txt('Leadership note', 'ملاحظة القيادة')) ?></label>
                        <textarea id="review-note" name="note" rows="7" placeholder="<?= e($txt('Add the decision, owner, follow-up time, or reason for deferral...', 'أضف القرار أو المسؤول أو وقت المتابعة أو سبب التأجيل...')) ?>"><?= e((string)($review['note'] ?? '')) ?></textarea>
                        <button type="submit"><?= e($txt('Save review status', 'حفظ حالة المراجعة')) ?></button>
                    </form>
                <?php endif; ?>

                <div class="review-history-box">
                    <small><?= e($txt('Last review update', 'آخر تحديث للمراجعة')) ?></small>
                    <strong><?= e((string)($review['updated_at'] ?? '') ?: '—') ?></strong>
                    <span><?= e((string)($review['updated_by'] ?? '') ?: $txt('No saved review yet', 'لا توجد مراجعة محفوظة بعد')) ?></span>
                    <em class="review-count"><?= e($txt('Review count', 'عدد المراجعات')) ?>: <?= e((string)$reviewCount) ?></em>
                </div>

                <?php if ($previousReview): ?>
                    <div class="review-continuity-box">
                        <small><?= e($txt('Previous operational-day context', 'سياق المراجعة من يوم تشغيلي سابق')) ?></small>
                        <strong><?= e($statusLabel((string)($previousReview['status'] ?? 'open'))) ?> · <?= e((string)($previousReview['operational_date'] ?? '—')) ?></strong>
                        <span><?= e((string)($previousReview['updated_at'] ?? '—')) ?> · <?= e((string)($previousReview['updated_by'] ?? '—')) ?></span>
                        <?php if (!empty($previousReview['note'])): ?><p><?= e($clip((string)$previousReview['note'], 220)) ?></p><?php endif; ?>
                    </div>
                <?php endif; ?>

                <div class="review-audit-mini">
                    <small><?= e($txt('Audit trail storage', 'تخزين سجل التدقيق')) ?></small>
                    <strong><?= e($reviewStorage === 'oracle' ? 'Oracle' : 'JSON fallback') ?></strong>
                    <em><?= e($txt('Phase 10.6.6 review audit trail ready', 'سجل تدقيق المراجعات للمرحلة 10.6.6 جاهز')) ?></em>
                </div>
            </aside>
        </section>

        <section class="governance-editor-section">
            <header class="governance-editor-head">
                <div>
                    <small><?= e($txt('Phase 10.6.6 — Governance & Accountability', 'المرحلة 10.6.6 — الحوكمة والمساءلة')) ?></small>
                    <h3><?= e($txt('Ownership, due date, follow-up and resolution control', 'إدارة المسؤولية والاستحقاق والمتابعة والإغلاق')) ?></h3>
                    <p><?= e($txt('The accountability record persists across operational days and every change is preserved in a separate governance audit trail.', 'يبقى سجل المسؤولية مستمرًا عبر الأيام التشغيلية ويتم حفظ كل تغيير في سجل تدقيق مستقل للحوكمة.')) ?></p>
                </div>
                <div class="governance-editor-head-actions">
                    <span class="governance-storage-pill <?= $governanceStorage === 'oracle' ? 'is-oracle' : 'is-fallback' ?>"><?= e($governanceStorage === 'oracle' ? 'Oracle' : 'JSON fallback') ?></span>
                    <a href="index.php?page=action-governance-dashboard&lang=<?= e(current_lang()) ?>"><?= e($txt('Governance dashboard', 'لوحة الحوكمة')) ?> →</a>
                </div>
            </header>

            <?php if ($governanceStorage !== 'oracle'): ?>
                <div class="governance-storage-warning compact">
                    <strong><?= e($txt('Oracle governance tables are not active.', 'جداول حوكمة Oracle غير مفعلة.')) ?></strong>
                    <span><?= e($txt('Run database/executive_action_governance.sql to activate Oracle persistence. JSON fallback remains available until then.', 'شغّل database/executive_action_governance.sql لتفعيل التخزين على Oracle. وسيظل JSON الاحتياطي متاحًا حتى ذلك الحين.')) ?></span>
                </div>
            <?php endif; ?>

            <div class="governance-editor-grid">
                <article class="governance-form-card">
                    <div class="governance-current-state governance-status-<?= e($governanceStatus) ?>">
                        <small><?= e($txt('Current accountability status', 'حالة المساءلة الحالية')) ?></small>
                        <strong><?= e($governanceStatusLabel($governanceStatus)) ?></strong>
                        <?php if ((int)($governance['overdue_days'] ?? 0) > 0): ?><span><?= e((string)$governance['overdue_days']) ?> <?= e($txt('days overdue', 'يوم تأخير')) ?></span><?php endif; ?>
                    </div>

                    <?php if ($historicalOnly): ?>
                        <div class="review-historical-readonly">
                            <small><?= e($txt('Historical governance record', 'سجل حوكمة تاريخي')) ?></small>
                            <strong><?= e($txt('Read-only', 'للقراءة فقط')) ?></strong>
                            <span><?= e($txt('Historical actions are protected here. Current accountability can be managed from active actions.', 'الإجراءات التاريخية محمية هنا. تتم إدارة المساءلة الحالية من الإجراءات النشطة.')) ?></span>
                        </div>
                    <?php else: ?>
                        <form method="post" action="index.php?page=action-governance-update&lang=<?= e(current_lang()) ?>" class="governance-form">
                            <?= Csrf::field() ?>
                            <input type="hidden" name="action" value="<?= e($ruleId) ?>">
                            <div class="governance-form-row two-col">
                                <label><span><?= e($txt('Accountable owner', 'المسؤول المعتمد')) ?></span><input type="text" name="owner_name" maxlength="150" value="<?= e((string)($governance['owner_name'] ?? '')) ?>" placeholder="<?= e($txt('Leadership owner', 'المسؤول القيادي')) ?>"></label>
                                <label><span><?= e($txt('Assigned to', 'مسند إلى')) ?></span><input type="text" name="assigned_to" maxlength="150" value="<?= e((string)($governance['assigned_to'] ?? '')) ?>" placeholder="<?= e($txt('Execution owner', 'مسؤول التنفيذ')) ?>"></label>
                            </div>
                            <div class="governance-form-row two-col">
                                <label><span><?= e($txt('Due date', 'تاريخ الاستحقاق')) ?></span><input type="date" name="due_date" value="<?= e((string)($governance['due_date'] ?? '')) ?>"></label>
                                <label><span><?= e($txt('Follow-up date', 'تاريخ المتابعة')) ?></span><input type="date" name="follow_up_date" value="<?= e((string)($governance['follow_up_date'] ?? '')) ?>"></label>
                            </div>
                            <div class="governance-form-row two-col">
                                <label><span><?= e($txt('Escalation level', 'مستوى التصعيد')) ?></span><select name="escalation_level">
                                    <?php foreach (['none' => $txt('None', 'بدون'), 'watch' => $txt('Watch', 'متابعة'), 'high' => $txt('High', 'مرتفع'), 'critical' => $txt('Critical', 'حرج')] as $value => $label): ?>
                                        <option value="<?= e($value) ?>" <?= (string)($governance['escalation_level'] ?? 'none') === $value ? 'selected' : '' ?>><?= e($label) ?></option>
                                    <?php endforeach; ?>
                                </select></label>
                                <label><span><?= e($txt('Resolution status', 'حالة الإغلاق')) ?></span><select name="resolution_status">
                                    <option value="active" <?= (string)($governance['resolution_status'] ?? 'active') === 'active' ? 'selected' : '' ?>><?= e($txt('Active', 'نشط')) ?></option>
                                    <option value="resolved" <?= (string)($governance['resolution_status'] ?? 'active') === 'resolved' ? 'selected' : '' ?>><?= e($txt('Resolved', 'مغلق')) ?></option>
                                </select></label>
                            </div>
                            <label class="governance-resolution-note"><span><?= e($txt('Resolution note', 'ملاحظة الإغلاق')) ?></span><textarea name="resolution_note" rows="4" maxlength="2000" placeholder="<?= e($txt('Required when the action is resolved. Record the outcome and evidence.', 'مطلوبة عند إغلاق الإجراء. سجّل النتيجة والدليل.')) ?>"><?= e((string)($governance['resolution_note'] ?? '')) ?></textarea></label>
                            <button type="submit"><?= e($txt('Save governance & follow-up', 'حفظ الحوكمة والمتابعة')) ?></button>
                        </form>
                    <?php endif; ?>

                    <div class="governance-record-meta">
                        <span><b><?= e($txt('Last updated', 'آخر تحديث')) ?></b><?= e((string)($governance['updated_at'] ?? '') ?: '—') ?></span>
                        <span><b><?= e($txt('Updated by', 'بواسطة')) ?></b><?= e((string)($governance['updated_by'] ?? '') ?: '—') ?></span>
                        <span><b><?= e($txt('Governance updates', 'عدد تحديثات الحوكمة')) ?></b><?= e((string)($governance['update_count'] ?? 0)) ?></span>
                    </div>
                </article>

                <article class="governance-history-card">
                    <header><div><small><?= e($txt('Governance Audit Trail', 'سجل تدقيق الحوكمة')) ?></small><h4><?= e($txt('Ownership and follow-up history', 'تاريخ المسؤولية والمتابعة')) ?></h4></div><span><?= e((string)count($governanceHistory)) ?> <?= e($txt('events', 'أحداث')) ?></span></header>
                    <?php if (!$governanceHistory): ?>
                        <div class="governance-empty"><strong><?= e($txt('No governance changes saved yet.', 'لم يتم حفظ تغييرات حوكمة بعد.')) ?></strong><span><?= e($txt('The first ownership or follow-up save will create immutable audit evidence.', 'سيؤدي أول حفظ للمسؤولية أو المتابعة إلى إنشاء دليل تدقيق ثابت.')) ?></span></div>
                    <?php else: ?>
                        <div class="governance-history-list">
                            <?php foreach ($governanceHistory as $row): ?>
                                <?php
                                $changes = [];
                                if ((string)($row['old_owner_name'] ?? '') !== (string)($row['new_owner_name'] ?? '')) { $changes[] = $txt('Owner', 'المسؤول') . ': ' . ((string)($row['old_owner_name'] ?? '') ?: '—') . ' → ' . ((string)($row['new_owner_name'] ?? '') ?: '—'); }
                                if ((string)($row['old_assigned_to'] ?? '') !== (string)($row['new_assigned_to'] ?? '')) { $changes[] = $txt('Assigned', 'المنفذ') . ': ' . ((string)($row['old_assigned_to'] ?? '') ?: '—') . ' → ' . ((string)($row['new_assigned_to'] ?? '') ?: '—'); }
                                if ((string)($row['old_due_date'] ?? '') !== (string)($row['new_due_date'] ?? '')) { $changes[] = $txt('Due', 'الاستحقاق') . ': ' . ((string)($row['old_due_date'] ?? '') ?: '—') . ' → ' . ((string)($row['new_due_date'] ?? '') ?: '—'); }
                                if ((string)($row['old_follow_up_date'] ?? '') !== (string)($row['new_follow_up_date'] ?? '')) { $changes[] = $txt('Follow-up', 'المتابعة') . ': ' . ((string)($row['old_follow_up_date'] ?? '') ?: '—') . ' → ' . ((string)($row['new_follow_up_date'] ?? '') ?: '—'); }
                                if ((string)($row['old_esc_level'] ?? '') !== (string)($row['new_esc_level'] ?? '')) { $changes[] = $txt('Escalation', 'التصعيد') . ': ' . ((string)($row['old_esc_level'] ?? '') ?: 'none') . ' → ' . ((string)($row['new_esc_level'] ?? '') ?: 'none'); }
                                if ((string)($row['old_res_status'] ?? '') !== (string)($row['new_res_status'] ?? '')) { $changes[] = $txt('Resolution', 'الإغلاق') . ': ' . ((string)($row['old_res_status'] ?? '') ?: 'active') . ' → ' . ((string)($row['new_res_status'] ?? '') ?: 'active'); }
                                if (!$changes) { $changes[] = $txt('Governance note updated', 'تم تحديث ملاحظة الحوكمة'); }
                                ?>
                                <article>
                                    <div><strong><?= e(implode(' · ', $changes)) ?></strong><small><?= e((string)($row['changed_at'] ?? '—')) ?> · <?= e((string)($row['changed_by'] ?? '—')) ?> · <?= e((string)($row['storage'] ?? $governanceStorage)) ?></small></div>
                                    <?php if (!empty($row['new_res_note'])): ?><p><?= e($clip((string)$row['new_res_note'], 240)) ?></p><?php endif; ?>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </article>
            </div>
        </section>

        <section class="review-support-strip">
            <article><small><?= e($txt('Patient Flow', 'تدفق المرضى')) ?></small><strong><?= e($metric(($metrics['opd'] ?? 0) + ($metrics['er'] ?? 0) + ($metrics['admissions'] ?? 0))) ?></strong><em><?= e($txt('OPD + ER + Admissions', 'عيادات + طوارئ + دخول')) ?></em></article>
            <article><small><?= e($txt('Occupancy', 'الإشغال')) ?></small><strong><?= e($metric($metrics['occupancy_rate'] ?? null)) ?>%</strong><em><?= e($metric($metrics['available_beds'] ?? null)) ?> <?= e($txt('available beds', 'سرير متاح')) ?></em></article>
            <article><small><?= e($txt('Today Revenue', 'إيراد اليوم')) ?></small><strong><?= e(isset($metrics['today_total']) && $metrics['today_total'] !== null ? 'SAR ' . compact_money((float)$metrics['today_total']) : '—') ?></strong><em><?= e($txt('Operational finance day', 'اليوم المالي التشغيلي')) ?></em></article>
            <article><small><?= e($txt('Summary Layer', 'طبقة الملخص')) ?></small><strong><?= e(!empty($center['summary_available']) ? $txt('Active', 'مفعلة') : $txt('Unavailable', 'غير متاحة')) ?></strong><em><?= e(!empty($center['is_stale']) ? $txt('Stale', 'قديم') : $txt('Fresh', 'حديث')) ?></em></article>
        </section>
    <?php endif; ?>
</section>
