<?php
require_once 'config.php';
require_once 'classes/Security.php';
require_once 'classes/Wallet.php';

Security::requireAuth();

$pageTitle = 'Transaction History - CryptoExchange Pro | Account Transactions';
$pageDescription = 'View your complete cryptocurrency transaction history including deposits, withdrawals, trades, and fees.';

$wallet = new Wallet();

// Get filter parameters
$filterType = $_GET['type'] ?? '';
$filterCrypto = $_GET['crypto'] ?? '';
$filterStatus = $_GET['status'] ?? '';
$limit = $_GET['limit'] ?? 50;

// Build query with filters
$whereConditions = ['t.user_id = :user_id'];
$params = [':user_id' => $_SESSION['user_id']];

if ($filterType) {
    $whereConditions[] = 't.transaction_type = :type';
    $params[':type'] = $filterType;
}

if ($filterCrypto) {
    $whereConditions[] = 't.crypto_id = :crypto_id';
    $params[':crypto_id'] = $filterCrypto;
}

if ($filterStatus) {
    $whereConditions[] = 't.status = :status';
    $params[':status'] = $filterStatus;
}

$whereClause = implode(' AND ', $whereConditions);

$db = new Database();
$db->query("SELECT t.*, c.symbol, c.name 
           FROM transactions t 
           JOIN cryptocurrencies c ON t.crypto_id = c.id 
           WHERE $whereClause 
           ORDER BY t.created_at DESC 
           LIMIT :limit");

foreach ($params as $key => $value) {
    $db->bind($key, $value);
}
$db->bind(':limit', (int)$limit);

$transactions = $db->resultSet();

// Get cryptocurrencies for filter
$db->query("SELECT DISTINCT c.id, c.symbol, c.name 
           FROM cryptocurrencies c 
           JOIN transactions t ON c.id = t.crypto_id 
           WHERE t.user_id = :user_id 
           ORDER BY c.symbol");
$db->bind(':user_id', $_SESSION['user_id']);
$availableCryptos = $db->resultSet();

// Get transaction statistics
$db->query("SELECT 
               COUNT(*) as total_transactions,
               SUM(CASE WHEN transaction_type IN ('deposit', 'trade_buy') THEN amount ELSE 0 END) as total_received,
               SUM(CASE WHEN transaction_type IN ('withdrawal', 'trade_sell', 'fee') THEN ABS(amount) ELSE 0 END) as total_sent,
               COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count
           FROM transactions 
           WHERE user_id = :user_id");
$db->bind(':user_id', $_SESSION['user_id']);
$stats = $db->single();

include 'includes/header.php';
?>

<main style="min-height: 100vh; background-color: var(--bg-secondary); padding: 40px 0;">
    <div class="container">
        <!-- Header -->
        <div class="mb-4">
            <h1 style="font-size: 2.5rem; font-weight: 700; color: var(--text-primary); margin-bottom: 8px;">
                <i class="fas fa-history" style="color: var(--primary-color); margin-right: 16px;"></i>Transaction History
            </h1>
            <p style="color: var(--text-secondary); font-size: 16px;">View and manage your cryptocurrency transactions</p>
        </div>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-3">
                <div class="card">
                    <div class="card-body text-center">
                        <div style="color: var(--primary-color); font-size: 2rem; margin-bottom: 8px;">
                            <i class="fas fa-receipt"></i>
                        </div>
                        <h3 style="font-size: 2rem; font-weight: 700; margin-bottom: 4px;"><?php echo number_format($stats['total_transactions']); ?></h3>
                        <p style="color: var(--text-secondary); margin: 0;">Total Transactions</p>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card">
                    <div class="card-body text-center">
                        <div style="color: var(--secondary-color); font-size: 2rem; margin-bottom: 8px;">
                            <i class="fas fa-arrow-down"></i>
                        </div>
                        <h3 style="font-size: 2rem; font-weight: 700; margin-bottom: 4px;"><?php echo number_format($stats['total_received'], 4); ?></h3>
                        <p style="color: var(--text-secondary); margin: 0;">Total Received</p>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card">
                    <div class="card-body text-center">
                        <div style="color: var(--danger-color); font-size: 2rem; margin-bottom: 8px;">
                            <i class="fas fa-arrow-up"></i>
                        </div>
                        <h3 style="font-size: 2rem; font-weight: 700; margin-bottom: 4px;"><?php echo number_format($stats['total_sent'], 4); ?></h3>
                        <p style="color: var(--text-secondary); margin: 0;">Total Sent</p>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card">
                    <div class="card-body text-center">
                        <div style="color: var(--warning-color); font-size: 2rem; margin-bottom: 8px;">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h3 style="font-size: 2rem; font-weight: 700; margin-bottom: 4px;"><?php echo number_format($stats['pending_count']); ?></h3>
                        <p style="color: var(--text-secondary); margin: 0;">Pending</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters and Transactions -->
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h2 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                        <i class="fas fa-filter" style="color: var(--primary-color); margin-right: 8px;"></i>
                        Transaction Filters
                    </h2>
                    <button class="btn btn-outline-primary btn-sm" onclick="exportTransactions()">
                        <i class="fas fa-download"></i> Export CSV
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="mb-4">
                    <div class="row">
                        <div class="col-3">
                            <div class="form-group">
                                <label class="form-label">Transaction Type</label>
                                <select name="type" class="form-control form-select">
                                    <option value="">All Types</option>
                                    <option value="deposit" <?php echo $filterType === 'deposit' ? 'selected' : ''; ?>>Deposit</option>
                                    <option value="withdrawal" <?php echo $filterType === 'withdrawal' ? 'selected' : ''; ?>>Withdrawal</option>
                                    <option value="trade_buy" <?php echo $filterType === 'trade_buy' ? 'selected' : ''; ?>>Trade Buy</option>
                                    <option value="trade_sell" <?php echo $filterType === 'trade_sell' ? 'selected' : ''; ?>>Trade Sell</option>
                                    <option value="fee" <?php echo $filterType === 'fee' ? 'selected' : ''; ?>>Fee</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label class="form-label">Cryptocurrency</label>
                                <select name="crypto" class="form-control form-select">
                                    <option value="">All Cryptocurrencies</option>
                                    <?php foreach ($availableCryptos as $crypto): ?>
                                    <option value="<?php echo $crypto['id']; ?>" <?php echo $filterCrypto == $crypto['id'] ? 'selected' : ''; ?>>
                                        <?php echo $crypto['symbol']; ?> - <?php echo $crypto['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-control form-select">
                                    <option value="">All Statuses</option>
                                    <option value="pending" <?php echo $filterStatus === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="confirmed" <?php echo $filterStatus === 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                                    <option value="failed" <?php echo $filterStatus === 'failed' ? 'selected' : ''; ?>>Failed</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="form-group">
                                <label class="form-label">Limit</label>
                                <select name="limit" class="form-control form-select">
                                    <option value="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25 transactions</option>
                                    <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50 transactions</option>
                                    <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100 transactions</option>
                                    <option value="250" <?php echo $limit == 250 ? 'selected' : ''; ?>>250 transactions</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> Apply Filters
                        </button>
                        <a href="transactions.php" class="btn btn-outline-primary">
                            <i class="fas fa-times"></i> Clear Filters
                        </a>
                    </div>
                </form>

                <!-- Transactions Table -->
                <?php if (!empty($transactions)): ?>
                <div style="overflow-x: auto;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Type</th>
                                <th>Asset</th>
                                <th style="text-align: right;">Amount</th>
                                <th style="text-align: right;">Balance Before</th>
                                <th style="text-align: right;">Balance After</th>
                                <th style="text-align: center;">Status</th>
                                <th>Transaction Hash</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $tx): ?>
                            <tr>
                                <td style="font-size: 14px; white-space: nowrap;">
                                    <?php echo date('M j, Y', strtotime($tx['created_at'])); ?><br>
                                    <small style="color: var(--text-secondary);"><?php echo date('H:i:s', strtotime($tx['created_at'])); ?></small>
                                </td>
                                <td>
                                    <?php
                                    $typeClasses = [
                                        'deposit' => 'badge-success',
                                        'withdrawal' => 'badge-danger',
                                        'trade_buy' => 'badge-primary',
                                        'trade_sell' => 'badge-warning',
                                        'fee' => 'badge-secondary'
                                    ];
                                    $typeIcons = [
                                        'deposit' => 'fa-arrow-down',
                                        'withdrawal' => 'fa-arrow-up',
                                        'trade_buy' => 'fa-shopping-cart',
                                        'trade_sell' => 'fa-tag',
                                        'fee' => 'fa-percent'
                                    ];
                                    ?>
                                    <span class="badge <?php echo $typeClasses[$tx['transaction_type']] ?? 'badge-secondary'; ?>">
                                        <i class="fas <?php echo $typeIcons[$tx['transaction_type']] ?? 'fa-question'; ?>"></i>
                                        <?php echo strtoupper(str_replace('_', ' ', $tx['transaction_type'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="trading-pair">
                                        <div class="crypto-icon" style="background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); width: 24px; height: 24px; font-size: 10px;">
                                            <?php echo substr($tx['symbol'], 0, 1); ?>
                                        </div>
                                        <div>
                                            <div style="font-weight: 600; color: var(--text-primary); font-size: 14px;"><?php echo $tx['symbol']; ?></div>
                                            <div style="font-size: 11px; color: var(--text-secondary);"><?php echo $tx['name']; ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td style="text-align: right; font-family: monospace;">
                                    <span style="font-weight: 600; color: <?php echo $tx['amount'] >= 0 ? 'var(--secondary-color)' : 'var(--danger-color)'; ?>;">
                                        <?php echo ($tx['amount'] >= 0 ? '+' : '') . number_format($tx['amount'], 8); ?>
                                    </span>
                                    <div style="font-size: 11px; color: var(--text-secondary);"><?php echo $tx['symbol']; ?></div>
                                </td>
                                <td style="text-align: right; font-family: monospace; font-size: 13px; color: var(--text-secondary);">
                                    <?php echo number_format($tx['balance_before'], 8); ?>
                                </td>
                                <td style="text-align: right; font-family: monospace; font-size: 13px; color: var(--text-primary);">
                                    <?php echo number_format($tx['balance_after'], 8); ?>
                                </td>
                                <td style="text-align: center;">
                                    <?php
                                    $statusClasses = [
                                        'pending' => 'badge-warning',
                                        'confirmed' => 'badge-success',
                                        'failed' => 'badge-danger'
                                    ];
                                    $statusIcons = [
                                        'pending' => 'fa-clock',
                                        'confirmed' => 'fa-check-circle',
                                        'failed' => 'fa-times-circle'
                                    ];
                                    ?>
                                    <span class="badge <?php echo $statusClasses[$tx['status']]; ?>">
                                        <i class="fas <?php echo $statusIcons[$tx['status']]; ?>"></i>
                                        <?php echo strtoupper($tx['status']); ?>
                                    </span>
                                </td>
                                <td style="font-family: monospace; font-size: 12px;">
                                    <?php if ($tx['transaction_hash']): ?>
                                    <span title="<?php echo $tx['transaction_hash']; ?>">
                                        <?php echo substr($tx['transaction_hash'], 0, 8) . '...'; ?>
                                    </span>
                                    <?php else: ?>
                                    <span style="color: var(--text-secondary);">-</span>
                                    <?php endif; ?>
                                </td>
                                <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; font-size: 13px;">
                                    <?php echo $tx['notes'] ?: '-'; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Info -->
                <div class="d-flex justify-content-between align-items-center mt-3">
                    <div style="color: var(--text-secondary); font-size: 14px;">
                        Showing <?php echo count($transactions); ?> of <?php echo $stats['total_transactions']; ?> transactions
                    </div>
                    <?php if (count($transactions) >= $limit): ?>
                    <div>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['limit' => $limit + 50])); ?>" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-plus"></i> Load More
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
                <?php else: ?>
                <div style="text-align: center; padding: 60px 0;">
                    <i class="fas fa-receipt" style="font-size: 4rem; color: var(--text-secondary); margin-bottom: 20px;"></i>
                    <h3 style="color: var(--text-secondary); margin-bottom: 12px;">No transactions found</h3>
                    <p style="color: var(--text-secondary); margin-bottom: 20px;">
                        <?php if ($filterType || $filterCrypto || $filterStatus): ?>
                        No transactions match your current filters. Try adjusting your search criteria.
                        <?php else: ?>
                        You haven't made any transactions yet. Start trading to see your transaction history here.
                        <?php endif; ?>
                    </p>
                    <?php if ($filterType || $filterCrypto || $filterStatus): ?>
                    <a href="transactions.php" class="btn btn-primary">
                        <i class="fas fa-times"></i> Clear Filters
                    </a>
                    <?php else: ?>
                    <a href="trading.php" class="btn btn-primary">
                        <i class="fas fa-exchange-alt"></i> Start Trading
                    </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<script>
function exportTransactions() {
    // Create CSV content
    const transactions = <?php echo json_encode($transactions); ?>;
    
    if (transactions.length === 0) {
        alert('No transactions to export');
        return;
    }
    
    let csv = 'Date,Type,Asset,Amount,Balance Before,Balance After,Status,Transaction Hash,Notes\n';
    
    transactions.forEach(tx => {
        const date = new Date(tx.created_at).toLocaleString();
        const type = tx.transaction_type.replace('_', ' ').toUpperCase();
        const amount = parseFloat(tx.amount).toFixed(8);
        const balanceBefore = parseFloat(tx.balance_before).toFixed(8);
        const balanceAfter = parseFloat(tx.balance_after).toFixed(8);
        const notes = (tx.notes || '').replace(/"/g, '""');
        
        csv += `"${date}","${type}","${tx.symbol}","${amount}","${balanceBefore}","${balanceAfter}","${tx.status.toUpperCase()}","${tx.transaction_hash || ''}","${notes}"\n`;
    });
    
    // Download CSV
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `transactions_${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}
</script>

<?php include 'includes/footer.php'; ?>