<?php
/**
 * Ads & Analytics — admin panel view.
 *
 *   • Ad Analytics: rewarded ads watched today, total unlocks granted,
 *     and the top-10 most active users (the 3-ads = 1-hour funnel).
 *   • House-Ad control: enable/disable the "Nadiplayer Premium"
 *     sponsored popup and fully customise it (title/body/image/link/CTA)
 *     so it can promote your own apps or a paying advertiser — WITHOUT
 *     touching real AdMob units.
 */
$s = get_settings();

// Ensure the analytics table exists (defined in api/routes/ad_free.php,
// required by index.php).
if (function_exists('ad_events_ensure_schema')) { ad_events_ensure_schema(); }

// Start of "today" in UTC.
$today_ts = strtotime(gmdate('Y-m-d') . ' 00:00:00 UTC');

$ads_today = 0; $unlocks_total = 0; $unlocks_today = 0; $top = [];
try {
    $ads_today     = (int)db()->query("SELECT COUNT(*) FROM ad_events WHERE type='watch'  AND created_ts >= $today_ts")->fetchColumn();
    $unlocks_total = (int)db()->query("SELECT COUNT(*) FROM ad_events WHERE type='unlock'")->fetchColumn();
    $unlocks_today = (int)db()->query("SELECT COUNT(*) FROM ad_events WHERE type='unlock' AND created_ts >= $today_ts")->fetchColumn();
    $top = db()->query(
        "SELECT e.user_id,
                SUM(e.type='watch')  AS watches,
                SUM(e.type='unlock') AS unlocks,
                MAX(e.created_ts)    AS last_ts
           FROM ad_events e
          GROUP BY e.user_id
          ORDER BY watches DESC
          LIMIT 10"
    )->fetchAll();
} catch (Throwable $e) { /* table may be brand new */ }

// Resolve usernames for the leaderboard.
$names = [];
if ($top) {
    $ids = array_column($top, 'user_id');
    $ph  = implode(',', array_fill(0, count($ids), '?'));
    try {
        $st = db()->prepare("SELECT id, username FROM users WHERE id IN ($ph)");
        $st->execute($ids);
        foreach ($st->fetchAll() as $u) { $names[$u['id']] = $u['username']; }
    } catch (Throwable $e) {}
}

// House-ad current values.
$ha_enabled = !empty($s['house_ad_enabled']);
$ha_title   = (string)($s['house_ad_title'] ?? 'NADIPLAYER PREMIUM');
$ha_body    = (string)($s['house_ad_body'] ?? 'Enjoy Nadiplayer with no ads, faster channel switching and exclusive premium streams.');
$ha_image   = (string)($s['house_ad_image_url'] ?? '');
$ha_image_t = (string)($s['house_ad_image_url_tablet'] ?? '');
$ha_image_v = (string)($s['house_ad_image_url_tv'] ?? '');
$ha_link    = (string)($s['house_ad_link_url'] ?? '');
$ha_cta     = (string)($s['house_ad_cta'] ?? 'Learn More');
$ha_skip    = (int)($s['house_ad_skip_secs'] ?? 5);
?>
<header class="page-head">
    <h1>Ads &amp; Analytics</h1>
    <p class="page-sub">Monitor the “3 ads = 1 hour” reward funnel and control the sponsored popup.</p>
</header>

<!-- ── Ad Analytics ──────────────────────────────────────────────── -->
<section class="stat-grid">
    <div class="stat">
        <div class="stat-label">Ads watched today</div>
        <div class="stat-value" data-testid="analytics-ads-today"><?= $ads_today ?></div>
        <div class="stat-foot">rewarded ads since 00:00 UTC</div>
    </div>
    <div class="stat">
        <div class="stat-label">Unlocks granted (total)</div>
        <div class="stat-value" data-testid="analytics-unlocks-total"><?= $unlocks_total ?></div>
        <div class="stat-foot"><?= $unlocks_today ?> today</div>
    </div>
    <div class="stat">
        <div class="stat-label">Reward threshold</div>
        <div class="stat-value">3 → 1h</div>
        <div class="stat-foot">ads watched per ad-free hour</div>
    </div>
</section>

