<?php
/**
 * GET /api/campaign/details?id=X
 *
 * Returns full campaign + applied testers + per-status meta.
 */

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

$user = Auth::apiRequireLogin();
$pid  = (int)$user['publisher_id'];

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) jsonError('Invalid campaign id.');

$pdo = db();
$stmt = $pdo->prepare("
    SELECT id, app_logo, app_icon_path, app_title, app_developername, app_pkg, app_des,
           plan_name, plan_testing_days, per_user_coins, total_users, completed_users,
           status_admin, start_date, end_date, created_at
    FROM pub_purchase_history
    WHERE id = ? AND publisher_id = ?
    LIMIT 1
");
$stmt->execute([$id, $pid]);
$c = $stmt->fetch();
if (!$c) jsonError('Campaign not found.', 404);

$statusMap = [
    0 => ['label' => 'Draft',      'badge' => 'badge-review'],
    1 => ['label' => 'In Review',  'badge' => 'badge-review'],
    2 => ['label' => 'Approved',   'badge' => 'badge-active'],
    3 => ['label' => 'Rejected',   'badge' => 'badge-rejected'],
    4 => ['label' => 'Live',       'badge' => 'badge-active'],
    5 => ['label' => 'Paused',     'badge' => 'badge-review'],
    6 => ['label' => 'Active',     'badge' => 'badge-active'],
    7 => ['label' => 'Completed',  'badge' => 'badge-completed'],
    8 => ['label' => 'Refunded',   'badge' => 'badge-rejected'],
];
$sa = (int)$c['status_admin'];
$st = $statusMap[$sa] ?? ['label' => 'Unknown', 'badge' => 'badge-review'];

// Total reward = days * coins/day
$totalReward = (int)$c['plan_testing_days'] * (int)$c['per_user_coins'];

// ───── Testers (joined via app_task_assign) ─────
$testerStmt = $pdo->prepare("
    SELECT u.id AS user_id, u.name, u.email, u.profile_pic,
           t.status AS tester_status, t.created_at AS applied_at
    FROM app_task_assign t
    JOIN app_users u ON u.id = t.user_id
    WHERE t.pub_purchase_history_id = ?
    ORDER BY t.created_at DESC
    LIMIT 100
");

$testers = [];
try {
    $testerStmt->execute([$id]);
    foreach ($testerStmt->fetchAll() as $r) {
        $tStat = (int)$r['tester_status'];
        // 0=pending, 1=active, 2=under_review, 3=rejected, 4=completed
        $tLabel = match ($tStat) {
            0 => 'Pending',
            1 => 'Active',
            2 => 'Under Review',
            3 => 'Rejected',
            4 => 'Completed',
            default => 'Unknown',
        };
        $name = (string)($r['name'] ?? 'Unnamed');
        $testers[] = [
            'user_id'      => (int)$r['user_id'],
            'name'         => $name,
            'email'        => $r['email'],
            'profile_pic'  => $r['profile_pic'],
            'initials'     => strtoupper(mb_substr(preg_replace('/[^A-Za-z]/', '', $name) ?: 'U', 0, 2)),
            'status'       => $tStat,
            'status_label' => $tLabel,
            'applied_at'   => $r['applied_at'],
        ];
    }
} catch (Throwable $e) {
    // Table may not have these exact columns yet — fall back gracefully
    Logger::warning('Tester list query failed', ['error' => $e->getMessage(), 'campaign_id' => $id]);
    $testers = [];
}

$activeTesters = count(array_filter($testers, fn($t) => $t['status'] === 1));
$pendingTesters = count(array_filter($testers, fn($t) => $t['status'] === 0));

jsonSuccess('OK', [
    'campaign' => [
        'id'                => (int)$c['id'],
        'app_title'         => $c['app_title'],
        'app_developer'     => $c['app_developername'],
        'app_pkg'           => $c['app_pkg'],
        'app_des'           => $c['app_des'],
        'app_logo'          => $c['app_icon_path']
                                 ? '/uploads/app-icons/' . $c['app_icon_path']
                                 : ($c['app_logo'] ?: null),
        'plan_name'         => $c['plan_name'],
        'plan_testing_days' => (int)$c['plan_testing_days'],
        'per_user_coins'    => (int)$c['per_user_coins'],
        'total_reward'      => $totalReward,
        'total_users'       => (int)$c['total_users'],
        'completed_users'   => (int)$c['completed_users'],
        'pending_testers'   => $pendingTesters,
        'active_testers'    => $activeTesters,
        'status_admin'      => $sa,
        'status_label'      => $st['label'],
        'status_badge'      => $st['badge'],
        'start_date'        => $c['start_date'],
        'end_date'          => $c['end_date'],
        'created_at'        => $c['created_at'],
        'created_at_human'  => date('M d, Y', strtotime((string)$c['created_at'])),
    ],
    'testers' => $testers,
    'can_start' => $sa === 2 && $activeTesters >= 1,  // refined in Phase 6
]);
