<?php
/** /api/public/* and /api/shared-profiles, /api/subscription/status */

function route_public_shared_xtream(): void {
    $s = get_settings_doc();
    send_json([
        'server'     => $s['shared_xtream_server']   ?? '',
        'username'   => $s['shared_xtream_username'] ?? '',
        'password'   => $s['shared_xtream_password'] ?? '',
        'configured' => !empty($s['shared_xtream_server'])
                       && !empty($s['shared_xtream_username'])
                       && !empty($s['shared_xtream_password']),
    ]);
}

function route_public_playback_mode(): void {
    $s = get_settings_doc();
    send_json([
        'external_player_enabled' => (bool)($s['external_player_enabled'] ?? false),
        'player_notice_enabled'   => (bool)($s['player_notice_enabled'] ?? true),
        'inline_preview_enabled'  => (bool)($s['inline_preview_enabled'] ?? true),
    ]);
}

/**
 * Public AdMob configuration. The mobile app fetches this on launch to
 * know whether to initialise ads, which Ad Unit IDs to use, whether to
 * run in testing mode, and how often to trigger interstitials.
 *
 * NEVER return secrets here — Ad Unit IDs are client-facing anyway (they
 * get baked into AndroidManifest.xml). `ads_enabled=false` means the app
 * should not mount any ad views at all.
 */
function route_public_ad_config(): void {
    $s = get_settings_doc();
    $enabled = (bool)($s['ads_enabled'] ?? false);
    $testing = (bool)($s['ads_testing_mode'] ?? true);
    // When testing_mode is on, hand out Google's universal test Ad Unit IDs
    // so the real publisher account is never touched regardless of what the
    // admin typed. The Capacitor plugin also respects isTesting=true, but
    // swapping IDs here is belt + braces.
    $banner = (string)($s['ads_banner_id'] ?? '');
    $inter  = (string)($s['ads_interstitial_id'] ?? '');
    $native = (string)($s['ads_native_id'] ?? '');
    // BUG FIX (2026-01): the upgrade-kit copy of this route was
    // missing `rewarded_id` entirely, so the React app's
    // `showRewarded()` always bailed with "no rewarded_id configured"
    // and the "Watch Ad to unlock 1 hour ad-free" button silently
    // no-op'd in production. Now mirrors the main nadiplayer/api/
    // route — falls back to the public TEST rewarded unit when
    // testing_mode is on so admins can validate the flow.
    $rewarded = (string)($s['ads_rewarded_id'] ?? '');
    if ($testing) {
        // Google's universal TEST adaptive banner unit. `6300978111`
        // returned a fixed 320x50 creative which left white gutters
        // on phones; `9214589741` is the Adaptive Banner test unit
        // and stretches to fill the AdView's measured width.
        $banner = 'ca-app-pub-3940256099942544/9214589741';
        $inter  = 'ca-app-pub-3940256099942544/1033173712';
        // Google's universal TEST Native Advanced unit. The Capacitor
        // plugin will load real test creatives so the team can confirm
        // wiring end-to-end before flipping testing_mode off.
        $native = 'ca-app-pub-3940256099942544/2247696110';
        // Google's universal TEST Rewarded unit.
        $rewarded = 'ca-app-pub-3940256099942544/5224354917';
    }
    send_json([
        'enabled'                 => $enabled,
        // BUG-2 FIX (2026-05): expose Users-vs-Guests sub-toggles so
        // the React client's useAdsPolicy hook can gate ads per
        // auth status. Defaults preserve the previous behaviour.
        'ads_enabled_for_users'   => (bool)($s['ads_enabled_for_users']  ?? false),
        'ads_enabled_for_guests'  => array_key_exists('ads_enabled_for_guests', $s)
                                       ? (bool)$s['ads_enabled_for_guests']
                                       : $enabled,
        'testing'                 => $testing,
        'app_id'                  => (string)($s['ads_app_id'] ?? ''),
        'banner_id'               => $banner,
        'interstitial_id'         => $inter,
        'native_id'               => $native,
        'rewarded_id'             => $rewarded,
        'interstitial_every'      => max(0, (int)($s['ads_interstitial_every'] ?? 5)),
    ]);
}

/**
 * Public read-only payload powering:
 *   • In-app update popup (latest + min-supported version, download URLs, changelog)
 *   • About / Help section (creator info, support email, privacy policy)
 *   • WhatsApp contact (number + prefilled message)
 *
 * No auth required — guests see this too. Admin edits these via PUT /api/admin/settings.
 */
