<?php
/**
 * GET /api/credit/history
 *
 * Returns publisher_payment rows + linked campaign info for the
 * logged-in publisher. Paginated.
 */

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

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

$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;

$pdo = db();

$count = $pdo->prepare("SELECT COUNT(*) FROM publisher_payment WHERE publisher_id = ?");
$count->execute([$pid]);
$totalCount = (int)$count->fetchColumn();
$totalPages = max(1, (int)ceil($totalCount / $perPage));

$stmt = $pdo->prepare("
    SELECT p.id, p.order_id, p.plan_name, p.subtotal, p.gst_amount, p.platform_fee,
           p.total_amount, p.currency, p.gateway, p.gateway_payment_id,
           p.status, p.created_at, p.updated_at,
           h.app_title, h.app_logo, h.app_icon_path
    FROM publisher_payment p
    LEFT JOIN pub_purchase_history h ON h.id = p.pub_purchase_history_id
    WHERE p.publisher_id = ?
    ORDER BY p.created_at DESC
    LIMIT {$perPage} OFFSET {$offset}
");
$stmt->execute([$pid]);
$rows = $stmt->fetchAll();

$gatewayLabels = [
    'cashfree' => 'Cashfree',
    'razorpay' => 'Razorpay',
    'phonepe'  => 'PhonePe',
    'stripe'   => 'Stripe',
    'paypal'   => 'PayPal',
];
$statusLabels = [
    'pending'   => ['label' => 'Pending',   'badge' => 'badge-review'],
    'success'   => ['label' => 'Completed', 'badge' => 'badge-active'],
    'failed'    => ['label' => 'Failed',    'badge' => 'badge-rejected'],
    'refunded'  => ['label' => 'Refunded',  'badge' => 'badge-rejected'],
    'cancelled' => ['label' => 'Cancelled', 'badge' => 'badge-rejected'],
];

$payments = array_map(function ($r) use ($gatewayLabels, $statusLabels, $user) {
    $st = $statusLabels[$r['status']] ?? ['label' => 'Unknown', 'badge' => 'badge-review'];
    return [
        'id'              => (int)$r['id'],
        'order_id'        => $r['order_id'],
        'plan_name'       => $r['plan_name'],
        'subtotal'        => (float)$r['subtotal'],
        'gst_amount'      => (float)$r['gst_amount'],
        'platform_fee'    => (float)$r['platform_fee'],
        'total_amount'    => (float)$r['total_amount'],
        'currency'        => $r['currency'],
        'currency_symbol' => $r['currency'] === 'INR' ? '₹' : '$',
        'gateway'         => $r['gateway'],
        'gateway_label'   => $gatewayLabels[$r['gateway']] ?? ucfirst($r['gateway']),
        'transaction_id'  => $r['gateway_payment_id'] ?? '—',
        'status'          => $r['status'],
        'status_label'    => $st['label'],
        'status_badge'    => $st['badge'],
        'created_at'      => $r['created_at'],
        'created_at_human'=> date('M d, Y', strtotime((string)$r['created_at'])),
        'app_title'       => $r['app_title'] ?? null,
        'app_logo'        => $r['app_icon_path'] ? '/uploads/app-icons/' . $r['app_icon_path'] : ($r['app_logo'] ?: null),
        'email'           => $user['email'],
    ];
}, $rows);

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