<?php
    require_once __DIR__ . '/config/config.php';
    session_start();

   
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }

    $userId = $_SESSION['user_id'];

    // Prepare arrays
    $transactions = [];

    // Fetch Deposits
    $depositQuery = "SELECT 'deposit' AS type, usd_amount, crypto_amount, crypto_type, wallet_address, status, created_at FROM deposits WHERE user_id = ? ORDER BY created_at DESC";
    if ($stmt = $conn->prepare($depositQuery)) {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $transactions[] = $row;
        }
        $stmt->close();
    }

    // Fetch Withdrawals
    $withdrawQuery = "SELECT 'withdrawal' AS type, usd_amount, crypto_amount, crypto_type, wallet_address, status, created_at FROM withdrawals WHERE user_id = ? ORDER BY created_at DESC";
    if ($stmt = $conn->prepare($withdrawQuery)) {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $transactions[] = $row;
        }
        $stmt->close();
    }

    // Sort transactions by created_at descending
    usort($transactions, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });

    // Output
    echo json_encode(['success' => true, 'transactions' => $transactions]);

?>