<?php

declare(strict_types=1);

$isArabic = current_lang() === 'ar';
$txt = function (string $en, string $ar) use ($isArabic): string { return $isArabic ? $ar : $en; };
$getText = function (array $row, string $key, string $fallback = '') use ($isArabic): string {
    if ($isArabic && isset($row[$key . '_ar']) && trim((string)$row[$key . '_ar']) !== '') { return (string)$row[$key . '_ar']; }
    return isset($row[$key]) && trim((string)$row[$key]) !== '' ? (string)$row[$key] : $fallback;
};

$center = is_array($center ?? null) ? $center : [];
$governance = is_array($governance ?? null) ? $governance : [];
$governanceDiagnostics = is_array($governanceDiagnostics ?? null) ? $governanceDiagnostics : [];
$hospital = is_array($hospital ?? null) ? $hospital : [];
$op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
$actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
$operationalDate = (string)($op['operational_date'] ?? $governance['operational_date'] ?? date('Y-m-d'));
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)($hospitalCode ?? 'NJCH')));
$lastUpdated = (string)($center['last_updated'] ?? '');
$storage = (string)($governance['storage'] ?? $governanceDiagnostics['storage_mode'] ?? 'json_fallback');
$queue = is_array($governance['accountability_queue'] ?? null) ? $governance['accountability_queue'] : [];
$owners = is_array($governance['owner_workload'] ?? null) ? $governance['owner_workload'] : [];
$recent = is_array($governance['recent_activity'] ?? null) ? $governance['recent_activity'] : [];

$statusLabel = function (string $status) 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', 'على المسار'),
    ];
    return $map[strtolower($status)] ?? ucfirst(str_replace('_', ' ', $status));
};
$escLabel = function (string $level) use ($txt): string {
    $map = [
        'none' => $txt('None', 'بدون'),
        'watch' => $txt('Watch', 'متابعة'),
        'high' => $txt('High', 'مرتفع'),
        'critical' => $txt('Critical', 'حرج'),
    ];
    return $map[strtolower($level)] ?? ucfirst($level);
};
$actionTitle = function (string $key) use ($actions, $getText): string {
    foreach ($actions as $action) {
        if (is_array($action) && (string)($action['rule_id'] ?? '') === $key) {
            return $getText($action, 'title', $key);
        }
    }
    return $key;
};
?>

