<?php
/**
 * Get wallet transaction history
 */
require_once 'config.php';

$userId = $_GET['user_id'] ?? $_POST['user_id'] ?? null;
$limit = (int)($_GET['limit'] ?? 20);

if (!$userId) {
    echo json_encode(['ok' => false, 'error' => 'user_id required'], JSON_UNESCAPED_UNICODE);
    exit;
}

$userId = (int)$userId;

// Get transactions
$stmt = $pdo->prepare("
    SELECT id, amount, type, status, description, created_at
    FROM wallet_transactions 
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT ?
");
$stmt->bindValue(1, $userId, PDO::PARAM_INT);
$stmt->bindValue(2, $limit, PDO::PARAM_INT);
$stmt->execute();
$transactions = $stmt->fetchAll();

// Get balance
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$userId]);
$balance = (int)$stmt->fetchColumn();

// Format transactions
$typeLabels = [
    'DEPOSIT'  => '💰 واریز',
    'PURCHASE' => '🛒 خرید',
    'REFUND'   => '↩️ استرداد',
    'ADMIN'    => '👑 ادمین',
];

$statusLabels = [
    'PENDING'   => '⏳ در انتظار',
    'COMPLETED' => '✅ تکمیل شده',
    'REJECTED'  => '❌ رد شده',
    'CANCELLED' => '🚫 لغو شده',
];

$formatted = [];
foreach ($transactions as $tx) {
    $isIncome = in_array($tx['type'], ['DEPOSIT', 'REFUND', 'ADMIN']);
    
    $formatted[] = [
        'id'               => (int)$tx['id'],
        'amount'           => (int)$tx['amount'],
        'amount_formatted' => money($tx['amount']),
        'type'             => $tx['type'],
        'type_label'       => $typeLabels[$tx['type']] ?? $tx['type'],
        'status'           => $tx['status'],
        'status_label'     => $statusLabels[$tx['status']] ?? $tx['status'],
        'description'      => $tx['description'],
        'created_at'       => $tx['created_at'],
        'is_income'        => $isIncome,
    ];
}

echo json_encode([
    'ok'   => true,
    'data' => [
        'balance'      => $balance,
        'balance_text' => money($balance),
        'transactions' => $formatted,
    ],
], JSON_UNESCAPED_UNICODE);
