<?php
/**
 * Ads (AdMob) configuration page — legacy PHP admin_panel.
 *
 * Fields are stored in the same global settings document as everything
 * else, so changing them here immediately propagates to both the React
 * admin (/admin) and the public /api/public/ad-config endpoint that the
 * Capacitor app polls on launch.
 */

$s = get_settings();
$ads_enabled            = !empty($s['ads_enabled']);
// BUG-2 FIX (2026-05) — Users-vs-Guests sub-toggles. Defaults preserve
// the legacy behaviour (guests on, users off) when the legacy DB row
// doesn't have these columns yet.
$ads_for_users          = !empty($s['ads_enabled_for_users']);
$ads_for_guests         = array_key_exists('ads_enabled_for_guests', $s)
                            ? !empty($s['ads_enabled_for_guests'])
                            : $ads_enabled;
$ads_testing            = array_key_exists('ads_testing_mode', $s) ? !empty($s['ads_testing_mode']) : true;
$ads_app_id             = (string)($s['ads_app_id'] ?? '');
$ads_banner_id          = (string)($s['ads_banner_id'] ?? '');
$ads_interstitial_id    = (string)($s['ads_interstitial_id'] ?? '');
$ads_native_id          = (string)($s['ads_native_id'] ?? '');
// BUG FIX (2026-01) — Rewarded Ad Unit ID was missing from the legacy
// admin_panel view, so admins couldn't configure their real Rewarded
// publisher ID from this UI. The settings document already supports
// it (see api/routes/admin.php#DEFAULT_SETTINGS) — we just needed an
// input field.
$ads_rewarded_id        = (string)($s['ads_rewarded_id'] ?? '');
$ads_interstitial_every = (int)($s['ads_interstitial_every'] ?? 5);

// FEATURE (2026-01) — Smart TV custom "House Ad" banner.
$tv_banner_enabled    = !empty($s['tv_banner_enabled']);
$tv_banner_type       = (string)($s['tv_banner_type'] ?? 'image');
if (!in_array($tv_banner_type, ['image', 'html'], true)) $tv_banner_type = 'image';
$tv_banner_html       = (string)($s['tv_banner_html'] ?? '');
$tv_banner_image_url  = (string)($s['tv_banner_image_url'] ?? '');
$tv_banner_click_url  = (string)($s['tv_banner_click_url'] ?? '');
?>
<header class="page-head">
    <h1>Ads Settings · AdMob</h1>
    <p class="page-sub">
        Google AdMob integration for the NADIPLAY Capacitor app.
        Banner ads appear at the bottom of the Live TV / Movie player
        screens. Interstitial ads fire every N channel switches (you
        pick N). All settings here are read live by the app on launch —
        no APK rebuild needed when you change Ad Unit IDs.
    </p>
</header>

<?php if (!$ads_enabled): ?>
<section class="card" style="border-color:rgba(226,177,80,.35);background:linear-gradient(180deg,rgba(40,30,15,.45),rgba(20,15,8,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        ⚠️ Ads are currently <strong style="color:var(--warn)">OFF</strong> —
        even if you fill in the IDs below, the app will not mount any ad
        views until you tick <em>Enable Ads</em> and save.
    </p>
</section>
<?php elseif ($ads_testing): ?>
<section class="card" style="border-color:rgba(86,192,141,.35);background:linear-gradient(180deg,rgba(15,40,25,.45),rgba(8,20,15,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        ✅ Ads are <strong style="color:var(--good)">ON in TEST MODE</strong>.
        Devices see Google's universal test banners — your real AdMob
        account is not billed and can't get flagged for invalid clicks.
        Safe for development. Flip <em>Testing Mode</em> off when you're
        ready to ship real ads.
    </p>
</section>
<?php else: ?>
<section class="card" style="border-color:rgba(232,97,90,.45);background:linear-gradient(180deg,rgba(40,15,15,.45),rgba(20,8,8,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        🔴 Ads are <strong style="color:var(--danger)">LIVE</strong>.
        Devices see YOUR real ads and impressions count against your
        AdMob account. Monitor the AdMob dashboard for anomalies.
    </p>
