<?php
/**
 * Broadcast page — sits inside the legacy PHP admin panel.
 *
 * Reuses the same FCM functions defined in api/routes/notifications.php
 * which are already loaded (and their tables ensured) by index.php at the
 * top of every request, so we don't need to require them again here.
 */

// Counts for the header strip.
$total_tokens   = (int)db()->query('SELECT COUNT(*) FROM fcm_tokens')->fetchColumn();
$active_tokens  = (int)db()->query('SELECT COUNT(*) FROM fcm_tokens WHERE is_active = 1')->fetchColumn();
$now_ts         = time();
$live_watchers  = (int)db()->query(
    'SELECT COUNT(*) FROM stats_heartbeats WHERE updated_at_ts >= ' . ($now_ts - 90)
)->fetchColumn();

// Recent broadcasts (last 10).
$recent = db()->query(
    'SELECT id, title, body, route, total_tokens, sent, failed, pruned, last_error, last_detail, created_at, kind
     FROM fcm_broadcasts ORDER BY id DESC LIMIT 10'
)->fetchAll();

// Pull the project_id out of the service-account JSON so we can show
// it prominently — this is the #1 thing admins need to compare against
// the project_id inside their APK's google-services.json.
$sa_path       = fcm_service_account_path();
$sa_loaded     = is_file($sa_path);
$sa_project_id = null;
$sa_client_email = null;
if ($sa_loaded) {
    $raw = @file_get_contents($sa_path);
    $j = $raw ? json_decode($raw, true) : null;
    if (is_array($j)) {
        $sa_project_id   = $j['project_id']   ?? null;
        $sa_client_email = $j['client_email'] ?? null;
    }
}

// Capture the result of the most recent send so we can render a fat banner.
$last_result = $_SESSION['fcm_last_result'] ?? null;
unset($_SESSION['fcm_last_result']);
?>
<header class="page-head">
    <h1>Notifications · Broadcast</h1>
    <p class="page-sub">
        Send a Firebase push to every registered Android/iOS install of NADIPLAY.
        Devices that have been uninstalled or cleared their data are auto-pruned
        from the recipient list.
    </p>
</header>

<?php if ($sa_loaded && $sa_project_id): ?>
<section class="card" style="background:linear-gradient(180deg,rgba(15,30,40,.55),rgba(8,16,22,.55));border-color:rgba(86,160,210,.35);">
    <h2 style="color:#7cc2e8">🔥 Firebase project on this server</h2>
    <p style="font-size:13px;line-height:1.7;margin:6px 0 0">
        <strong>project_id:</strong>
        <code style="background:rgba(124,194,232,.15);color:#9fdcff;font-size:13px;padding:2px 8px;border-radius:6px;letter-spacing:.04em"><?= h($sa_project_id) ?></code>
        <br>
        <strong>service-account:</strong>
        <code style="font-size:11px"><?= h($sa_client_email ?? '?') ?></code>
    </p>
    <p class="hint" style="margin-top:10px;line-height:1.6">
        ⚠️ Your APK's <code>google-services.json</code> file <strong>must</strong> contain
        <strong>the exact same <code>project_id</code></strong> (look for <code>"project_info" → "project_id"</code>
        in that JSON file). If they differ, every push will fail with
        <code>INVALID_ARGUMENT</code> or <code>SENDER_ID_MISMATCH</code> — that's
        what's happening to your devices right now.
    </p>
</section>
<?php endif; ?>

<section class="stat-grid">
    <div class="stat">
        <div class="stat-label">Active devices</div>
        <div class="stat-value"><?= $active_tokens ?></div>
        <div class="stat-foot"><?= $total_tokens ?> total · <?= $total_tokens - $active_tokens ?> deactivated</div>
    </div>
    <div class="stat">
        <div class="stat-label">Watching now (last 90s)</div>
        <div class="stat-value"><?= $live_watchers ?></div>
        <div class="stat-foot">live + on-demand combined</div>
    </div>
    <div class="stat">
        <div class="stat-label">FCM service account</div>
        <div class="stat-value" style="font-size:14px;letter-spacing:0;text-transform:none;color:<?= $sa_loaded ? 'var(--good)' : 'var(--danger)' ?>;">
            <?= $sa_loaded ? 'Loaded' : 'MISSING' ?>
        </div>
        <div class="stat-foot">
            <?= $sa_loaded
                ? h(basename($sa_path))
                : 'Drop your firebase-service-account.json into api/secrets/' ?>
        </div>
    </div>
</section>

<?php if ($last_result): ?>
    <?php $cls = $last_result['sent'] > 0 ? 'success' : ($last_result['failed'] > 0 ? 'error' : 'info'); ?>
    <div class="flash flash-<?= $cls ?>" style="margin-bottom:18px;line-height:1.55">
        <strong>Result:</strong>
        Queued to <?= (int)$last_result['total_tokens'] ?> device(s) ·
        <span style="color:var(--good)"><?= (int)$last_result['sent'] ?> sent</span> ·
        <span style="color:var(--danger)"><?= (int)$last_result['failed'] ?> failed</span> ·
        <?= (int)$last_result['pruned'] ?> pruned
        <?php if (!empty($last_result['hint'])): ?>
            <div class="hint" style="margin-top:8px;color:#f3d28a">
                ⚠️ <?= h($last_result['hint']) ?>
            </div>
        <?php endif; ?>
        <?php if (empty($last_result['hint']) && !empty($last_result['last_error'])): ?>
            <div class="hint" style="margin-top:8px;color:#f3d28a">
                FCM said: <code><?= h($last_result['last_error']) ?></code>
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>

