<?php
/**
 * One-off migration — add `ads_enabled_for_users` and `ads_enabled_for_guests`
 * to the existing settings JSON row.
 *
 * USAGE
 *   Drop this file inside your deployed `nadiplayer/api/` directory (next to
 *   config.php) and hit it ONCE from your browser:
 *       https://YOUR_DOMAIN/api/migrate_ads_audience.php
 *
 *   It is safe to run multiple times — idempotent.
 *
 * IMPORTANT
 *   • No ALTER TABLE is needed. The `settings` table only has two columns
 *     (`id`, `data` JSON), so all settings live inside the existing `data`
 *     blob. This script just edits that blob.
 *   • Delete this file after running it. It is gated by a CLI/admin check
 *     so even if you forget, only an authenticated admin (or the cPanel
 *     shell) can trigger it.
 */
declare(strict_types=1);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/lib/db.php';

// ── Access gate ────────────────────────────────────────────────────
// Allow ONLY:
//   1. CLI execution (cPanel "Run Cron Job Now" / SSH)
//   2. Authenticated admin session (cookie issued by /api/auth/login)
$is_cli = (PHP_SAPI === 'cli');
$is_admin = false;
if (!$is_cli) {
    require_once __DIR__ . '/lib/auth.php';
    try {
        $u = current_user();
        $is_admin = $u && ($u['role'] ?? '') === 'admin';
    } catch (Throwable $e) {
        $is_admin = false;
    }
}
if (!$is_cli && !$is_admin) {
    http_response_code(403);
    echo "403 — log in as admin first, or run from cPanel shell.\n";
    exit;
}

// ── Migration logic ────────────────────────────────────────────────
$pdo = db();
$row = $pdo->query("SELECT data FROM settings WHERE id = 'global'")->fetch();

if (!$row) {
    // Fresh DB — create the document with the new fields baked in.
    $data = [
        'ads_enabled'             => false,
        'ads_enabled_for_users'   => false,
        'ads_enabled_for_guests'  => true,
        'ads_testing_mode'        => true,
    ];
    $pdo->prepare("INSERT INTO settings (id, data) VALUES ('global', ?)")
        ->execute([json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]);
    $action = 'inserted new settings row';
} else {
    $data = json_decode($row['data'], true) ?: [];
    $changes = [];
    if (!array_key_exists('ads_enabled_for_users', $data)) {
        $data['ads_enabled_for_users'] = false;
        $changes[] = 'ads_enabled_for_users := false';
    }
    if (!array_key_exists('ads_enabled_for_guests', $data)) {
        // Default to whatever the master toggle says, so guests keep
        // seeing ads with no manual config.
        $data['ads_enabled_for_guests'] = !empty($data['ads_enabled']);
        $changes[] = 'ads_enabled_for_guests := ' . ($data['ads_enabled_for_guests'] ? 'true' : 'false');
    }
    if ($changes) {
        $pdo->prepare("UPDATE settings SET data = ? WHERE id = 'global'")
            ->execute([json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]);
        $action = 'patched: ' . implode(', ', $changes);
    } else {
        $action = 'already migrated — nothing to do';
    }
}

// ── Report ─────────────────────────────────────────────────────────
header('Content-Type: text/plain; charset=utf-8');
echo "Migration complete: $action\n\n";
echo "Current settings doc:\n";
$row = $pdo->query("SELECT data FROM settings WHERE id = 'global'")->fetch();
$doc = json_decode($row['data'], true);
foreach (['ads_enabled', 'ads_enabled_for_users', 'ads_enabled_for_guests', 'ads_testing_mode'] as $k) {
    $v = $doc[$k] ?? '(missing)';
    if (is_bool($v)) $v = $v ? 'true' : 'false';
    echo "  $k = $v\n";
}
echo "\nDelete this script after running it.\n";
