<?php
/**
 * GET /api/campaign/list
 *
 * Query params:
 *   - filter: all | active | review | completed | rejected (default: all)
 *   - q: search query (matches app_title, app_developername, app_pkg)
 *   - page: 1+ (default 1)
 *   - per_page: 10|20|50 (default 10)
 */

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

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

$filter   = strtolower(Validator::clean((string)($_GET['filter'] ?? 'all'), 20));
$q        = Validator::clean((string)($_GET['q'] ?? ''), 80);
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = (int)($_GET['per_page'] ?? 10);
if (!in_array($perPage, [10, 20, 50], true)) $perPage = 10;
$offset   = ($page - 1) * $perPage;

// Filter → status_admin set
$filterMap = [
    'all'       => null,                    // any > 0
    'active'    => [2, 4, 6],
    'review'    => [1],
    'completed' => [7],
    'rejected'  => [3, 8],
    'paused'    => [5],
];
if (!array_key_exists($filter, $filterMap)) $filter = 'all';

$where  = ['publisher_id = ?', 'status_admin > 0'];
$params = [$pid];

if ($filterMap[$filter] !== null) {
    $in = implode(',', array_fill(0, count($filterMap[$filter]), '?'));
    $where[] = "status_admin IN ({$in})";
    array_push($params, ...$filterMap[$filter]);
}
if ($q !== '') {
    $where[] = '(app_title LIKE ? OR app_developername LIKE ? OR app_pkg LIKE ?)';
    $like = '%' . $q . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}
$whereSql = implode(' AND ', $where);

$pdo = db();

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) AS c FROM pub_purchase_history WHERE {$whereSql}");
$countStmt->execute($params);
$totalCount = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalCount / $perPage));

// Page rows
$rowStmt = $pdo->prepare("
    SELECT id, app_logo, app_icon_path, app_title, app_developername, app_pkg,
           plan_name, status_admin, total_users, completed_users,
           start_date, end_date, created_at
    FROM pub_purchase_history
    WHERE {$whereSql}
    ORDER BY created_at DESC
    LIMIT {$perPage} OFFSET {$offset}
");
$rowStmt->execute($params);
$rows = $rowStmt->fetchAll();

$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'],
];

$campaigns = 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_pkg'         => $r['app_pkg'],
        'app_logo'        => $r['app_icon_path'] ? '/uploads/app-icons/' . $r['app_icon_path'] : ($r['app_logo'] ?: null),
        'plan_name'       => $r['plan_name'],
        'status_admin'    => $sa,
        'status_label'    => $st['label'],
        'status_badge'    => $st['badge'],
        'total_users'     => (int)$r['total_users'],
        'completed_users' => (int)$r['completed_users'],
        'start_date'      => $r['start_date'],
        'end_date'        => $r['end_date'],
        'created_at'      => $r['created_at'],
        'created_at_human'=> date('M d, Y', strtotime((string)$r['created_at'])),
        'detail_url'      => '/dashboard/campaigns/' . (int)$r['id'],
    ];
}, $rows);

jsonSuccess('OK', [
    'campaigns'   => $campaigns,
    'pagination'  => [
        'page'        => $page,
        'per_page'    => $perPage,
        'total_count' => $totalCount,
        'total_pages' => $totalPages,
        'has_prev'    => $page > 1,
        'has_next'    => $page < $totalPages,
    ],
    'filter'      => $filter,
    'q'           => $q,
]);
