<?php
function phase109_card_icon(string $key): string {
    $icons = [
        'total' => '◈',
        'cash' => '●',
        'insurance' => '◐',
        'moh' => '◎',
        'profit_loss' => '◆',
    ];
    return $icons[$key] ?? '▦';
}

function phase109_total(array $cards, string $key, string $field): float {
    return isset($cards[$key][$field]) ? (float)$cards[$key][$field] : 0.0;
}

function phase109_card_title(string $key, array $card): string {
    $map = [
        'total' => 'revenue.total',
        'cash' => 'revenue.cash',
        'insurance' => 'revenue.insurance',
        'moh' => 'revenue.moh',
        'profit_loss' => 'revenue.profit_loss',
    ];
    return isset($map[$key]) ? t($map[$key]) : (string)($card['title'] ?? $key);
}

function phase109_chart_title(string $key, array $chart): string {
    $map = [
        'total' => 'chart.total',
        'cash' => 'chart.cash',
        'insurance' => 'chart.insurance',
        'moh' => 'chart.moh',
        'profit_loss' => 'chart.profit_loss',
    ];
    return isset($map[$key]) ? t($map[$key]) : (string)($chart['title'] ?? $key);
}

$totalRevenue = phase109_total($cards, 'total', 'current_total');
$compareRevenue = phase109_total($cards, 'total', 'compare_total');
$cashRevenue = phase109_total($cards, 'cash', 'current_total');
$insuranceRevenue = phase109_total($cards, 'insurance', 'current_total');
$cashPct = $totalRevenue > 0 ? min(100, round(($cashRevenue / $totalRevenue) * 100)) : 0;
$insurancePct = $totalRevenue > 0 ? min(100, round(($insuranceRevenue / $totalRevenue) * 100)) : 0;
$isRange = $mode === 'range';
$heroText = $isRange
    ? t('revenue.hero_range_text', [
        'hospital' => $hospital['name'],
        'from' => (string)$fromDate,
        'to' => (string)$toDate,
        'compareFrom' => (string)$compareFromDate,
        'compareTo' => (string)$compareToDate,
    ])
    : t('revenue.hero_text', ['hospital' => $hospital['name'], 'year' => $year, 'compareYear' => $compareYear]);
$currentPeriodLabel = $isRange ? ((string)$fromDate . ' → ' . (string)$toDate) : (string)$year;
$comparePeriodLabel = $isRange ? ((string)$compareFromDate . ' → ' . (string)$compareToDate) : (string)$compareYear;
?>

<section class="revenue-hero executive-hero compact-hero revenue109-hero" data-revenue-mode="<?= e($mode) ?>">
    <div class="hero-copy">
        <span class="overline light"><?= e(t('revenue.kicker')) ?></span>
        <h2><?= e(t('revenue.hero_title')) ?></h2>
        <p><?= e($heroText) ?></p>
        <div class="revenue109-period-strip" aria-label="<?= e(t('revenue.period_in_focus')) ?>">
            <span><b><?= e(t('revenue.current_period')) ?></b><strong><?= e($currentPeriodLabel) ?></strong></span>
            <span><b><?= e(t('revenue.compare_period')) ?></b><strong><?= e($comparePeriodLabel) ?></strong></span>
            <span><b><?= e(t('revenue.active_branch')) ?></b><strong><?= e((string)$hospital['name']) ?></strong></span>
        </div>
    </div>
    <div class="hero-totals">
        <div>
            <span><?= e(t('revenue.current_total')) ?></span>
            <strong><?= e(compact_money($totalRevenue)) ?></strong>
            <small><?= e(money_number($totalRevenue)) ?></small>
        </div>
        <div>
            <span><?= e(t('revenue.compare_total')) ?></span>
            <strong><?= e(compact_money($compareRevenue)) ?></strong>
            <small><?= e(money_number($compareRevenue)) ?></small>
        </div>
    </div>
</section>