</section>
<?php endif; ?>

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

    <h2>Master switches</h2>
    <div class="grid-2">
        <label class="field" style="flex-direction:row;align-items:center;gap:12px;">
            <input type="checkbox" name="ads_enabled" value="1"
                   <?= $ads_enabled ? 'checked' : '' ?>
                   data-testid="toggle-ads-enabled"
                   style="width:18px;height:18px;accent-color:var(--gold)">
            <div>
                <span style="display:block;font-size:13px;font-weight:600;color:var(--text)">Enable Ads</span>
                <span class="muted" style="font-size:11px">Turn off to instantly mute all banner/interstitial ads.</span>
            </div>
        </label>
        <label class="field" style="flex-direction:row;align-items:center;gap:12px;">
            <input type="checkbox" name="ads_testing_mode" value="1"
                   <?= $ads_testing ? 'checked' : '' ?>
                   data-testid="toggle-ads-testing"
                   style="width:18px;height:18px;accent-color:var(--gold)">
            <div>
                <span style="display:block;font-size:13px;font-weight:600;color:var(--text)">Testing Mode</span>
                <span class="muted" style="font-size:11px">ON = Google's test ads (safe). OFF = YOUR real ads.</span>
            </div>
        </label>
    </div>

    <!-- BUG-2 FIX (2026-05) — Audience toggles -->
    <h2 style="margin-top:24px">Audience</h2>
    <div class="grid-2">
        <label class="field" style="flex-direction:row;align-items:center;gap:12px;">
            <!-- Hidden "0" field BEFORE the checkbox guarantees the form
                 ALWAYS submits this key, even when unchecked. PHP $_POST
                 takes the last value, so checked=1 wins, unchecked=0. -->
            <input type="hidden" name="ads_enabled_for_users" value="0">
            <input type="checkbox" name="ads_enabled_for_users" value="1"
                   <?= $ads_for_users ? 'checked' : '' ?>
                   data-testid="toggle-ads-for-users"
                   style="width:18px;height:18px;accent-color:var(--gold)">
            <div>
                <span style="display:block;font-size:13px;font-weight:600;color:var(--text)">Show Ads to Users</span>
                <span class="muted" style="font-size:11px">Registered (logged-in) users see banner / interstitial / native ads. Per-user override on the Subscriber card still wins.</span>
            </div>
        </label>
        <label class="field" style="flex-direction:row;align-items:center;gap:12px;">
            <input type="hidden" name="ads_enabled_for_guests" value="0">
            <input type="checkbox" name="ads_enabled_for_guests" value="1"
                   <?= $ads_for_guests ? 'checked' : '' ?>
                   data-testid="toggle-ads-for-guests"
                   style="width:18px;height:18px;accent-color:var(--gold)">
            <div>
                <span style="display:block;font-size:13px;font-weight:600;color:var(--text)">Show Ads to Guests</span>
                <span class="muted" style="font-size:11px">Anyone using the app without logging in sees ads.</span>
            </div>
        </label>
    </div>

    <h2 style="margin-top:24px">AdMob Unit IDs</h2>
    <label class="field">
        <span>App ID <small>(also baked into AndroidManifest.xml at build time)</small></span>
        <input type="text" name="ads_app_id"
               value="<?= h($ads_app_id) ?>"
               data-testid="set-ads-app-id"
               placeholder="ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY">
    </label>
    <label class="field">
        <span>Banner Ad Unit ID</span>
        <input type="text" name="ads_banner_id"
               value="<?= h($ads_banner_id) ?>"
               data-testid="set-ads-banner-id"
               placeholder="ca-app-pub-XXXXXXXXXXXXXXXX/YYYYYYYYYY">
    </label>
    <label class="field">
        <span>Interstitial Ad Unit ID</span>
        <input type="text" name="ads_interstitial_id"
               value="<?= h($ads_interstitial_id) ?>"
               data-testid="set-ads-interstitial-id"
               placeholder="ca-app-pub-XXXXXXXXXXXXXXXX/YYYYYYYYYY">
    </label>
    <label class="field">
        <span>Native Ad Unit ID <small>(used by in-grid Sponsored cards — keeps 2:3 portrait poster aspect ratio)</small></span>
        <input type="text" name="ads_native_id"
               value="<?= h($ads_native_id) ?>"
               data-testid="set-ads-native-id"
               placeholder="ca-app-pub-XXXXXXXXXXXXXXXX/YYYYYYYYYY">
    </label>
    <label class="field">
        <span>Rewarded Ad Unit ID <small>(used by the "Watch N Ads → unlock ad-free" reward flow on the Account tab)</small></span>
        <input type="text" name="ads_rewarded_id"
               value="<?= h($ads_rewarded_id) ?>"
               data-testid="set-ads-rewarded-id"
               placeholder="ca-app-pub-XXXXXXXXXXXXXXXX/YYYYYYYYYY">
    </label>

    <h2 style="margin-top:24px">Interstitial frequency</h2>
    <label class="field">
        <span>Show interstitial every <strong><?= $ads_interstitial_every ?: 5 ?></strong> channel switches</span>
        <input type="number" name="ads_interstitial_every"
               min="0" max="100"
               value="<?= $ads_interstitial_every ?: 5 ?>"
               data-testid="set-ads-interstitial-every"
               style="max-width:120px">
        <small class="muted" style="margin-top:4px;display:block">
            0 = never fire an interstitial · 3–10 recommended · default 5
        </small>
    </label>

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

