<?php 
session_start();
include 'includes/head.php';

// Get filter parameters
$type_filter = isset($_GET['type']) ? $conn->real_escape_string($_GET['type']) : '';
$category_filter = isset($_GET['category']) ? $conn->real_escape_string($_GET['category']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// Get pagination parameters
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 15;
$offset = ($page - 1) * $per_page;

// Build combined query for all transactions
$combined_transactions = [];

// 1. Get Deposits
$deposit_conditions = ["d.user_id = '$user_id'"];
if (!empty($status_filter)) {
    $deposit_conditions[] = "d.status = '$status_filter'";
}
if (!empty($date_from)) {
    $deposit_conditions[] = "DATE(d.created_at) >= '$date_from'";
}
if (!empty($date_to)) {
    $deposit_conditions[] = "DATE(d.created_at) <= '$date_to'";
}
if (!empty($search)) {
    $deposit_conditions[] = "(d.transaction_hash LIKE '%$search%' OR d.note LIKE '%$search%')";
}

$deposit_where = !empty($deposit_conditions) ? 'WHERE ' . implode(' AND ', $deposit_conditions) : '';

$deposit_sql = "SELECT 
                    d.id,
                    'deposit' as type,
                    d.amount,
                    d.transaction_hash as description,
                    d.status,
                    d.created_at,
                    d.note,
                    NULL as fee,
                    d.amount as net_amount,
                    'USDT' as currency,
                    NULL as balance_after,
                    'USDT Deposit' as category
                 FROM deposits d
                 $deposit_where
                 ORDER BY d.created_at DESC";

$deposit_result = mysqli_query($conn, $deposit_sql);
while ($row = mysqli_fetch_assoc($deposit_result)) {
    if (empty($type_filter) || $type_filter == 'credit') {
        $combined_transactions[] = $row;
    }
}

// 2. Get Withdrawals
$withdrawal_conditions = ["w.user_id = '$user_id'"];
if (!empty($status_filter)) {
    $status_map = ['pending' => 'pending', 'processing' => 'processing', 'completed' => 'completed'];
    $withdrawal_status = isset($status_map[$status_filter]) ? $status_map[$status_filter] : $status_filter;
    $withdrawal_conditions[] = "w.status = '$withdrawal_status'";
}
if (!empty($date_from)) {
    $withdrawal_conditions[] = "DATE(w.created_at) >= '$date_from'";
}
if (!empty($date_to)) {
    $withdrawal_conditions[] = "DATE(w.created_at) <= '$date_to'";
}
if (!empty($search)) {
    $withdrawal_conditions[] = "(w.destination_address LIKE '%$search%')";
}

$withdrawal_where = !empty($withdrawal_conditions) ? 'WHERE ' . implode(' AND ', $withdrawal_conditions) : '';

$withdrawal_sql = "SELECT 
                    w.id,
                    'withdrawal' as type,
                    w.amount,
                    w.destination_address as description,
                    w.status,
                    w.created_at,
                    NULL as note,
                    w.fee,
                    w.total_amount as net_amount,
                    'USDT' as currency,
                    NULL as balance_after,
                    'USDT Withdrawal' as category
                 FROM withdrawals w
                 $withdrawal_where
                 ORDER BY w.created_at DESC";

$withdrawal_result = mysqli_query($conn, $withdrawal_sql);
while ($row = mysqli_fetch_assoc($withdrawal_result)) {
    if (empty($type_filter) || $type_filter == 'debit') {
        $combined_transactions[] = $row;
    }
}

// 3. Get Trading Transactions
$trading_conditions = ["t.user_id = '$user_id'"];
if (!empty($type_filter)) {
    if ($type_filter == 'credit') {
        $trading_conditions[] = "t.type IN ('credit', 'profit')";
    } elseif ($type_filter == 'debit') {
        $trading_conditions[] = "t.type IN ('debit', 'fee')";
    }
}
if (!empty($category_filter)) {
    $trading_conditions[] = "t.category = '$category_filter'";
}
if (!empty($status_filter)) {
    $trading_conditions[] = "t.status = '$status_filter'";
}
if (!empty($date_from)) {
    $trading_conditions[] = "DATE(t.created_at) >= '$date_from'";
}
if (!empty($date_to)) {
    $trading_conditions[] = "DATE(t.created_at) <= '$date_to'";
}
if (!empty($search)) {
    $trading_conditions[] = "(t.description LIKE '%$search%' OR t.reference LIKE '%$search%')";
}

$trading_where = !empty($trading_conditions) ? 'WHERE ' . implode(' AND ', $trading_conditions) : '';

$trading_sql = "SELECT 
                    t.id,
                    t.type,
                    t.amount,
                    t.description,
                    t.status,
                    t.created_at,
                    NULL as note,
                    NULL as fee,
                    t.amount as net_amount,
                    t.currency,
                    t.balance_after,
                    t.category
                 FROM transactions t
                 $trading_where
                 ORDER BY t.created_at DESC";

$trading_result = mysqli_query($conn, $trading_sql);
while ($row = mysqli_fetch_assoc($trading_result)) {
    $combined_transactions[] = $row;
}

// Sort all transactions by date (newest first)
usort($combined_transactions, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Get total count for pagination
$total_transactions = count($combined_transactions);
$total_pages = ceil($total_transactions / $per_page);

// Apply pagination
$paginated_transactions = array_slice($combined_transactions, $offset, $per_page);

// Get transaction statistics
$stats_sql = "SELECT 
    COUNT(*) as total_transactions,
    SUM(CASE WHEN type IN ('credit', 'profit') THEN amount ELSE 0 END) as total_credits,
    SUM(CASE WHEN type IN ('debit', 'fee') THEN amount ELSE 0 END) as total_debits,
    SUM(CASE 
        WHEN type IN ('credit', 'profit') THEN amount 
        WHEN type IN ('debit', 'fee') THEN -amount 
        ELSE 0 
    END) as net_flow
    FROM transactions 
    WHERE user_id = '$user_id' AND status = 'completed'";

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Add deposit and withdrawal stats
$deposit_stats_sql = "SELECT 
    COUNT(*) as total_deposits,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_deposit_amount
    FROM deposits 
    WHERE user_id = '$user_id'";
    
$deposit_stats_result = mysqli_query($conn, $deposit_stats_sql);
$deposit_stats = mysqli_fetch_assoc($deposit_stats_result);

$withdrawal_stats_sql = "SELECT 
    COUNT(*) as total_withdrawals,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_withdrawal_amount
    FROM withdrawals 
    WHERE user_id = '$user_id'";
    
$withdrawal_stats_result = mysqli_query($conn, $withdrawal_stats_sql);
$withdrawal_stats = mysqli_fetch_assoc($withdrawal_stats_result);

// Update stats with deposit and withdrawal data
$stats['total_credits'] += $deposit_stats['total_deposit_amount'];
$stats['total_debits'] += $withdrawal_stats['total_withdrawal_amount'];
$stats['total_transactions'] += $deposit_stats['total_deposits'] + $withdrawal_stats['total_withdrawals'];
$stats['net_flow'] = $stats['total_credits'] - $stats['total_debits'];

// Get current wallet balance
$wallet_sql = "SELECT available_balance, fund_balance FROM users WHERE id = '$user_id'";
$wallet_result = mysqli_query($conn, $wallet_sql);
$wallet = mysqli_fetch_assoc($wallet_result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction History - AI Trading Platform</title>
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
    .transaction-card {
        border: none;
        border-radius: 10px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        margin-bottom: 10px;
    }
    .transaction-card:hover {
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    .transaction-credit {
        border-left: 4px solid #28a745;
    }
    .transaction-debit {
        border-left: 4px solid #dc3545;
    }
    .transaction-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
    }
    .icon-credit { background-color: #d4edda; color: #28a745; }
    .icon-debit { background-color: #f8d7da; color: #dc3545; }
    .icon-deposit { background-color: #cce5ff; color: #0d6efd; }
    .icon-withdrawal { background-color: #fff3cd; color: #ffc107; }
    .amount-credit { color: #28a745; font-weight: bold; }
    .amount-debit { color: #dc3545; font-weight: bold; }
    .amount-deposit { color: #0d6efd; font-weight: bold; }
    .amount-withdrawal { color: #ffc107; font-weight: bold; }
    .status-badge { font-size: 0.75em; }
    .filter-section {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .stat-card {
        text-align: center;
        padding: 15px;
        border-radius: 10px;
        margin-bottom: 15px;
    }
    .stat-total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
    .stat-credit { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; }
    .stat-debit { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white; }
    .stat-net { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white; }
    .export-btn { background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); border: none; }
    .empty-state {
        text-align: center;
        padding: 40px 20px;
    }
    .category-badge {
        font-size: 0.7em;
        background: #6c757d;
        color: white;
    }
    .tx-hash {
        font-family: monospace;
        font-size: 0.8em;
        background: #f8f9fa;
        padding: 2px 6px;
        border-radius: 4px;
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Transaction History</h3>
                                        <p class="mb-2">View all your transactions including deposits, withdrawals, and trading</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="wallets.php">Wallet</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Transaction History</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transaction Statistics -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-total">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-receipt"></i>
                            </div>
                            <h5 class="mb-1"><?php echo number_format($stats['total_transactions']); ?></h5>
                            <p class="mb-0">Total Transactions</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-credit">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-arrow-down-to-line"></i>
                            </div>
                            <h5 class="mb-1">$ <?php echo number_format($stats['total_credits'], 2); ?></h5>
                            <p class="mb-0">Total Credits</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-debit">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-arrow-up-from-line"></i>
                            </div>
                            <h5 class="mb-1">$ <?php echo number_format($stats['total_debits'], 2); ?></h5>
                            <p class="mb-0">Total Debits</p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6">
                        <div class="stat-card stat-net">
                            <div class="stat-icon mb-2">
                                <i class="fi fi-rr-trend-up"></i>
                            </div>
                            <h5 class="mb-1">$ <?php echo number_format($stats['net_flow'], 2); ?></h5>
                            <p class="mb-0">Net Flow</p>
                        </div>
                    </div>
                </div>

                <!-- Current Balance -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h6 class="card-title mb-1">Current Wallet Balance</h6>
                                        <h3 class="text-primary mb-0">$ <?php echo number_format($wallet['available_balance'], 2); ?></h3>
                                        <small class="text-muted">
                                            Available Balance | 
                                            Locked Funds: $<?php echo number_format($wallet['fund_balance'], 2); ?>
                                        </small>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <a href="wallets.php" class="btn btn-outline-primary me-2">
                                            <i class="fi fi-rr-arrow-left me-1"></i>Back to Wallet
                                        </a>
                                        <button class="btn export-btn" onclick="exportTransactions()">
                                            <i class="fi fi-rr-download me-1"></i>Export
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters Section -->
                <div class="card filter-section">
                    <div class="card-body">
                        <h5 class="card-title mb-3">Filter Transactions</h5>
                        <form method="GET" action="transaction_history.php" class="row g-3">
                            <div class="col-md-2">
                                <label class="form-label">Type</label>
                                <select class="form-select" name="type">
                                    <option value="">All Types</option>
                                    <option value="credit" <?php echo $type_filter == 'credit' ? 'selected' : ''; ?>>Credit</option>
                                    <option value="debit" <?php echo $type_filter == 'debit' ? 'selected' : ''; ?>>Debit</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Category</label>
                                <select class="form-select" name="category">
                                    <option value="">All Categories</option>
                                    <option value="deposit" <?php echo $category_filter == 'deposit' ? 'selected' : ''; ?>>Deposit</option>
                                    <option value="withdrawal" <?php echo $category_filter == 'withdrawal' ? 'selected' : ''; ?>>Withdrawal</option>
                                    <option value="profit" <?php echo $category_filter == 'profit' ? 'selected' : ''; ?>>Trading Profit</option>
                                    <option value="fee" <?php echo $category_filter == 'fee' ? 'selected' : ''; ?>>Fee</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Statuses</option>
                                    <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="processing" <?php echo $status_filter == 'processing' ? 'selected' : ''; ?>>Processing</option>
                                    <option value="failed" <?php echo $status_filter == 'failed' ? 'selected' : ''; ?>>Failed</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">From Date</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">To Date</label>
                                <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search...">
                            </div>
                            <div class="col-12">
                                <div class="d-flex justify-content-between">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fi fi-rr-filter me-1"></i>Apply Filters
                                    </button>
                                    <a href="transaction_history.php" class="btn btn-outline-secondary">
                                        <i class="fi fi-rr-refresh me-1"></i>Clear Filters
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Transactions List -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">
                            Transaction History 
                            <span class="badge bg-primary"><?php echo $total_transactions; ?></span>
                        </h5>
                        <div class="d-flex gap-2">
                            <span class="text-muted">
                                Showing <?php echo count($paginated_transactions); ?> of <?php echo $total_transactions; ?> transactions
                            </span>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($paginated_transactions)): ?>
                            <div class="transactions-list">
                                <?php foreach($paginated_transactions as $transaction): 
                                    // Determine transaction type and styling
                                    $is_credit = in_array($transaction['type'], ['credit', 'profit', 'deposit']);
                                    $is_deposit = $transaction['type'] === 'deposit';
                                    $is_withdrawal = $transaction['type'] === 'withdrawal';
                                    
                                    $icon_class = '';
                                    $amount_class = '';
                                    $transaction_class = '';
                                    
                                    if ($is_deposit) {
                                        $icon_class = 'icon-deposit';
                                        $amount_class = 'amount-deposit';
                                        $transaction_class = 'transaction-credit';
                                        $sign = '+';
                                    } elseif ($is_withdrawal) {
                                        $icon_class = 'icon-withdrawal';
                                        $amount_class = 'amount-withdrawal';
                                        $transaction_class = 'transaction-debit';
                                        $sign = '-';
                                    } elseif ($is_credit) {
                                        $icon_class = 'icon-credit';
                                        $amount_class = 'amount-credit';
                                        $transaction_class = 'transaction-credit';
                                        $sign = '+';
                                    } else {
                                        $icon_class = 'icon-debit';
                                        $amount_class = 'amount-debit';
                                        $transaction_class = 'transaction-debit';
                                        $sign = '-';
                                    }
                                    
                                    // Get appropriate icon
                                    $icon = getTransactionIcon($transaction['category'], $transaction['type']);
                                    
                                    // Format description
                                    $description = $transaction['description'];
                                    if ($is_deposit && strlen($description) > 20) {
                                        $description = 'Deposit: ' . substr($description, 0, 10) . '...' . substr($description, -10);
                                    } elseif ($is_withdrawal && strlen($description) > 20) {
                                        $description = 'Withdrawal to: ' . substr($description, 0, 10) . '...' . substr($description, -10);
                                    }
                                    
                                    // Status badge class
                                    $status_class = getStatusBadgeClass($transaction['status']);
                                    $status_text = getStatusText($transaction['status']);
                                    
                                    // Category display
                                    $category_display = ucfirst(str_replace('_', ' ', $transaction['category']));
                                ?>
                                <div class="card transaction-card <?php echo $transaction_class; ?>">
                                    <div class="card-body">
                                        <div class="row align-items-center">
                                            <div class="col-md-1">
                                                <div class="transaction-icon <?php echo $icon_class; ?>">
                                                    <i class="<?php echo $icon; ?>"></i>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($description); ?></h6>
                                                <div class="d-flex gap-2 align-items-center">
                                                    <span class="badge category-badge"><?php echo $category_display; ?></span>
                                                    <?php if (!empty($transaction['note'])): ?>
                                                        <small class="text-muted"><?php echo htmlspecialchars($transaction['note']); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <small class="text-muted">
                                                    <?php echo date('M j, Y', strtotime($transaction['created_at'])); ?>
                                                </small>
                                                <div>
                                                    <small class="text-muted">
                                                        <?php echo date('g:i A', strtotime($transaction['created_at'])); ?>
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="col-md-2 text-center">
                                                <span class="badge <?php echo $status_class; ?> status-badge">
                                                    <?php echo $status_text; ?>
                                                </span>
                                            </div>
                                            <div class="col-md-2 text-end">
                                                <div class="<?php echo $amount_class; ?>">
                                                    <?php echo $sign; ?>$ <?php echo number_format($transaction['net_amount'], 2); ?>
                                                    <?php if ($transaction['fee'] > 0): ?>
                                                        <br><small class="text-muted">Fee: $<?php echo number_format($transaction['fee'], 2); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if (!empty($transaction['balance_after'])): ?>
                                                <small class="text-muted">
                                                    Balance: $<?php echo number_format($transaction['balance_after'], 2); ?>
                                                </small>
                                                <?php endif; ?>
                                            </div>
                                            <div class="col-md-1 text-end">
                                                <button class="btn btn-sm btn-outline-primary" 
                                                        onclick="viewTransactionDetails('<?php echo $transaction['type']; ?>', <?php echo $transaction['id']; ?>)"
                                                        title="View Details">
                                                    <i class="fi fi-rr-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <!-- Pagination -->
                            <?php if($total_pages > 1): ?>
                            <nav aria-label="Transaction pagination" class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <?php if($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page - 1))); ?>">
                                            <i class="fi fi-rr-arrow-left me-1"></i>Previous
                                        </a>
                                    </li>
                                    <?php endif; ?>

                                    <?php 
                                    // Show page numbers
                                    $start_page = max(1, $page - 2);
                                    $end_page = min($total_pages, $page + 2);
                                    
                                    for($i = $start_page; $i <= $end_page; $i++): 
                                    ?>
                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $i))); ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    </li>
                                    <?php endfor; ?>

                                    <?php if($page < $total_pages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page' => $page + 1))); ?>">
                                            Next<i class="fi fi-rr-arrow-right ms-1"></i>
                                        </a>
                                    </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                            <?php endif; ?>

                        <?php else: ?>
                            <div class="empty-state">
                                <i class="fi fi-rr-receipt fs-1 text-muted mb-3"></i>
                                <h5 class="text-muted">No transactions found</h5>
                                <p class="text-muted mb-4">
                                    <?php echo ($type_filter || $category_filter || $status_filter || $date_from || $date_to || $search) ? 
                                        'Try adjusting your filters' : 
                                        'You haven\'t made any transactions yet'; ?>
                                </p>
                                <?php if($type_filter || $category_filter || $status_filter || $date_from || $date_to || $search): ?>
                                    <a href="transaction_history.php" class="btn btn-primary">Clear Filters</a>
                                <?php else: ?>
                                    <a href="wallets.php" class="btn btn-primary">Make Your First Transaction</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <?php include('includes/footer.php');?>
    </div>

    <!-- Transaction Details Modal -->
    <div class="modal fade" id="transactionDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Transaction Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="transactionDetailsContent">
                    <!-- Content will be loaded via AJAX -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="printTransaction()">Print Receipt</button>
                </div>
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
    function viewTransactionDetails(type, id) {
        $.ajax({
            url: 'get_transaction_details.php',
            method: 'GET',
            data: { type: type, id: id },
            success: function(response) {
                $('#transactionDetailsContent').html(response);
                const modal = new bootstrap.Modal(document.getElementById('transactionDetailsModal'));
                modal.show();
            },
            error: function() {
                alert('Error loading transaction details');
            }
        });
    }

    function exportTransactions() {
        // Get current filter parameters
        const params = new URLSearchParams(window.location.search);
        
        // Redirect to export script with current filters
        window.location.href = 'export_transactions.php?' + params.toString();
    }

    function printTransaction() {
        const content = document.getElementById('transactionDetailsContent').innerHTML;
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
            <html>
                <head>
                    <title>Transaction Receipt - AI Trading Platform</title>
                    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
                    <style>
                        body { font-family: Arial, sans-serif; }
                        .receipt-header { text-align: center; margin-bottom: 20px; }
                        .receipt-details { margin: 20px 0; }
                        .receipt-table { width: 100%; margin: 20px 0; }
                        .receipt-table td { padding: 8px; border-bottom: 1px solid #dee2e6; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="receipt-header">
                            <h3>AI Trading Platform</h3>
                            <p>Transaction Receipt</p>
                            <p>Generated on: ${new Date().toLocaleString()}</p>
                        </div>
                        ${content}
                    </div>
                </body>
            </html>
        `);
        printWindow.document.close();
        printWindow.print();
    }

    // Auto-submit form when date inputs change (for better UX)
    document.addEventListener('DOMContentLoaded', function() {
        const dateInputs = document.querySelectorAll('input[type="date"]');
        dateInputs.forEach(input => {
            input.addEventListener('change', function() {
                // Small delay to ensure all filters are set
                setTimeout(() => {
                    document.querySelector('form').submit();
                }, 500);
            });
        });
    });
    </script>
</body>
</html>

<?php
// Helper function to get appropriate icon for transaction
function getTransactionIcon($category, $type) {
    switch($type) {
        case 'deposit':
            return 'fi fi-rr-download';
        case 'withdrawal':
            return 'fi fi-rr-upload';
        case 'credit':
        case 'profit':
            return 'fi fi-rr-plus';
        case 'debit':
        case 'fee':
            return 'fi fi-rr-minus';
        default:
            return 'fi fi-rr-exchange';
    }
}

// Helper function to get status badge class
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'completed':
        case 'confirmed':
            return 'bg-success';
        case 'pending':
            return 'bg-warning';
        case 'processing':
            return 'bg-info';
        case 'rejected':
        case 'failed':
        case 'cancelled':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}

// Helper function to get status text
function getStatusText($status) {
    switch ($status) {
        case 'completed':
        case 'confirmed':
            return 'Completed';
        case 'pending':
            return 'Pending';
        case 'processing':
            return 'Processing';
        case 'rejected':
            return 'Rejected';
        case 'cancelled':
            return 'Cancelled';
        case 'failed':
            return 'Failed';
        default:
            return ucfirst($status);
    }
}

mysqli_close($conn);
?>