<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
require_once 'db.php';

$user_id = $_SESSION['user_id'];

// Combine all transaction types into one result set
$union_query = "
    (SELECT 'Deposit'    AS type, amount, status,       created_at FROM deposits    WHERE user_id=?)
    UNION
    (SELECT 'Withdrawal' AS type, amount, status,       created_at FROM withdrawals WHERE user_id=?)
    UNION
    (SELECT 'Investment' AS type, amount, status,       start_date AS created_at FROM investments WHERE user_id=?)
    UNION
    (SELECT 'Profit'     AS type, amount, 'processed'  AS status,  created_at FROM profits     WHERE user_id=?)
    ORDER BY created_at DESC
";

$stmt = mysqli_prepare($conn, $union_query);
if ($stmt) {
    mysqli_stmt_bind_param($stmt, 'iiii', $user_id, $user_id, $user_id, $user_id);
    mysqli_stmt_execute($stmt);
    $transactions_result = mysqli_stmt_get_result($stmt);
} else {
    $transactions_result = null;
}

// Calculate counts
$total_transactions = $transactions_result ? mysqli_num_rows($transactions_result) : 0;
$processing_count   = 0;
$processed_count    = 0;

if ($transactions_result && $total_transactions > 0) {
    while ($row = mysqli_fetch_assoc($transactions_result)) {
        if ($row['status'] === 'processing') $processing_count++;
        if (in_array($row['status'], ['processed', 'running', 'matured'])) $processed_count++;
    }
    mysqli_data_seek($transactions_result, 0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction History - MaxTrade</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background-color: #000; color: #fff;
            font-family: Arial, sans-serif;
            padding-bottom: 70px;
        }

        /* ── Header ── */
        .header {
            background: #111; padding: 15px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.5);
            position: sticky; top: 0; z-index: 100;
        }
        .header h1 { color: #fff; font-size: 18px; }
        .back-btn {
            position: absolute; left: 15px; top: 50%;
            transform: translateY(-50%);
            color: #FFD700; text-decoration: none; font-size: 22px;
        }

        /* ── Stats ── */
        .container { padding: 12px; }
        .stats-grid {
            display: grid; grid-template-columns: repeat(2, 1fr);
            gap: 10px; margin-bottom: 14px;
        }
        .stat-card {
            background: #111; border-radius: 10px;
            padding: 14px; text-align: center;
        }
        .stat-value { font-size: 22px; font-weight: bold; color: #FFD700; margin-bottom: 4px; }
        .stat-label { font-size: 11px; color: #888; }

        /* ── Filter Tabs ── */
        .filter-tabs {
            display: flex; gap: 8px;
            margin-bottom: 14px; overflow-x: auto; padding-bottom: 4px;
        }
        .filter-tab {
            padding: 8px 16px; background: #111;
            border-radius: 8px; cursor: pointer;
            font-weight: bold; white-space: nowrap;
            transition: all 0.3s; font-size: 12px; color: #fff;
            border: 1px solid #222;
        }
        .filter-tab.active { background: #FFD700; color: #000; border-color: #FFD700; }
        .filter-tab:hover:not(.active) { border-color: #FFD700; color: #FFD700; }

        /* ── Transaction Card ── */
        .transaction-card {
            background: #111; border-radius: 12px;
            padding: 14px; margin-bottom: 10px;
            display: flex; justify-content: space-between;
            align-items: center; gap: 12px;
            border: 1px solid #1a1a1a;
        }
        .transaction-left { display: flex; align-items: center; gap: 12px; flex: 1; }

        /* Icon circle */
        .tx-icon {
            width: 42px; height: 42px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 18px; flex-shrink: 0;
        }
        .tx-icon.deposit    { background: rgba(0,230,118,0.15);  color: #00e676; }
        .tx-icon.withdrawal { background: rgba(255,100,100,0.15); color: #ff6464; }
        .tx-icon.investment { background: rgba(255,215,0,0.15);   color: #FFD700; }
        .tx-icon.profit     { background: rgba(0,180,255,0.15);   color: #00b4ff; }

        .tx-info {}
        .tx-type  { font-weight: bold; font-size: 13px; color: #fff; }
        .tx-date  { font-size: 10px; color: #666; margin-top: 2px; }
        .tx-badge {
            display: inline-block; margin-top: 4px;
            padding: 2px 8px; border-radius: 4px;
            font-size: 9px; font-weight: bold;
        }

        /* Status colours */
        .badge-processing { background: rgba(255,165,0,0.2);  color: #FFA500; border: 1px solid #FFA500; }
        .badge-processed  { background: rgba(0,230,118,0.2);  color: #00e676; border: 1px solid #00e676; }
        .badge-rejected   { background: rgba(255,100,100,0.2);color: #ff6464; border: 1px solid #ff6464; }
        .badge-running    { background: rgba(0,230,118,0.2);  color: #00e676; border: 1px solid #00e676; }
        .badge-matured    { background: rgba(255,215,0,0.2);  color: #FFD700; border: 1px solid #FFD700; }
        .badge-cancelled  { background: rgba(150,150,150,0.2);color: #888;    border: 1px solid #555;    }

        /* Amount column */
        .tx-amount { text-align: right; white-space: nowrap; }
        .tx-amount-value { font-size: 16px; font-weight: bold; }
        .amount-positive { color: #00e676; }
        .amount-negative { color: #ff6464; }
        .amount-neutral  { color: #FFD700; }

        /* No transactions */
        .no-transactions {
            background: #111; border-radius: 12px;
            padding: 40px 20px; text-align: center; color: #555;
        }
        .no-transactions i { font-size: 40px; opacity: 0.3; display: block; margin-bottom: 12px; }
    </style>
</head>
<body>

    <div class="header" style="position:relative;">
        <a href="profile.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
        <h1><i class="fas fa-history"></i> Transaction History</h1>
    </div>

    <div class="container">

        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-value"><?php echo $total_transactions; ?></div>
                <div class="stat-label">Total Transactions</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $processing_count; ?></div>
                <div class="stat-label">Pending / Processing</div>
            </div>
        </div>

        <!-- Filter Tabs -->
        <div class="filter-tabs">
            <div class="filter-tab active" onclick="filterTx('all', this)">All</div>
            <div class="filter-tab" onclick="filterTx('Deposit',    this)">Deposits</div>
            <div class="filter-tab" onclick="filterTx('Withdrawal', this)">Withdrawals</div>
            <div class="filter-tab" onclick="filterTx('Investment', this)">Investments</div>
            <div class="filter-tab" onclick="filterTx('Profit',     this)">Profits</div>
        </div>

        <!-- Transaction List -->
        <div id="tx-container">
        <?php if ($transactions_result && $total_transactions > 0):
            while ($tx = mysqli_fetch_assoc($transactions_result)):
                $type   = $tx['type'];
                $amount = floatval($tx['amount']);
                $status = $tx['status'] ?? '';
                $date   = date('d M Y, h:i A', strtotime($tx['created_at']));

                // Icon class & FA icon
                switch ($type) {
                    case 'Deposit':
                        $icon_class = 'deposit';
                        $icon       = 'fa-arrow-down';
                        $amt_class  = 'amount-positive';
                        $sign       = '+';
                        break;
                    case 'Withdrawal':
                        $icon_class = 'withdrawal';
                        $icon       = 'fa-arrow-up';
                        $amt_class  = 'amount-negative';
                        $sign       = '-';
                        break;
                    case 'Investment':
                        $icon_class = 'investment';
                        $icon       = 'fa-chart-line';
                        $amt_class  = 'amount-neutral';
                        $sign       = '';
                        break;
                    case 'Profit':
                        $icon_class = 'profit';
                        $icon       = 'fa-coins';
                        $amt_class  = 'amount-positive';
                        $sign       = '+';
                        break;
                    default:
                        $icon_class = 'investment';
                        $icon       = 'fa-circle';
                        $amt_class  = 'amount-neutral';
                        $sign       = '';
                }

                // Badge class
                $badge_class = 'badge-' . strtolower($status);
        ?>
        <div class="transaction-card" data-type="<?php echo htmlspecialchars($type); ?>">
            <div class="transaction-left">
                <div class="tx-icon <?php echo $icon_class; ?>">
                    <i class="fas <?php echo $icon; ?>"></i>
                </div>
                <div class="tx-info">
                    <div class="tx-type"><?php echo htmlspecialchars($type); ?></div>
                    <div class="tx-date"><?php echo $date; ?></div>
                    <span class="tx-badge <?php echo $badge_class; ?>">
                        <?php echo strtoupper($status); ?>
                    </span>
                </div>
            </div>
            <div class="tx-amount">
                <div class="tx-amount-value <?php echo $amt_class; ?>">
                    <?php echo $sign; ?> ZMW <?php echo number_format($amount, 2); ?>
                </div>
            </div>
        </div>
        <?php   endwhile;
        else: ?>
            <div class="no-transactions">
                <i class="fas fa-inbox"></i>
                <h3>No Transactions Yet</h3>
                <p>Your transaction history will appear here.</p>
            </div>
        <?php endif; ?>
        </div>

    </div><!-- /.container -->

    <script>
        function filterTx(type, el) {
            document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
            el.classList.add('active');
            document.querySelectorAll('.transaction-card').forEach(card => {
                card.style.display =
                    (type === 'all' || card.dataset.type === type) ? 'flex' : 'none';
            });
        }
    </script>
    <?php include 'bottom-nav.php'; ?>
</body>
</html>
<?php
if (isset($stmt)) mysqli_stmt_close($stmt);
mysqli_close($conn);
?>