<?php
// miniapp/api/wallet_history.php
// تاریخچه تراکنش‌های کیف پول کاربر
header('Content-Type: application/json; charset=utf-8');

require __DIR__ . '/config.php';

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;

if ($userId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'شناسه کاربر نامعتبر است'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $offset = ($page - 1) * $limit;

    // تعداد کل
    $countStmt = $pdo->prepare("SELECT COUNT(*) as count FROM wallet_transactions WHERE user_id = ?");
    $countStmt->execute([$userId]);
    $total = $countStmt->fetch()['count'];

    // دریافت تراکنش‌ها
    $stmt = $pdo->prepare("
        SELECT id, amount, type, status, description, created_at, updated_at 
        FROM wallet_transactions 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    ");
    $stmt->execute([$userId, $limit, $offset]);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ترجمه نوع و وضعیت
    $typeLabels = [
        'DEPOSIT' => 'واریز',
        'PURCHASE' => 'خرید',
        'REFUND' => 'بازگشت وجه',
        'ADMIN' => 'توسط ادمین'
    ];
    
    $statusLabels = [
        'PENDING' => 'در انتظار تایید',
        'COMPLETED' => 'تکمیل شده',
        'REJECTED' => 'رد شده',
        'CANCELLED' => 'لغو شده'
    ];

    foreach ($transactions as &$tx) {
        $tx['type_label'] = $typeLabels[$tx['type']] ?? $tx['type'];
        $tx['status_label'] = $statusLabels[$tx['status']] ?? $tx['status'];
        $tx['amount_formatted'] = number_format($tx['amount']) . ' تومان';
        $tx['is_income'] = in_array($tx['type'], ['DEPOSIT', 'REFUND', 'ADMIN']) && $tx['status'] === 'COMPLETED';
    }

    echo json_encode([
        'ok' => true,
        'data' => [
            'transactions' => $transactions,
            'current_page' => $page,
            'total_pages' => ceil($total / $limit),
            'total_count' => (int)$total
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    error_log("wallet_history error: " . $e->getMessage());
    echo json_encode(['ok' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}