<section class="action-center governance-dashboard phase-10-6-6">
    <?php if (!empty($centerError)): ?>
        <div class="action-error"><strong><?= e($txt('Governance dashboard could not fully load.', 'تعذر تحميل لوحة الحوكمة بالكامل.')) ?></strong><span><?= e((string)$centerError) ?></span></div>
    <?php endif; ?>

    <section class="action-hero governance-hero">
        <div class="action-hero-copy">
            <span class="action-overline">Phase 10.6.6</span>
            <h2><?= e($txt('Executive Governance & Follow-up', 'حوكمة الإجراءات والمتابعة التنفيذية')) ?></h2>
            <p><?= e($txt('Assign accountability, control due dates, manage follow-up commitments, track escalation, and close actions with auditable resolution evidence.', 'إسناد المسؤولية وضبط تواريخ الاستحقاق وإدارة المتابعة والتصعيد وإغلاق الإجراءات مع دليل تدقيق كامل.')) ?></p>
            <div class="action-hero-tags">
                <span><?= e($txt('Branch', 'الفرع')) ?>: <b><?= e($hospitalName) ?></b></span>
                <span><?= e($txt('Operational Day', 'اليوم التشغيلي')) ?>: <b><?= e($operationalDate) ?></b></span>
                <span><?= e($txt('Last Updated', 'آخر تحديث')) ?>: <b><?= e($lastUpdated ?: '—') ?></b></span>
                <span class="review-flow-pill"><b><?= e($txt('Governance Storage', 'تخزين الحوكمة')) ?></b>: <?= e($storage === 'oracle' ? 'Oracle' : 'JSON fallback') ?></span>
            </div>
        </div>
        <div class="governance-hero-actions">
            <a class="governance-back-link" href="index.php?page=action-center&lang=<?= e(current_lang()) ?>">← <?= e($txt('Back to Action Center', 'العودة إلى مركز الإجراءات')) ?></a>
            <a class="governance-review-link" href="index.php?page=action-review-dashboard&lang=<?= e(current_lang()) ?>"><?= e($txt('Review Dashboard', 'لوحة المراجعات')) ?> →</a>
        </div>
    </section>

    <?php if ($storage !== 'oracle'): ?>
        <section class="governance-storage-warning">
            <div><strong><?= e($txt('Oracle governance tables are not active yet.', 'جداول حوكمة Oracle غير مفعلة بعد.')) ?></strong><span><?= e($txt('The feature is running in JSON fallback mode. Run database/executive_action_governance.sql, then reopen this page.', 'الميزة تعمل حاليًا بوضع JSON الاحتياطي. شغّل database/executive_action_governance.sql ثم أعد فتح الصفحة.')) ?></span></div>
            <a href="executive-action-governance-storage-check.php?hospital=<?= e(strtolower((string)$hospitalCode)) ?>"><?= e($txt('Open storage check', 'فتح فحص التخزين')) ?> →</a>
        </section>
    <?php endif; ?>

    <section class="governance-kpi-grid">
        <article class="governance-kpi"><small><?= e($txt('Active actions', 'إجراءات نشطة')) ?></small><strong><?= e((string)($governance['active'] ?? 0)) ?></strong><em><?= e($txt('still requiring accountability', 'ما زالت تتطلب مسؤولية')) ?></em></article>
        <article class="governance-kpi governance-kpi-overdue"><small><?= e($txt('Overdue', 'متأخر')) ?></small><strong><?= e((string)($governance['overdue'] ?? 0)) ?></strong><em><?= e($txt('past due date', 'تجاوزت تاريخ الاستحقاق')) ?></em></article>
        <article class="governance-kpi governance-kpi-follow"><small><?= e($txt('Follow-up due', 'متابعة مستحقة')) ?></small><strong><?= e((string)($governance['follow_up_due'] ?? 0)) ?></strong><em><?= e($txt('needs follow-up now', 'تحتاج متابعة الآن')) ?></em></article>
        <article class="governance-kpi governance-kpi-unassigned"><small><?= e($txt('Unassigned', 'غير مسند')) ?></small><strong><?= e((string)($governance['unassigned'] ?? 0)) ?></strong><em><?= e($txt('no owner or assignee', 'دون مسؤول أو منفذ')) ?></em></article>
        <article class="governance-kpi governance-kpi-escalated"><small><?= e($txt('Escalated', 'مصعّد')) ?></small><strong><?= e((string)($governance['escalated'] ?? 0)) ?></strong><em><?= e($txt('watch / high / critical', 'متابعة / مرتفع / حرج')) ?></em></article>
        <article class="governance-kpi governance-kpi-resolved"><small><?= e($txt('Resolved', 'مغلق')) ?></small><strong><?= e((string)($governance['resolved'] ?? 0)) ?></strong><em><?= e($txt('closed with evidence', 'مغلق مع دليل')) ?></em></article>
    </section>

    <section class="governance-main-grid">
        <article class="governance-panel governance-queue-panel">
            <header><div><small><?= e($txt('Accountability Queue', 'قائمة المساءلة')) ?></small><h3><?= e($txt('Actions requiring executive follow-up', 'إجراءات تتطلب متابعة تنفيذية')) ?></h3></div><span><?= e((string)count($queue)) ?> <?= e($txt('active', 'نشط')) ?></span></header>
            <?php if (!$queue): ?>
                <div class="governance-empty"><strong><?= e($txt('No active accountability items.', 'لا توجد عناصر مساءلة نشطة.')) ?></strong><span><?= e($txt('All current actions are resolved.', 'جميع الإجراءات الحالية مغلقة.')) ?></span></div>
            <?php else: ?>
                <div class="governance-queue-list">
                    <?php foreach ($queue as $row): ?>
                        <?php $key = (string)($row['action_key'] ?? ''); $accountability = (string)($row['accountability_status'] ?? 'unassigned'); ?>
                        <a class="governance-queue-row governance-status-<?= e($accountability) ?>" href="index.php?page=action-review&action=<?= e(rawurlencode($key)) ?>&lang=<?= e(current_lang()) ?>">
                            <div class="governance-queue-main">
                                <span class="governance-severity governance-severity-<?= e((string)($row['severity'] ?? 'routine')) ?>"><?= e(strtoupper((string)($row['severity'] ?? 'routine'))) ?></span>
                                <strong><?= e($isArabic && !empty($row['title_ar']) ? (string)$row['title_ar'] : (string)($row['title'] ?? $key)) ?></strong>
                                <small><?= e($statusLabel($accountability)) ?></small>
                            </div>
                            <div class="governance-queue-meta">
                                <span><b><?= e($txt('Owner', 'المسؤول')) ?></b><?= e((string)($row['owner_name'] ?? '') ?: '—') ?></span>
                                <span><b><?= e($txt('Assigned', 'المنفذ')) ?></b><?= e((string)($row['assigned_to'] ?? '') ?: '—') ?></span>
                                <span><b><?= e($txt('Due', 'الاستحقاق')) ?></b><?= e((string)($row['due_date'] ?? '') ?: '—') ?></span>
                                <span><b><?= e($txt('Escalation', 'التصعيد')) ?></b><?= e($escLabel((string)($row['escalation_level'] ?? 'none'))) ?></span>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </article>

        <aside class="governance-panel governance-owner-panel">
            <header><div><small><?= e($txt('Accountability', 'المساءلة')) ?></small><h3><?= e($txt('Owner workload', 'أعباء المسؤولين')) ?></h3></div><span><?= e((string)count($owners)) ?> <?= e($txt('owners', 'مسؤولين')) ?></span></header>
            <?php if (!$owners): ?>
                <div class="governance-empty compact"><strong><?= e($txt('No ownership data yet.', 'لا توجد بيانات إسناد بعد.')) ?></strong></div>
            <?php else: ?>
                <div class="governance-owner-list">
                    <?php foreach ($owners as $owner): ?>
                        <article>
                            <div><strong><?= e((string)($owner['owner'] ?? 'Unassigned')) ?></strong><small><?= e((string)($owner['active'] ?? 0)) ?> <?= e($txt('active', 'نشط')) ?> · <?= e((string)($owner['resolved'] ?? 0)) ?> <?= e($txt('resolved', 'مغلق')) ?></small></div>
                            <div class="governance-owner-counts"><span><?= e((string)($owner['overdue'] ?? 0)) ?> <?= e($txt('overdue', 'متأخر')) ?></span><span><?= e((string)($owner['escalated'] ?? 0)) ?> <?= e($txt('escalated', 'مصعّد')) ?></span></div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </aside>
    </section>

    <section class="governance-panel governance-current-actions">
        <header><div><small><?= e($txt('Current Worklist', 'قائمة الإجراءات الحالية')) ?></small><h3><?= e($txt('Governance state by action', 'حالة الحوكمة حسب الإجراء')) ?></h3></div><span><?= e((string)count($actions)) ?> <?= e($txt('actions', 'إجراءات')) ?></span></header>
        <div class="governance-action-grid">
            <?php foreach ($actions as $action): ?>
                <?php if (!is_array($action)) { continue; } $gov = is_array($action['governance'] ?? null) ? $action['governance'] : []; $key = (string)($action['rule_id'] ?? ''); $state = (string)($gov['accountability_status'] ?? 'unassigned'); ?>
                <a class="governance-action-card governance-status-<?= e($state) ?>" href="index.php?page=action-review&action=<?= e(rawurlencode($key)) ?>&lang=<?= e(current_lang()) ?>">
                    <div class="governance-action-card-head"><span><?= e(strtoupper((string)($action['severity'] ?? 'routine'))) ?></span><em><?= e($statusLabel($state)) ?></em></div>
                    <strong><?= e($getText($action, 'title', $key)) ?></strong>
                    <div class="governance-action-card-meta"><span><?= e($txt('Owner', 'المسؤول')) ?>: <b><?= e((string)($gov['owner_name'] ?? '') ?: '—') ?></b></span><span><?= e($txt('Due', 'الاستحقاق')) ?>: <b><?= e((string)($gov['due_date'] ?? '') ?: '—') ?></b></span><span><?= e($txt('Follow-up', 'المتابعة')) ?>: <b><?= e((string)($gov['follow_up_date'] ?? '') ?: '—') ?></b></span></div>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="governance-panel governance-audit-panel">
        <header><div><small><?= e($txt('Governance Audit Trail', 'سجل تدقيق الحوكمة')) ?></small><h3><?= e($txt('Recent ownership and follow-up changes', 'آخر تغييرات المسؤولية والمتابعة')) ?></h3></div><span><?= e((string)count($recent)) ?> <?= e($txt('events', 'أحداث')) ?></span></header>
        <?php if (!$recent): ?>
            <div class="governance-empty"><strong><?= e($txt('No governance audit events yet.', 'لا توجد أحداث تدقيق للحوكمة بعد.')) ?></strong><span><?= e($txt('The first saved ownership or follow-up change will appear here.', 'سيظهر هنا أول تغيير محفوظ في المسؤولية أو المتابعة.')) ?></span></div>
        <?php else: ?>
            <div class="governance-audit-list">
                <?php foreach ($recent as $row): ?>
                    <?php $key = (string)($row['action_key'] ?? ''); ?>
                    <article>
                        <div><strong><?= e($actionTitle($key)) ?></strong><small><?= e((string)($row['changed_at'] ?? '—')) ?> · <?= e((string)($row['changed_by'] ?? '—')) ?></small></div>
                        <span><?= e($txt('Owner', 'المسؤول')) ?>: <?= e((string)($row['old_owner_name'] ?? '') ?: '—') ?> → <?= e((string)($row['new_owner_name'] ?? '') ?: '—') ?></span>
                        <span><?= e($txt('Due', 'الاستحقاق')) ?>: <?= e((string)($row['old_due_date'] ?? '') ?: '—') ?> → <?= e((string)($row['new_due_date'] ?? '') ?: '—') ?></span>
                        <span><?= e($txt('Escalation', 'التصعيد')) ?>: <?= e($escLabel((string)($row['old_esc_level'] ?? 'none'))) ?> → <?= e($escLabel((string)($row['new_esc_level'] ?? 'none'))) ?></span>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</section>