<form method="post" action="?page=broadcast" class="card">
    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="send_broadcast">

    <h2>Compose</h2>
    <label class="field">
        <span>Title <small>(required, max 60 chars)</small></span>
        <input type="text" name="title" maxlength="60" required placeholder="Server maintenance tonight">
    </label>
    <label class="field">
        <span>Body <small>(required)</small></span>
        <textarea name="body" rows="4" required placeholder="We'll be offline 02:00–02:30 UTC for upgrades. Thanks for your patience!"></textarea>
    </label>

    <h2 style="margin-top:24px">Recipient</h2>
    <div class="grid-2">
        <label class="field">
            <span>Send to</span>
            <select name="recipient_kind" id="recipient_kind"
                    onchange="document.getElementById('uid_row').style.display = this.value === 'user' ? '' : 'none';">
                <option value="all">All devices</option>
                <option value="user">Single user (by user_id)</option>
            </select>
        </label>
        <label class="field" id="uid_row" style="display:none">
            <span>User ID <small>(from Subscribers page)</small></span>
            <input type="text" name="target_user_id" placeholder="UUID copied from Users tab">
        </label>
    </div>

    <h2 style="margin-top:24px">Optional deep-link</h2>
    <label class="field">
        <span>Route <small>(opens this in-app screen on tap, e.g. <code>/live-tv</code>)</small></span>
        <input type="text" name="route" placeholder="/live-tv">
    </label>

    <div class="actions">
        <button type="submit" class="btn-primary" data-testid="send-notification-btn">Send Notification</button>
    </div>
</form>

<?php
// Show a "rehydrate" form only when there are pruned tokens — useful for
// retesting after fixing a project mismatch.
$deactivated_count = $total_tokens - $active_tokens;
if ($deactivated_count > 0):
?>
<section class="card" style="background:linear-gradient(180deg,rgba(40,30,15,.55),rgba(20,15,8,.55));border-color:rgba(226,177,80,.35);">
    <h2 style="color:var(--warn)">Reactivate pruned tokens</h2>
    <p class="hint" style="margin-top:6px;line-height:1.6">
        <?= $deactivated_count ?> token(s) were auto-pruned after FCM rejected them.
        After fixing your Firebase project mismatch (replace
        <code>api/secrets/firebase-service-account.json</code> with the JSON
        from the SAME project as your APK), click below to re-enable them and
        try sending again. If they're still rejected, the only fix is to
        rebuild the APK against the matching project.
    </p>
    <form method="post" action="?page=broadcast" style="margin-top:10px">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="reactivate_tokens">
        <button type="submit" class="btn-secondary" data-testid="reactivate-tokens-btn"
                onclick="return confirm('Reactivate all <?= $deactivated_count ?> pruned token(s)?')">
            Reactivate <?= $deactivated_count ?> pruned token(s)
        </button>
    </form>
</section>
<?php endif; ?>

<section class="card">
    <h2>Recent broadcasts</h2>
    <?php if (!$recent): ?>
        <p class="hint">No broadcasts yet.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table class="users-table">
                <thead>
                    <tr>
                        <th>When</th>
                        <th>Title</th>
                        <th>Recipients</th>
                        <th>Sent</th>
                        <th>Failed</th>
                        <th>Reason</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($recent as $b): ?>
                    <tr>
                        <td class="muted" style="font-size:11px;white-space:nowrap;">
                            <?= h(substr((string)$b['created_at'], 0, 19)) ?>
                        </td>
                        <td>
                            <strong><?= h($b['title']) ?></strong>
                            <div class="muted" style="font-size:11px;margin-top:2px;max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                                <?= h($b['body']) ?>
                            </div>
                        </td>
                        <td><?= (int)$b['total_tokens'] ?></td>
                        <td style="color:var(--good)"><?= (int)$b['sent'] ?></td>
                        <td style="color:<?= ((int)$b['failed']) > 0 ? 'var(--danger)' : 'var(--muted)' ?>">
                            <?= (int)$b['failed'] ?>
                            <?php if ((int)$b['pruned']): ?>
                                <span class="muted" style="font-size:10px"> · <?= (int)$b['pruned'] ?> pruned</span>
                            <?php endif; ?>
                        </td>
                        <td class="muted" style="font-size:11px;">
                            <?php if ($b['last_error']): ?>
                                <strong style="color:var(--danger);font-weight:600"><?= h($b['last_error']) ?></strong>
                                <?php if (!empty($b['last_detail'])): ?>
                                    <div style="margin-top:3px;color:var(--muted);font-size:10px;line-height:1.4;max-width:280px">
                                        <?= h($b['last_detail']) ?>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                —
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>
