<?php
/**
 * GET /api/dashboard/stats
 *
 * Returns campaign counts, recent campaigns, and donut chart data
 * for the logged-in publisher.
 */

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

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

$pdo = db();

// ───── Counts ─────
$counts = $pdo->prepare("
    SELECT
      SUM(CASE WHEN status_admin > 0 THEN 1 ELSE 0 END)               AS total,
      SUM(CASE WHEN status_admin IN (2, 4, 6) THEN 1 ELSE 0 END)      AS active,
      SUM(CASE WHEN status_admin = 7 THEN 1 ELSE 0 END)               AS completed,
      SUM(CASE WHEN status_admin = 1 THEN 1 ELSE 0 END)               AS in_review,
      SUM(CASE WHEN status_admin = 3 THEN 1 ELSE 0 END)               AS rejected
    FROM pub_purchase_history
    WHERE publisher_id = ?
");
$counts->execute([$pid]);
$row = $counts->fetch() ?: [];

$total     = (int)($row['total'] ?? 0);
$active    = (int)($row['active'] ?? 0);
$completed = (int)($row['completed'] ?? 0);
$inReview  = (int)($row['in_review'] ?? 0);
$rejected  = (int)($row['rejected'] ?? 0);

$completionPct = $total > 0 ? (int)round(($completed / $total) * 100) : 0;

// ───── Recent campaigns (last 5) ─────
$recentStmt = $pdo->prepare("
    SELECT id, app_logo, app_icon_path, app_title, app_developername, app_pkg,
           status_admin, total_users, completed_users, created_at
    FROM pub_purchase_history
    WHERE publisher_id = ? AND status_admin > 0
    ORDER BY created_at DESC
    LIMIT 5
");
$recentStmt->execute([$pid]);
$recent = $recentStmt->fetchAll();

// Map status_admin → badge label + color class
$statusMap = [
    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'],
];

$recentList = array_map(function ($r) use ($statusMap) {
    $sa = (int)$r['status_admin'];
    $st = $statusMap[$sa] ?? ['label' => 'Unknown', 'badge' => 'badge-review'];
    return [
        'id'             => (int)$r['id'],
        'app_title'      => $r['app_title'],
        'app_developer'  => $r['app_developername'],
        'app_logo'       => $r['app_icon_path'] ? '/uploads/app-icons/' . $r['app_icon_path'] : ($r['app_logo'] ?: null),
        'app_pkg'        => $r['app_pkg'],
        'status_admin'   => $sa,
        'status_label'   => $st['label'],
        'status_badge'   => $st['badge'],
        'total_users'    => (int)$r['total_users'],
        'completed_users'=> (int)$r['completed_users'],
        'created_at'     => $r['created_at'],
        'detail_url'     => '/dashboard/campaigns/' . (int)$r['id'],
    ];
}, $recent);

jsonSuccess('OK', [
    'stats' => [
        'total'           => $total,
        'active'          => $active,
        'completed'       => $completed,
        'in_review'       => $inReview,
        'rejected'        => $rejected,
        'completion_pct'  => $completionPct,
        'credits'         => (float)$user['credits'],
    ],
    'chart' => [
        'labels'  => ['Total', 'Active', 'Completed'],
        'data'    => [$total, $active, $completed],
        'colors'  => ['#E8DDD0', '#7DC9A0', '#1B7A43'],
    ],
    'recent_campaigns' => $recentList,
    'publisher' => [
        'name'    => $user['name'],
        'email'   => $user['email'],
        'company' => $user['company_name'] ?? null,
    ],
]);
