<?php
/**
 * View — Admin Report Subscriptions.
 *
 * @var array  $schedules       report_key => schedule row
 * @var array  $subscribers     report_key => [user_id => true]
 * @var array  $users           active users with email
 * @var array  $reports         ReportRenderer::REPORTS
 * @var array  $dowNames        1..7 => translated day name
 * @var array  $logicalOptions  key => translated label
 * @var array  $lastSends       last 10 send log entries
 */

$pageTitle = t('report_sub.title');
include WEBROOT_PATH . '/includes/header.php';
?>

<div class="admin-layout">
<?php include WEBROOT_PATH . '/includes/admin_sidebar.php'; ?>
<div class="admin-content">
<h1>📬 <?= t('report_sub.title') ?></h1>

<?php
/*
 * Aucun rapport a proposer : tous appartiennent a des modules desactives.
 * Le dire, plutot que d'afficher un formulaire a trois sections vides — dont
 * l'enregistrement ne ferait rien de bon.
 */
if ($reports === []): ?>
<div class="alert alert-warning">
    <?= htmlspecialchars(t('report_sub.no_active_module')) ?>
</div>
<div class="card">
    <a href="/admin/modules.php" class="btn btn-primary"><?= t('module.manage') ?></a>
</div>
</div><!-- .admin-content -->
</div><!-- .admin-layout -->
<?php include WEBROOT_PATH . '/includes/footer.php'; return; endif; ?>

<form method="post" action="/admin/report_subscriptions.php">
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(Session::get('csrf_token')) ?>">

    <!-- ── Section 1 : Planification ──────────────────────────────────── -->
    <h2 style="font-size:1rem;margin:1rem 0 .5rem"><?= t('report_sub.schedules_title') ?></h2>

    <?php foreach ($reports as $rk => $meta):
        $sched  = $schedules[$rk] ?? ['frequency' => 'daily', 'day_config' => null, 'time_of_day' => '08:00', 'enabled' => 0];
        $dc     = $sched['day_config'] ? json_decode($sched['day_config'], true) : [];
        $freq   = $sched['frequency'];
        $rkSafe = htmlspecialchars($rk);
    ?>
    <div class="card" style="margin-bottom:.75rem;padding:.75rem 1rem">
        <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap">
            <label style="display:inline-flex;align-items:center;gap:.3rem;font-weight:600;min-width:200px">
                <input type="checkbox" name="enabled_<?= $rkSafe ?>" value="1" <?= $sched['enabled'] ? 'checked' : '' ?>>
                <?= t($meta['label_key']) ?>
            </label>

            <select name="freq_<?= $rkSafe ?>" class="freq-select" data-rk="<?= $rkSafe ?>"
                    style="font-size:.85rem;padding:.2rem .4rem">
                <option value="daily"   <?= $freq === 'daily'   ? 'selected' : '' ?>><?= t('report_sub.frequency_daily') ?></option>
                <option value="weekly"  <?= $freq === 'weekly'  ? 'selected' : '' ?>><?= t('report_sub.frequency_weekly') ?></option>
                <option value="monthly" <?= $freq === 'monthly' ? 'selected' : '' ?>><?= t('report_sub.frequency_monthly') ?></option>
            </select>

            <!-- Weekly: day of week -->
            <select name="dow_<?= $rkSafe ?>" class="dow-cfg" data-rk="<?= $rkSafe ?>"
                    style="font-size:.85rem;padding:.2rem .4rem;<?= $freq !== 'weekly' ? 'display:none' : '' ?>">
                <?php foreach ($dowNames as $d => $name): ?>
                <option value="<?= $d ?>" <?= ($dc['dow'] ?? 1) == $d ? 'selected' : '' ?>><?= $name ?></option>
                <?php endforeach; ?>
            </select>

            <!-- Monthly config -->
            <span class="month-cfg" data-rk="<?= $rkSafe ?>" style="display:<?= $freq === 'monthly' ? 'inline-flex' : 'none' ?>;gap:.3rem;align-items:center">
                <select name="mtype_<?= $rkSafe ?>" class="mtype-select" data-rk="<?= $rkSafe ?>"
                        style="font-size:.82rem;padding:.2rem .3rem">
                    <option value="numeric" <?= isset($dc['dom']) ? 'selected' : '' ?>><?= t('report_sub.day_of_month') ?></option>
                    <option value="logical" <?= isset($dc['logical']) ? 'selected' : '' ?>><?= t('report_sub.logical_day') ?></option>
                </select>
                <input type="number" name="dom_<?= $rkSafe ?>" min="1" max="31"
                       value="<?= $dc['dom'] ?? 1 ?>"
                       class="dom-cfg" data-rk="<?= $rkSafe ?>"
                       style="width:50px;font-size:.82rem;padding:.2rem .3rem;<?= isset($dc['logical']) ? 'display:none' : '' ?>">
                <select name="logical_<?= $rkSafe ?>" class="logical-cfg" data-rk="<?= $rkSafe ?>"
                        style="font-size:.82rem;padding:.2rem .3rem;<?= !isset($dc['logical']) ? 'display:none' : '' ?>">
                    <?php foreach ($logicalOptions as $lk => $ll): ?>
                    <option value="<?= $lk ?>" <?= ($dc['logical'] ?? '') === $lk ? 'selected' : '' ?>><?= $ll ?></option>
                    <?php endforeach; ?>
                </select>
            </span>

            <input type="time" name="time_<?= $rkSafe ?>"
                   value="<?= htmlspecialchars($sched['time_of_day']) ?>"
                   style="font-size:.85rem;padding:.2rem .4rem">
        </div>
    </div>
    <?php endforeach; ?>

    <!-- ── Section 2 : Matrice ────────────────────────────────────────── -->
    <h2 style="font-size:1rem;margin:1.5rem 0 .5rem"><?= t('report_sub.matrix_title') ?></h2>

    <?php if (empty($users)): ?>
    <div class="card"><p style="margin:0;color:var(--color-text-muted)"><?= t('report_sub.no_users') ?></p></div>
    <?php else: ?>
    <div class="card" style="padding:0;overflow-x:auto">
    <table class="data-table" style="width:100%;font-size:.85rem">
        <thead>
            <tr>
                <th style="padding:.4rem .6rem"><?= t('report_sub.col_user') ?></th>
                <th style="padding:.4rem .6rem"><?= t('report_sub.col_email') ?></th>
                <?php foreach ($reports as $rk => $meta): ?>
                <th style="padding:.4rem .6rem;text-align:center;font-size:.78rem;max-width:120px">
                    <?= t($meta['label_key']) ?>
                </th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
            <tr style="border-bottom:1px solid var(--color-border,#eee)">
                <td style="padding:.4rem .6rem"><strong><?= htmlspecialchars($u['username']) ?></strong></td>
                <td style="padding:.4rem .6rem;font-size:.8rem"><?= htmlspecialchars($u['email']) ?></td>
                <?php foreach ($reports as $rk => $meta):
                    $checked = !empty($subscribers[$rk][$u['id']]);
                ?>
                <td style="padding:.4rem .6rem;text-align:center">
                    <input type="checkbox" name="sub[<?= htmlspecialchars($rk) ?>][<?= $u['id'] ?>]" value="1"
                           <?= $checked ? 'checked' : '' ?>>
                </td>
                <?php endforeach; ?>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>

    <div class="form-actions" style="margin-top:1rem">
        <button type="submit" class="btn btn-primary"><?= t('report_sub.save') ?></button>
    </div>