<section class="card">
    <h2 class="card-title">Top 10 most active users</h2>
    <?php if (!$top): ?>
        <p class="hint">No rewarded-ad activity recorded yet. Once users start watching ads, the leaderboard appears here.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table class="users-table" data-testid="analytics-top-users">
            <thead>
                <tr><th style="width:40px">#</th><th>User</th><th>Ads watched</th><th>Unlocks</th><th>Last activity</th></tr>
            </thead>
            <tbody>
            <?php foreach ($top as $i => $r): ?>
                <tr>
                    <td class="muted"><?= $i + 1 ?></td>
                    <td>
                        <strong><?= h($names[$r['user_id']] ?? '—') ?></strong>
                        <div class="muted" style="font-size:10px"><?= h(substr((string)$r['user_id'], 0, 18)) ?></div>
                    </td>
                    <td style="color:var(--good);font-weight:600"><?= (int)$r['watches'] ?></td>
                    <td><?= (int)$r['unlocks'] ?></td>
                    <td class="muted" style="font-size:11px"><?= $r['last_ts'] ? h(gmdate('Y-m-d H:i', (int)$r['last_ts'])) . ' UTC' : '—' ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</section>

<!-- ── House-Ad control ──────────────────────────────────────────── -->
<form method="post" action="?page=ads_control" class="card">
    <input type="hidden" name="csrf"   value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="save_house_ad">
    <h2 class="card-title">“Nadiplayer Premium” sponsored popup</h2>
    <p class="hint" style="margin-top:-6px">
        This is the full-screen sponsored card shown when no AdMob interstitial fills.
        Toggle it on/off or repoint it at your own app / an advertiser. <strong>Does not affect real AdMob ads.</strong>
    </p>

    <div class="field-row">
        <label class="switch">
            <input type="checkbox" name="house_ad_enabled" value="1" <?= $ha_enabled ? 'checked' : '' ?> data-testid="house-ad-enable">
            <span class="switch-slider"></span>
            <span class="switch-label">Enable sponsored popup</span>
        </label>
    </div>

    <div class="field-row">
        <label for="house_ad_title">Title</label>
        <input type="text" id="house_ad_title" name="house_ad_title" value="<?= h($ha_title) ?>" data-testid="house-ad-title">
    </div>
    <div class="field-row">
        <label for="house_ad_body">Body text</label>
        <textarea id="house_ad_body" name="house_ad_body" rows="3" data-testid="house-ad-body"><?= h($ha_body) ?></textarea>
    </div>
    <div class="field-row field-row-2col">
        <div>
            <label for="house_ad_image_url">Phone image URL (full-screen background)</label>
            <input type="text" id="house_ad_image_url" name="house_ad_image_url" value="<?= h($ha_image) ?>" placeholder="https://…/promo-phone.jpg" data-testid="house-ad-image">
        </div>
        <div>
            <label for="house_ad_link_url">Link URL (opens on tap)</label>
            <input type="text" id="house_ad_link_url" name="house_ad_link_url" value="<?= h($ha_link) ?>" placeholder="https://play.google.com/…" data-testid="house-ad-link">
        </div>
    </div>
    <div class="field-row field-row-2col">
        <div>
            <label for="house_ad_image_url_tablet">Tablet image URL (optional)</label>
            <input type="text" id="house_ad_image_url_tablet" name="house_ad_image_url_tablet" value="<?= h($ha_image_t) ?>" placeholder="falls back to phone image" data-testid="house-ad-image-tablet">
        </div>
        <div>
            <label for="house_ad_image_url_tv">TV image URL (optional)</label>
            <input type="text" id="house_ad_image_url_tv" name="house_ad_image_url_tv" value="<?= h($ha_image_v) ?>" placeholder="falls back to phone image" data-testid="house-ad-image-tv">
        </div>
    </div>
    <p class="hint" style="margin-top:-6px">
        Background scales full-bleed (cover / centerCrop) on every screen. Supply separate
        Phone / Tablet / TV images for the sharpest fit; PNG &amp; JPEG both supported.
    </p>
    <div class="field-row field-row-2col">
        <div>
            <label for="house_ad_cta">Button label (CTA)</label>
            <input type="text" id="house_ad_cta" name="house_ad_cta" value="<?= h($ha_cta) ?>" data-testid="house-ad-cta">
        </div>
        <div>
            <label for="house_ad_skip_secs">Skip after (seconds)</label>
            <input type="number" id="house_ad_skip_secs" name="house_ad_skip_secs" value="<?= $ha_skip ?>" min="0" max="15" data-testid="house-ad-skip">
        </div>
    </div>

    <div class="form-actions">
        <button class="btn btn-primary" type="submit" data-testid="house-ad-save">Save popup settings</button>
    </div>
</form>
