<?php
ob_start();
require_once __DIR__ . '/../../includes/auth.php';
ob_end_clean();
header('Content-Type: application/json');

if (!isLoggedIn()) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }

$userId = (int)$_SESSION['user_id'];
$action = $_GET['action'] ?? 'all';

// ── Purchases ──────────────────────────────────────────────
if ($action === 'all' || $action === 'purchases') {
    $stmt = db()->prepare("
        SELECT id, tokens, amount_cents, payment_method, platform_id, game_alias,
               card_brand, card_last4, status, admin_note, created_at
        FROM token_purchases
        WHERE user_id=?
        ORDER BY created_at DESC
        LIMIT 50
    ");
    $stmt->execute([$userId]);
    $purchases = $stmt->fetchAll();
}

// ── Cashouts ───────────────────────────────────────────────
if ($action === 'all' || $action === 'cashouts') {
    $stmt = db()->prepare("
        SELECT cr.*,
               COALESCE(p.name, cr.platform_id) AS platform_name
        FROM cashout_requests cr
        LEFT JOIN platforms p ON cr.platform_id = p.slug
        WHERE cr.user_id=?
        ORDER BY cr.created_at DESC
        LIMIT 50
    ");
    $stmt->execute([$userId]);
    $cashouts = $stmt->fetchAll();
}

// ── Broadcasts/Invites (use broadcasts as announcements) ───
if ($action === 'all' || $action === 'broadcasts') {
    $stmt = db()->prepare("
        SELECT b.id, b.subject, b.message, b.sent_at,
               u.username AS sender,
               (SELECT COUNT(*) FROM broadcast_reads WHERE broadcast_id=b.id AND user_id=?) AS is_read,
               (SELECT COUNT(*) FROM broadcast_replies WHERE broadcast_id=b.id AND user_id=?) AS replied
        FROM broadcasts b
        JOIN users u ON b.admin_id=u.id
        WHERE b.target='all'
           OR (b.target='verified'   AND EXISTS(SELECT 1 FROM users WHERE id=? AND email_verified=1))
           OR (b.target='unverified' AND EXISTS(SELECT 1 FROM users WHERE id=? AND email_verified=0))
           OR (b.target='admins'     AND 0)
        ORDER BY b.sent_at DESC
        LIMIT 20
    ");
    $stmt->execute([$userId,$userId,$userId,$userId]);
    $broadcasts = $stmt->fetchAll();
}

if ($action === 'all') {
    echo json_encode([
        'success'    => true,
        'purchases'  => $purchases,
        'cashouts'   => $cashouts,
        'broadcasts' => $broadcasts,
    ]);
} elseif ($action === 'purchases') {
    echo json_encode(['success'=>true,'purchases'=>$purchases]);
} elseif ($action === 'cashouts') {
    echo json_encode(['success'=>true,'cashouts'=>$cashouts]);
} elseif ($action === 'broadcasts') {
    echo json_encode(['success'=>true,'broadcasts'=>$broadcasts]);
} else {
    echo json_encode(['success'=>false,'error'=>'Unknown action']);
}