function route_public_app_info(): void {
    $s = get_settings_doc();
    send_json([
        'update' => [
            'enabled'               => (bool)($s['update_enabled'] ?? false),
            'latest_version'        => trim((string)($s['app_version'] ?? '')) ?: '1.0.0',
            'min_supported_version' => trim((string)($s['min_supported_version'] ?? '')) ?: '1.0.0',
            'apk_url'               => (string)($s['update_apk_url'] ?? ''),
            'play_url'              => (string)($s['update_play_url'] ?? ''),
            'changelog'             => (string)($s['update_changelog'] ?? ''),
            'popup_delay_seconds'   => (int)($s['popup_delay_seconds'] ?? 10),
        ],
        'creator' => [
            'name'       => (string)($s['creator_name'] ?? ''),
            'role'       => (string)($s['creator_role'] ?? ''),
            'avatar_url' => (string)($s['creator_avatar_url'] ?? ''),
            'bio'        => (string)($s['creator_bio'] ?? ''),
        ],
        'support' => [
            'whatsapp_number'  => (string)($s['whatsapp_number'] ?? ''),
            'whatsapp_message' => (string)($s['whatsapp_message'] ?? ''),
            'email'            => (string)($s['support_email'] ?? ''),
        ],
        'flags' => [
            // Mirrored from /api/public/playback-mode for resilience — even
            // if a deployment somewhere is missing the playback-mode route,
            // the device still picks up the admin choice from app-info.
            'player_notice_enabled'   => (bool)($s['player_notice_enabled'] ?? true),
            'external_player_enabled' => (bool)($s['external_player_enabled'] ?? false),
            'inline_preview_enabled'  => (bool)($s['inline_preview_enabled'] ?? true),
            'proxy_enabled'           => (bool)($s['proxy_enabled'] ?? true),
        ],
        'privacy_policy_text' => (string)($s['privacy_policy_text'] ?? ''),
        // FEATURE (2026-01): Terms & Conditions text. Same admin-editable
        // pattern as privacy_policy_text — surfaced by the About modal on
        // the Account page. Empty string falls back to a placeholder on
        // the client side.
        'terms_policy_text'   => (string)($s['terms_policy_text'] ?? ''),
    ]);
}

function route_shared_profiles(): void {
    $current = require_auth();
    $s = get_settings_doc();

    // BUG-7 FIX (2026-05): "own" mode users get empty list.
    $mode = $current['xtream_mode'] ?? 'shared';
    if ($mode === 'own') {
        send_json(['profiles' => [], 'xtream_mode' => 'own']);
        return;
    }

    send_json([
        'profiles'      => $s['shared_profiles'] ?? [],
        'proxy_enabled' => (bool)($s['proxy_enabled'] ?? true),
    ]);
}

function route_subscription_status(): void {
    $current = require_auth();

    // Re-fetch fresh — SELECT * so old DBs without hybrid columns don't crash
    $stmt = db()->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$current['id']]);
    $shaped = shape_user($stmt->fetch() ?: $current);

    $s = get_settings_doc();
    $resolved = ['server' => '', 'username' => '', 'password' => ''];
    $live_source = null;
    $vod_source = null;

    if (($shaped['role'] ?? '') === 'user') {
        $mode = $shaped['xtream_mode'] ?? 'shared';

        if ($mode === 'own') {
            $resolved = [
                'server'   => $shaped['xtream_server']   ?? '',
                'username' => $shaped['xtream_username'] ?? '',
                'password' => $shaped['xtream_password'] ?? '',
            ];
            // Check for per-user hybrid sources (only if columns exist in this DB)
            $u_live_srv = trim((string)($shaped['live_server'] ?? ''));
            $u_vod_srv  = trim((string)($shaped['vod_server']  ?? ''));
            if ($u_live_srv !== '') {
                $live_source = [
                    'type'     => 'xtream',
                    'url'      => $u_live_srv,
                    'username' => (string)($shaped['live_username'] ?? ''),
                    'password' => (string)($shaped['live_password'] ?? ''),
                ];
            }
            if ($u_vod_srv !== '') {
                $vod_source = [
                    'type'     => 'xtream',
                    'url'      => $u_vod_srv,
                    'username' => (string)($shaped['vod_username'] ?? ''),
                    'password' => (string)($shaped['vod_password'] ?? ''),
                ];
            }
        } else {
            // Shared mode
            $resolved = [
                'server'   => $s['shared_xtream_server']   ?? '',
                'username' => $s['shared_xtream_username'] ?? '',
                'password' => $s['shared_xtream_password'] ?? '',
            ];
            // Check shared profiles for hybrid sources (safe null checks)
            $shared_profiles = $s['shared_profiles'] ?? [];
            if (is_array($shared_profiles)) {
                foreach ($shared_profiles as $sp) {
                    if (!is_array($sp)) continue;
                    $sa_srv = trim((string)($sp['source_a_server'] ?? ''));
                    $sb_srv = trim((string)($sp['source_b_server'] ?? ''));
                    if ($sa_srv !== '' && !$live_source) {
                        $live_source = [
                            'type'     => ((string)($sp['source_a_kind'] ?? '')) ?: 'xtream',
                            'url'      => $sa_srv,
                            'username' => (string)($sp['source_a_username'] ?? ''),
                            'password' => (string)($sp['source_a_password'] ?? ''),
                        ];
                    }
                    if ($sb_srv !== '' && !$vod_source) {
                        $vod_source = [
                            'type'     => ((string)($sp['source_b_kind'] ?? '')) ?: 'xtream',
                            'url'      => $sb_srv,
                            'username' => (string)($sp['source_b_username'] ?? ''),
                            'password' => (string)($sp['source_b_password'] ?? ''),
                        ];
                    }
                }
            }
        }
    }

    if (!empty($shaped['is_expired'])) {
        $resolved = ['server' => '', 'username' => '', 'password' => ''];
        $live_source = null;
        $vod_source = null;
    }

    $response = [
        'user'            => $shaped,
        'xtream'          => $resolved,
        'xtream_mode'     => $mode ?? 'shared',
        'xtream_configured' => !empty($resolved['server']) && !empty($resolved['username']) && !empty($resolved['password']),
        'whatsapp_number' => $s['whatsapp_number'] ?? '',
        'proxy_enabled'   => (bool)($s['proxy_enabled'] ?? true),
    ];
    // Only include hybrid sources when they have real data
    if ($live_source && !empty($live_source['url'])) $response['live_source'] = $live_source;
    if ($vod_source && !empty($vod_source['url']))   $response['vod_source']  = $vod_source;

    send_json($response);
}
