<?php
/**
 * GET /api/campaign/plans
 *
 * Returns all active plans from `tester_pkg_plans` so the Add Campaign
 * form and the checkout page can render them dynamically.
 */

declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/bootstrap.php';

Auth::apiRequireLogin();

$pdo = db();

try {
    // Try with new columns first
    $stmt = $pdo->query("
        SELECT plan_name, total_users, plan_testing_days, coin_per_day,
               COALESCE(price_inr, 0) AS price_inr,
               COALESCE(price_usd, 0) AS price_usd,
               COALESCE(min_testers_to_start, 1) AS min_testers_to_start,
               COALESCE(is_active, 1) AS is_active
        FROM tester_pkg_plans
        WHERE COALESCE(is_active, 1) = 1
        ORDER BY price_inr ASC
    ");
    $rows = $stmt->fetchAll();
} catch (PDOException $e) {
    // Fallback if migration not run yet
    Logger::warning('Plans query fell back (migration may not be run)', ['err' => $e->getMessage()]);
    $stmt = $pdo->query("
        SELECT plan_name, total_users, plan_testing_days, coin_per_day
        FROM tester_pkg_plans
    ");
    $rows = array_map(function ($r) {
        $r['price_inr'] = match (strtolower($r['plan_name'])) {
            'silver'   => 9.00,
            'gold'     => 1499.00,
            'platinum' => 2199.00,
            default    => 0,
        };
        $r['price_usd'] = round((float)$r['price_inr'] / 83, 2);
        $r['min_testers_to_start'] = (int)$r['total_users'];
        $r['is_active'] = 1;
        return $r;
    }, $stmt->fetchAll());
}

if (!$rows) jsonError('No plans configured. Please contact support.', 503);

// Build feature lists per plan (UI-friendly)
$plans = array_map(function ($r) {
    $name = $r['plan_name'];
    $key = strtolower($name);
    $accent = match ($key) {
        'silver'   => '#C0C0C0',
        'gold'     => '#FFD700',
        'platinum' => '#E5E4E2',
        default    => '#1B7A43',
    };
    $bgGradient = match ($key) {
        'silver'   => 'linear-gradient(135deg,#FFFFFF,#F5F5F5)',
        'gold'     => 'linear-gradient(135deg,#E67E22,#F5A623)',
        'platinum' => 'linear-gradient(135deg,#2C3E50,#4A5568)',
        default    => 'linear-gradient(135deg,#1B7A43,#2D9B5A)',
    };
    $totalReward = (int)$r['plan_testing_days'] * (int)$r['coin_per_day'];

    return [
        'plan_name'             => $name,
        'plan_key'              => $key,
        'price_inr'             => (float)$r['price_inr'],
        'price_usd'             => (float)$r['price_usd'],
        'total_users'           => (int)$r['total_users'],
        'plan_testing_days'     => (int)$r['plan_testing_days'],
        'coin_per_day'          => (int)$r['coin_per_day'],
        'total_reward_per_user' => $totalReward,
        'min_testers_to_start'  => (int)$r['min_testers_to_start'],
        'accent_color'          => $accent,
        'bg_gradient'           => $bgGradient,
        'features' => [
            "{$r['total_users']}+ Real Device Users",
            "{$r['plan_testing_days']} Days Active Testing",
            "{$r['coin_per_day']} Coins / Day per Tester",
            "{$totalReward} Coins Total per Tester",
            $key === 'silver' ? 'Standard Support' : 'Priority Support 24×7',
            'Daily Activity Reports',
        ],
    ];
}, $rows);

jsonSuccess('OK', ['plans' => $plans]);
