<?php
/**
 * API - Transaction History
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';
require_once '../../includes/ApiAuth.php';

$user = ApiAuth::authenticate();
$userId = $user['id'];

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = min(50, max(10, (int)($_GET['per_page'] ?? 20)));
$type = $_GET['type'] ?? ''; // deposit, withdrawal, bonus, trade, all
$offset = ($page - 1) * $perPage;

$where = "user_id = :uid";
$params = ['uid' => $userId];

if ($type && $type !== 'all') {
    $where .= " AND type = :type";
    $params['type'] = $type;
}

// Get total count
$total = dbFetch("SELECT COUNT(*) as cnt FROM transactions WHERE {$where}", $params);
$totalCount = (int)($total['cnt'] ?? 0);

// Get transactions
$transactions = dbFetchAll(
    "SELECT transaction_id, type, amount, balance_after, description, status, created_at 
     FROM transactions 
     WHERE {$where} 
     ORDER BY created_at DESC 
     LIMIT {$perPage} OFFSET {$offset}",
    $params
);

// Get wallet summary
$wallet = dbFetch("SELECT balance, bonus_balance, total_deposit, total_withdrawal FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);

jsonSuccess('Transaction history', [
    'transactions' => $transactions,
    'pagination' => [
        'page' => $page,
        'per_page' => $perPage,
        'total' => $totalCount,
        'total_pages' => ceil($totalCount / $perPage)
    ],
    'wallet' => [
        'balance' => (float)($wallet['balance'] ?? 0),
        'bonus_balance' => (float)($wallet['bonus_balance'] ?? 0),
        'total_deposit' => (float)($wallet['total_deposit'] ?? 0),
        'total_withdrawal' => (float)($wallet['total_withdrawal'] ?? 0)
    ]
]);
