<?php
declare(strict_types=1);

require_once __DIR__ . '/layout.php';
require_once __DIR__ . '/report-data.php';

function crm_report_page(string $key, string $title, string $description): void
{
    require_login();
    // Every CRM analytics page belongs to the single Reports permission group.
    // This also keeps newly added legacy MIS routes available without duplicating
    // one role-permission record for every report file.
    require_acl('can_view', 'modules/crm/reports/index.php');

    $data = crm_report_data($key);
    $kpis = $data['kpis'];
    $columns = $data['columns'];
    $rows = $data['rows'];
    $message = (string)($data['message'] ?? '');
    $filters = crm_report_filters();

    if (($_GET['export'] ?? '') === 'csv') {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $key . '-' . date('Y-m-d') . '.csv"');
        $stream = fopen('php://output', 'wb');
        if ($stream !== false) {
            fwrite($stream, "\xEF\xBB\xBF");
            fputcsv($stream, $columns);
            foreach ($rows as $row) {
                fputcsv($stream, $row);
            }
            fclose($stream);
        }
        exit;
    }

    crm_page_start($title, 'reports', $description);
    ?>
    <form class="command-bar" method="get">
        <strong><i class="fa-solid fa-filter"></i> Report Filters</strong>
        <div class="form-actions">
            <input class="control report-date" name="from" value="<?= crm_e($filters['from']) ?>" type="date" aria-label="From date">
            <input class="control report-date" name="to" value="<?= crm_e($filters['to']) ?>" type="date" aria-label="To date">
            <a class="button secondary" href="<?= crm_e(crm_url('reports/' . basename($_SERVER['PHP_SELF'] ?? 'index.php'))) ?>"><i class="fa-solid fa-rotate"></i> Reset</a>
            <button class="button primary" type="submit"><i class="fa-solid fa-magnifying-glass"></i> Apply</button>
            <button class="button secondary" type="submit" name="export" value="csv"><i class="fa-solid fa-file-export"></i> Export CSV</button>
        </div>
    </form>
    <?php if ($message !== ''): ?>
        <div class="report-notice"><i class="fa-solid fa-circle-info"></i><span><?= crm_e($message) ?></span></div>
    <?php endif; ?>
    <section class="kpi-grid">
        <?php foreach ($kpis as [$label, $value, $note]): ?>
            <article class="card kpi"><span><?= crm_e((string)$label) ?></span><strong><?= crm_e((string)$value) ?></strong><small><?= crm_e((string)$note) ?></small></article>
        <?php endforeach; ?>
    </section>
    <section class="card">
        <div class="card-head"><div class="card-title"><i class="fa-solid fa-table-list"></i><div><h2><?= crm_e($title) ?></h2><p><?= crm_e($description) ?></p></div></div></div>
        <div class="card-body table-wrap">
            <table class="data-table">
                <thead><tr><?php foreach ($columns as $column): ?><th><?= crm_e((string)$column) ?></th><?php endforeach; ?></tr></thead>
                <tbody>
                <?php if ($rows === []): ?>
                    <tr><td class="empty-table" colspan="<?= count($columns) ?>">No records found for the selected period.</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?><tr><?php foreach ($row as $cell): ?><td><?= crm_e((string)$cell) ?></td><?php endforeach; ?></tr><?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
    <?php
    crm_page_end();
}