<!--
  FEATURE (2026-01) — Smart-TV "House Ad" banner.
  AdMob is strictly mobile (Android / iOS only) and does not work on
  Samsung Tizen / LG webOS. Admins use the form below to paste either
  an HTML snippet OR an image URL + click URL pair. The React frontend
  mounts <TVBanner /> at the bottom of the screen on TV builds only,
  so this never affects mobile users.
-->
<form method="post" action="?page=ads" class="card" style="margin-top:24px">
    <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="save_tv_banner">

    <header style="margin-bottom:8px">
        <h2 style="margin:0">Smart-TV House Banner <small class="muted" style="font-weight:400">(Tizen / webOS only)</small></h2>
        <p class="muted" style="font-size:12px;line-height:1.5;margin:6px 0 0">
            AdMob is not supported on Smart TVs. Use this slot to run
            your own house ads on Samsung Tizen / LG webOS builds —
            either paste a raw HTML snippet, or supply an image URL +
            click URL pair. The banner anchors to the bottom of the
            screen on TV only; mobile users see your AdMob banner
            instead.
        </p>
    </header>

    <label class="field" style="flex-direction:row;align-items:center;gap:12px;margin-top:12px">
        <input type="hidden" name="tv_banner_enabled" value="0">
        <input type="checkbox" name="tv_banner_enabled" value="1"
               <?= $tv_banner_enabled ? 'checked' : '' ?>
               data-testid="toggle-tv-banner-enabled"
               style="width:18px;height:18px;accent-color:var(--gold)">
        <div>
            <span style="display:block;font-size:13px;font-weight:600;color:var(--text)">Enable TV Banner</span>
            <span class="muted" style="font-size:11px">When OFF, no banner is mounted on Tizen / webOS.</span>
        </div>
    </label>

    <label class="field" style="margin-top:12px">
        <span>Banner type</span>
        <select name="tv_banner_type" data-testid="set-tv-banner-type">
            <option value="image" <?= $tv_banner_type === 'image' ? 'selected' : '' ?>>Image URL + Click URL</option>
            <option value="html"  <?= $tv_banner_type === 'html'  ? 'selected' : '' ?>>Raw HTML snippet</option>
        </select>
        <small class="muted">Both payloads are stored — switching between modes does not erase the other one. Only the selected mode is rendered.</small>
    </label>

    <fieldset style="border:1px solid var(--border);border-radius:8px;padding:12px;margin-top:12px">
        <legend style="font-size:12px;font-weight:600;color:var(--gold);padding:0 6px">Image + Click URL</legend>
        <label class="field">
            <span>Image URL</span>
            <input type="text" name="tv_banner_image_url"
                   value="<?= h($tv_banner_image_url) ?>"
                   data-testid="set-tv-banner-image-url"
                   placeholder="https://your-cdn.example/house-ad.jpg">
            <small class="muted">Recommended: a 1280×120 (10.7:1) banner so it sits cleanly on the TV's bottom strip.</small>
        </label>
        <label class="field">
            <span>Click URL <small>(optional)</small></span>
            <input type="text" name="tv_banner_click_url"
                   value="<?= h($tv_banner_click_url) ?>"
                   data-testid="set-tv-banner-click-url"
                   placeholder="https://your-landing-page.example/">
            <small class="muted">If empty, the banner is rendered as a non-clickable image.</small>
        </label>
    </fieldset>

    <fieldset style="border:1px solid var(--border);border-radius:8px;padding:12px;margin-top:12px">
        <legend style="font-size:12px;font-weight:600;color:var(--gold);padding:0 6px">Raw HTML snippet</legend>
        <label class="field">
            <span>HTML</span>
            <textarea name="tv_banner_html" rows="6"
                      data-testid="set-tv-banner-html"
                      placeholder="<a href='https://...'><img src='...' alt='Promo' style='height:100%'></a>"
                      style="font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px"><?= h($tv_banner_html) ?></textarea>
            <small class="muted">Rendered verbatim inside a sandboxed wrapper. Use inline styles. NEVER paste untrusted HTML.</small>
        </label>
    </fieldset>

    <div class="actions" style="margin-top:16px">
        <button type="submit" class="btn-primary" data-testid="save-tv-banner-btn">Save TV banner</button>
    </div>
</form>