<section class="surface-card filter-card revenue109-filter-card">
    <div class="filter-heading revenue109-filter-heading">
        <div>
            <span class="overline"><?= e(t('revenue.filter_title')) ?></span>
            <h2><?= e(t('revenue.filter_prompt')) ?></h2>
        </div>
        <div class="revenue109-mode-summary">
            <span><?= e(t('revenue.mode')) ?></span>
            <strong><?= e($isRange ? t('revenue.mode_range') : t('revenue.mode_year')) ?></strong>
        </div>
    </div>

    <?php if ($filterError !== ''): ?>
        <div class="revenue109-alert" role="alert"><?= e($filterError) ?></div>
    <?php endif; ?>

    <form method="get" action="index.php" class="filters revenue109-filters" data-revenue-filter-form>
        <input type="hidden" name="page" value="revenue">
        <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">

        <label>
            <span><?= e(t('revenue.hospital')) ?></span>
            <select name="hospital">
                <?php foreach ($hospitals as $code => $item): ?>
                    <option value="<?= e($code) ?>" <?= $code === $hospitalCode ? 'selected' : '' ?>><?= e($item['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>

        <label>
            <span><?= e(t('revenue.mode')) ?></span>
            <select name="mode" data-revenue-mode-select>
                <option value="year" <?= !$isRange ? 'selected' : '' ?>><?= e(t('revenue.mode_year')) ?></option>
                <option value="range" <?= $isRange ? 'selected' : '' ?>><?= e(t('revenue.mode_range')) ?></option>
            </select>
        </label>

        <label data-revenue-year-field>
            <span><?= e(t('revenue.current_year')) ?></span>
            <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
        </label>

        <label data-revenue-range-field>
            <span><?= e(t('revenue.from_date')) ?></span>
            <input type="date" name="from_date" value="<?= e((string)$fromDate) ?>">
        </label>

        <label data-revenue-range-field>
            <span><?= e(t('revenue.to_date')) ?></span>
            <input type="date" name="to_date" value="<?= e((string)$toDate) ?>">
        </label>

        <label>
            <span><?= e(t('revenue.compare_year')) ?></span>
            <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
        </label>

        <button class="btn primary revenue109-update" type="submit"><?= e(t('revenue.update')) ?></button>
    </form>

    <p class="revenue109-filter-help"><?= e($isRange ? t('revenue.range_help') : t('revenue.year_help')) ?></p>
</section>

<section class="metric-grid revenue-kpis revenue109-kpis">
    <?php foreach ($cards as $key => $card): ?>
        <?php $percent = $card['percent']; ?>
        <article class="revenue-kpi kpi-<?= e((string)$key) ?>">
            <div class="kpi-head">
                <span class="kpi-symbol"><?= e(phase109_card_icon((string)$key)) ?></span>
                <?php if ($percent !== null): ?>
                    <em class="delta <?= $percent >= 0 ? 'positive' : 'negative' ?>">
                        <?= $percent >= 0 ? '↑' : '↓' ?> <?= e(number_format(abs((float)$percent), 2)) ?>%
                    </em>
                <?php else: ?>
                    <em class="delta neutral">—</em>
                <?php endif; ?>
            </div>
            <span><?= e(phase109_card_title((string)$key, $card)) ?></span>
            <strong><?= e(compact_money($card['current_total'])) ?></strong>
            <small><?= e(t('revenue.compared_with_period')) ?>: <?= e(compact_money($card['compare_total'])) ?></small>
        </article>
    <?php endforeach; ?>
</section>

<section class="workspace-grid revenue-summary revenue109-summary">
    <article class="surface-card mix-card">
        <div class="section-head compact">
            <span class="overline"><?= e(t('revenue.mix_label')) ?></span>
            <h2><?= e(t('revenue.revenue_mix')) ?></h2>
        </div>
        <div class="mix-visual" style="--cash: <?= e((string)$cashPct) ?>%; --insurance: <?= e((string)$insurancePct) ?>%;">
            <span><?= e((string)$cashPct) ?>%</span>
        </div>
        <div class="mix-list">
            <div>
                <span><?= e(t('revenue.cash')) ?></span>
                <strong><?= e(compact_money($cashRevenue)) ?></strong>
                <div class="progress"><i style="width: <?= e((string)$cashPct) ?>%"></i></div>
            </div>
            <div>
                <span><?= e(t('revenue.insurance')) ?></span>
                <strong><?= e(compact_money($insuranceRevenue)) ?></strong>
                <div class="progress alt"><i style="width: <?= e((string)$insurancePct) ?>%"></i></div>
            </div>
        </div>
    </article>

    <article class="surface-card note-card revenue109-note-card">
        <div class="section-head compact">
            <span class="overline"><?= e(t('revenue.insight_label')) ?></span>
            <h2><?= e(t('revenue.quick_read')) ?></h2>
        </div>
        <p><?= e(t('revenue.quick_text')) ?></p>
        <dl class="revenue109-glance-list">
            <div><dt><?= e(t('revenue.current_period')) ?></dt><dd><?= e($currentPeriodLabel) ?></dd></div>
            <div><dt><?= e(t('revenue.compare_period')) ?></dt><dd><?= e($comparePeriodLabel) ?></dd></div>
            <div><dt><?= e(t('revenue.active_branch')) ?></dt><dd><?= e((string)$hospital['name']) ?></dd></div>
        </dl>
    </article>
</section>

<?php foreach ($charts as $key => $chart): ?>
    <?php
        $canvasId = 'chart_' . e((string)$key);
        $jsonId = 'chart_data_' . e((string)$key);
        $chartTitle = phase109_chart_title((string)$key, $chart);
        $payload = $chart['payload'];
        $payload['title'] = $chartTitle;
        $payload['locale'] = current_lang() === 'ar' ? 'ar-SA' : 'en-US';
        $payload['dir'] = current_dir();
    ?>
    <section class="surface-card chart-card revenue109-chart-card">
        <div class="chart-toolbar">
            <div>
                <span class="overline"><?= e(t('revenue.monthly_trend')) ?></span>
                <h2><?= e($chartTitle) ?></h2>
                <p><?= e($heroText) ?></p>
            </div>
            <div class="legend-pills revenue109-legend-pills">
                <span title="<?= e($currentPeriodLabel) ?>"><?= e($year) ?></span>
                <span title="<?= e($comparePeriodLabel) ?>"><?= e($compareYear) ?></span>
            </div>
        </div>

        <canvas id="<?= $canvasId ?>" class="chart" height="188"></canvas>
        <script type="application/json" id="<?= $jsonId ?>"><?= json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>

        <details class="data-details revenue109-data-details">
            <summary><?= e(t('revenue.show_months')) ?></summary>
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?= e(t('revenue.month')) ?></th>
                            <th><?= e($year) ?></th>
                            <th><?= e($compareYear) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($chart['rows'] as $row): ?>
                            <tr>
                                <td><?= e($row['month_name']) ?></td>
                                <td><?= e(money_number($row['current_value'])) ?></td>
                                <td><?= e(money_number($row['compare_value'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </details>
    </section>
<?php endforeach; ?>

<script>
window.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('script[type="application/json"][id^="chart_data_"]').forEach(function (node) {
        var key = node.id.replace('chart_data_', '');
        var payload = JSON.parse(node.textContent || '{}');
        window.renderBarCompareChart('chart_' + key, payload);
    });

    var modeSelect = document.querySelector('[data-revenue-mode-select]');
    var form = document.querySelector('[data-revenue-filter-form]');
    function syncRevenueMode() {
        if (!modeSelect || !form) return;
        var isRange = modeSelect.value === 'range';
        form.querySelectorAll('[data-revenue-range-field]').forEach(function (node) {
            node.hidden = !isRange;
        });
        form.querySelectorAll('[data-revenue-year-field]').forEach(function (node) {
            node.hidden = isRange;
        });
    }
    if (modeSelect) {
        modeSelect.addEventListener('change', syncRevenueMode);
        syncRevenueMode();
    }
});
</script>