</form>

<!-- Dernier envoi -->
<?php if (!empty($lastSends)): ?>
<h2 style="font-size:1rem;margin:1.5rem 0 .5rem"><?= t('report_sub.log_title') ?></h2>
<div class="card" style="padding:0;overflow-x:auto">
<table class="data-table" style="width:100%;font-size:.82rem">
    <thead><tr>
        <th style="padding:.3rem .5rem"><?= t('report_sub.log_date') ?></th>
        <th style="padding:.3rem .5rem"><?= t('report_sub.log_report') ?></th>
        <th style="padding:.3rem .5rem"><?= t('report_sub.log_recipients') ?></th>
        <th style="padding:.3rem .5rem"><?= t('report_sub.log_status') ?></th>
    </tr></thead>
    <tbody>
    <?php foreach ($lastSends as $ls): ?>
    <tr style="border-bottom:1px solid var(--color-border,#eee)">
        <td style="padding:.3rem .5rem;font-family:monospace;font-size:.75rem"><?= htmlspecialchars($ls['sent_at']) ?></td>
        <td style="padding:.3rem .5rem"><?= htmlspecialchars($ls['report_key']) ?></td>
        <td style="padding:.3rem .5rem;text-align:center"><?= (int)$ls['recipient_count'] ?></td>
        <td style="padding:.3rem .5rem">
            <span class="badge badge-<?= $ls['status'] === 'ok' ? 'success' : 'danger' ?>" style="font-size:.7rem">
                <?= htmlspecialchars($ls['status']) ?>
            </span>
            <?php if ($ls['details']): ?>
            <small style="color:var(--color-text-muted)"><?= htmlspecialchars($ls['details']) ?></small>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>

</div><!-- .admin-content -->
</div><!-- .admin-layout -->

<script>window.AdminReportSub = {};</script>
<script src="/admin/assets/js/admin-report-subscriptions.js"></script>

<?php include WEBROOT_PATH . '/includes/footer.php'; ?>
