<?php
/** @var array<string,mixed>|null $doctorData */
$isAr = current_lang() === 'ar';
$fmt = static function ($value, string $format = 'count') use ($isAr): string {
    $value = (float)$value;
    if ($format === 'money') {
        if (abs($value) >= 1000000) {
            return number_format($value / 1000000, 2) . 'M';
        }
        return number_format($value, 0);
    }
    return number_format($value, 0);
};
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
?>

<div class="doctors1013-shell">
    <section class="doctors1013-hero">
        <div>
            <span class="doctors1013-kicker"><?= e(t('doctors.executive_kicker')) ?></span>
            <h2><?= e(t('doctors.executive_title')) ?></h2>
            <p><?= e(t('doctors.executive_text')) ?></p>
            <div class="doctors1013-period-strip">
                <span><small><?= e(t('doctors.current_period')) ?></small><strong><?= e((string)$year) ?></strong></span>
                <span><small><?= e(t('doctors.comparison_period')) ?></small><strong><?= e((string)$compareYear) ?></strong></span>
                <span><small><?= e(t('doctors.active_branch')) ?></small><strong><?= e($hospitalName) ?></strong></span>
            </div>
        </div>
        <div class="doctors1013-hero-summary">
            <span><?= e(t('doctors.primary_view')) ?></span>
            <strong><?= e(t('doctors.metric_revenue')) ?></strong>
            <small><?= e(t('doctors.hero_summary_hint')) ?></small>
        </div>
    </section>

    <section class="doctors1013-controls">
        <div class="doctors1013-section-head">
            <span><?= e(t('doctors.controls_kicker')) ?></span>
            <h2><?= e(t('doctors.controls_title')) ?></h2>
            <p><?= e(t('doctors.controls_text')) ?></p>
        </div>
        <form method="get" action="index.php" class="doctors1013-filter">
            <input type="hidden" name="page" value="doctors">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $years = $doctorData['availableYears'] ?? []; ?>
            <label>
                <span><?= e(t('doctors.current_year')) ?></span>
                <?php if (!empty($years)): ?>
                    <select name="year">
                        <?php foreach ($years as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$year ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" name="year" min="2014" max="2100" value="<?= e((string)$year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.compare_year')) ?></span>
                <?php if (!empty($years)): ?>
                    <select name="compare_year">
                        <?php foreach ($years as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$compareYear ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" name="compare_year" min="2014" max="2100" value="<?= e((string)$compareYear) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.metric')) ?></span>
                <select name="metric">
                    <?php foreach (($doctorData['availableMetrics'] ?? []) as $m): ?>
                        <option value="<?= e((string)$m['key']) ?>" <?= (string)$m['key'] === (string)$metric ? 'selected' : '' ?>><?= e(t((string)$m['label_key'])) ?></option>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['availableMetrics'])): ?>
                        <option value="TOT_REV"><?= e(t('doctors.metric_revenue')) ?></option>
                    <?php endif; ?>
                </select>
            </label>
            <button class="doctors1013-primary" type="submit"><?= e(t('doctors.update_report')) ?></button>
        </form>
    </section>

    <?php if ($dataError || !is_array($doctorData)): ?>
        <section class="doctors1013-state doctors1013-state-error">
            <strong><?= e(t('doctors.friendly_error_title')) ?></strong>
            <p><?= e(t('doctors.friendly_error_text')) ?></p>
        </section>
    <?php else: ?>
        <section class="doctors1013-kpi-grid">
            <?php foreach (($doctorData['cards'] ?? []) as $key => $card): ?>
                <?php $pct = $card['percent'] ?? null; ?>
                <article class="doctors1013-kpi doctors1013-kpi-<?= e((string)$key) ?>">
                    <div class="doctors1013-kpi-top">
                        <span><?= e((string)$card['title']) ?></span>
                        <?php if ($pct !== null): ?>
                            <em class="<?= (float)$pct >= 0 ? 'up' : 'down' ?>"><?= e(((float)$pct >= 0 ? '↑ ' : '↓ ') . number_format(abs((float)$pct), 1) . '%') ?></em>
                        <?php endif; ?>
                    </div>
                    <strong><?= e($fmt((float)$card['current_total'], (string)($card['format'] ?? 'count'))) ?></strong>
                    <?php if ($card['compare_total'] !== null): ?>
                        <small><?= e(t('doctors.compare_value')) ?>: <?= e($fmt((float)$card['compare_total'], (string)($card['format'] ?? 'count'))) ?></small>
                    <?php else: ?>
                        <small><?= e(t('doctors.active_hint')) ?></small>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="doctors1013-insight-grid">
            <article class="doctors1013-surface doctors1013-insight">
                <span class="doctors1013-kicker"><?= e(t('doctors.executive_insight_kicker')) ?></span>
                <h2><?= e(t('doctors.executive_insight_title')) ?></h2>
                <?php $movement = $doctorData['primaryMovement'] ?? null; ?>
                <?php if (is_array($movement)): ?>
                    <p><?= e(t('doctors.insight_movement', [
                        'metric' => (string)$movement['title'],
                        'direction' => (float)$movement['percent'] >= 0 ? t('doctors.direction_up') : t('doctors.direction_down'),
                        'percent' => number_format(abs((float)$movement['percent']), 1),
                    ])) ?></p>
                <?php else: ?>
                    <p><?= e(t('doctors.insight_stable')) ?></p>
                <?php endif; ?>
                <?php if (!empty($doctorData['topDoctor'])): ?>
                    <p><?= e(t('doctors.insight_top_doctor', [
                        'doctor' => (string)$doctorData['topDoctor']['label'],
                        'value' => number_format((float)$doctorData['topDoctor']['value'], 0),
                    ])) ?></p>
                <?php endif; ?>
                <?php if (!empty($doctorData['topSpecialty'])): ?>
                    <p><?= e(t('doctors.insight_top_specialty', [
                        'specialty' => (string)$doctorData['topSpecialty']['label'],
                    ])) ?></p>
                <?php endif; ?>
            </article>

            <article class="doctors1013-surface doctors1013-profile">
                <span class="doctors1013-kicker"><?= e(t('doctors.revenue_mix_kicker')) ?></span>
                <h2><?= e(t('doctors.revenue_mix_title')) ?></h2>
                <?php $mixTotal = 0.0; foreach (($doctorData['mix'] ?? []) as $row) { $mixTotal += max(0, (float)$row['value']); } ?>
                <div class="doctors1013-mix-list">
                    <?php foreach (($doctorData['mix'] ?? []) as $row): ?>
                        <?php $mixPct = $mixTotal > 0 ? ((float)$row['value'] / $mixTotal) * 100 : 0; ?>
                        <div><span><?= e((string)$row['label']) ?></span><strong><?= e(number_format((float)$row['value'], 0)) ?></strong><i><b style="width:<?= e(number_format(max(2, $mixPct), 2, '.', '')) ?>%"></b></i></div>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['mix'])): ?><p><?= e(t('doctors.no_mix')) ?></p><?php endif; ?>
                </div>
            </article>
        </section>

        <section class="doctors1013-chart-grid">
            <?php foreach (['doctors', 'specialties'] as $chartKey): ?>
                <?php $chart = $doctorData['charts'][$chartKey] ?? []; ?>
                <article class="doctors1013-surface doctors1013-chart-card" data-doctors-chart-shell="<?= e($chartKey) ?>" data-chart-state="pending">
                    <div class="doctors1013-section-head compact">
                        <span><?= e($chartKey === 'doctors' ? t('doctors.top_doctors_kicker') : t('doctors.specialty_kicker')) ?></span>
                        <h2><?= e((string)($chart['title'] ?? '')) ?></h2>
                    </div>
                    <div class="doctors1013-chart-stage">
                        <canvas id="doctors1013_chart_<?= e($chartKey) ?>" height="165"></canvas>
                        <div class="doctors1013-chart-state doctors1013-chart-empty">
                            <strong><?= e(t('doctors.no_chart_data_title')) ?></strong>
                            <p><?= e(t('doctors.no_chart_data_text')) ?></p>
                        </div>
                        <div class="doctors1013-chart-state doctors1013-chart-error">
                            <strong><?= e(t('doctors.chart_unavailable_title')) ?></strong>
                            <p><?= e(t('doctors.chart_unavailable_text')) ?></p>
                        </div>
                    </div>
                    <script type="application/json" id="doctors1013_data_<?= e($chartKey) ?>"><?= json_encode($chart['payload'] ?? [], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="doctors1013-surface doctors1013-table-card">
            <div class="doctors1013-section-head compact">
                <span><?= e(t('doctors.table_kicker')) ?></span>
                <h2><?= e(t('doctors.table_title')) ?></h2>
                <p><?= e(t('doctors.table_text')) ?></p>
            </div>
            <div class="doctors1013-table-wrap">
                <table>
                    <thead><tr><th>#</th><th><?= e(t('doctors.doctor')) ?></th><th><?= e(t('doctors.specialty')) ?></th><th><?= e(t('doctors.value')) ?></th><th><?= e(t('doctors.opd')) ?></th><th><?= e(t('doctors.inpatient')) ?></th></tr></thead>
                    <tbody>
                    <?php foreach (($doctorData['topDoctors'] ?? []) as $idx => $row): ?>
                        <tr>
                            <td><?= e((string)($idx + 1)) ?></td>
                            <td><strong><?= e((string)$row['label']) ?></strong></td>
                            <td><?= e((string)($row['secondary'] ?: t('common.not_available'))) ?></td>
                            <td><?= e(number_format((float)$row['value'], 0)) ?></td>
                            <td><?= e(number_format((float)$row['op_visits'], 0)) ?></td>
                            <td><?= e(number_format((float)$row['inpat_visits'], 0)) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['topDoctors'])): ?><tr><td colspan="6"><?= e(t('doctors.no_doctors')) ?></td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var gate = { expected: 2, rendered: 0, empty: 0, failed: 0, status: 'PENDING' };
            ['doctors', 'specialties'].forEach(function (key) {
                var shell = document.querySelector('[data-doctors-chart-shell="' + key + '"]');
                var node = document.getElementById('doctors1013_data_' + key);
                try {
                    var payload = JSON.parse(node ? (node.textContent || '{}') : '{}');
                    var values = [];
                    (payload.series || []).forEach(function (series) {
                        (series.values || []).forEach(function (value) { values.push(Number(value || 0)); });
                    });
                    if (!values.some(function (value) { return value !== 0; })) {
                        if (shell) shell.setAttribute('data-chart-state', 'empty');
                        gate.empty += 1;
                        return;
                    }
                    var result = window.renderBarCompareChart('doctors1013_chart_' + key, payload);
                    if (result && result.rendered) {
                        if (shell) shell.setAttribute('data-chart-state', 'rendered');
                        gate.rendered += 1;
                    } else {
                        if (shell) shell.setAttribute('data-chart-state', 'error');
                        gate.failed += 1;
                    }
                } catch (error) {
                    if (shell) shell.setAttribute('data-chart-state', 'error');
                    gate.failed += 1;
                }
            });
            gate.status = gate.failed === 0 && (gate.rendered + gate.empty) === gate.expected ? 'PASS' : 'FAIL';
            window.__DDB_DOCTORS_CHART_GATE__ = gate;
            document.documentElement.setAttribute('data-doctors-chart-expected', String(gate.expected));
            document.documentElement.setAttribute('data-doctors-chart-rendered', String(gate.rendered));
            document.documentElement.setAttribute('data-doctors-chart-empty', String(gate.empty));
            document.documentElement.setAttribute('data-doctors-chart-failed', String(gate.failed));
            document.documentElement.setAttribute('data-doctors-chart-gate', gate.status);
        });
        </script>
    <?php endif; ?>
</div>
