<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Transactions';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();
date_default_timezone_set('Africa/Nairobi');

// ============================================================================
// GET ADMIN CURRENCY
// ============================================================================
$adminCountry = getSetting('admin_country', 'Kenya');
$stmt = $conn->prepare("SELECT currency_symbol FROM countries WHERE name = ? LIMIT 1");
$defaultCurrency = 'Ksh';
if ($stmt) {
    $stmt->bind_param("s", $adminCountry);
    $stmt->execute();
    $r = $stmt->get_result();
    if ($r && $row = $r->fetch_assoc()) {
        $defaultCurrency = $row['currency_symbol'] ?? 'Ksh';
    }
    $stmt->close();
}

// ============================================================================
// COLLECT FILTER PARAMETERS
// ============================================================================
$filterStatus   = $_GET['status']    ?? 'all';
$filterType     = $_GET['type']      ?? 'all';
$filterCategory = $_GET['category']  ?? 'all';   // credit / debit / referral
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo   = $_GET['date_to']   ?? '';
$searchQuery    = trim($_GET['search'] ?? '');
$sortBy         = $_GET['sort']      ?? 'newest';
$page           = max(1, intval($_GET['page'] ?? 1));
$perPage        = 25;
$offset         = ($page - 1) * $perPage;

// ============================================================================
// BUILD QUERY WITH FILTERS
// ============================================================================
$where   = ["1=1"];
$params  = [];
$types   = "";

// Status filter
if ($filterStatus !== 'all' && in_array($filterStatus, ['completed', 'pending', 'failed'])) {
    $where[]  = "t.status = ?";
    $params[] = $filterStatus;
    $types   .= "s";
}

// Category filter (credit / debit / referral)
if ($filterCategory === 'credit') {
    $where[] = "t.type LIKE 'credit_%'";
} elseif ($filterCategory === 'debit') {
    $where[] = "t.type LIKE 'debit_%'";
} elseif ($filterCategory === 'referral') {
    $where[] = "(t.type = 'referral_bonus' OR t.type LIKE '%referral%')";
} elseif ($filterCategory === 'withdrawal') {
    $where[] = "(t.type LIKE '%withdrawal%' OR t.type LIKE 'debit_main%')";
} elseif ($filterCategory === 'task') {
    $where[] = "(t.type LIKE 'credit_video%' OR t.type LIKE 'credit_survey%' OR t.type LIKE 'credit_trivia%' OR t.type LIKE 'credit_ads%' OR t.type LIKE 'credit_blog%' OR t.type LIKE 'credit_meme%' OR t.type LIKE 'credit_spin%' OR t.type LIKE 'credit_chat%' OR t.type LIKE 'credit_transcription%')";
} elseif ($filterCategory === 'bonus') {
    $where[] = "(t.type LIKE '%bonus%' AND t.type != 'referral_bonus')";
}

// Specific type filter
if ($filterType !== 'all' && $filterType !== '') {
    $where[]  = "t.type = ?";
    $params[] = $filterType;
    $types   .= "s";
}

// Date range
if ($filterDateFrom !== '') {
    $where[]  = "DATE(t.created_at) >= ?";
    $params[] = $filterDateFrom;
    $types   .= "s";
}
if ($filterDateTo !== '') {
    $where[]  = "DATE(t.created_at) <= ?";
    $params[] = $filterDateTo;
    $types   .= "s";
}

// Search — username, description, reference
if ($searchQuery !== '') {
    $where[]  = "(u.username LIKE ? OR t.description LIKE ? OR t.reference LIKE ?)";
    $like     = "%{$searchQuery}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types   .= "sss";
}

$whereClause = implode(" AND ", $where);

// Sort
$orderClause = match ($sortBy) {
    'oldest'     => "t.created_at ASC",
    'amount_high'=> "t.amount DESC",
    'amount_low' => "t.amount ASC",
    default      => "t.created_at DESC",
};

// ============================================================================
// COUNT TOTAL FOR PAGINATION
// ============================================================================
$countSql = "SELECT COUNT(*) as total FROM transactions t JOIN users u ON t.user_id = u.id WHERE {$whereClause}";
$countStmt = $conn->prepare($countSql);
if ($types !== '' && $params) {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$totalRecords = intval($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
$totalPages   = max(1, ceil($totalRecords / $perPage));
$countStmt->close();

// ============================================================================
// FETCH TRANSACTIONS
// ============================================================================
$sql = "
    SELECT t.*, u.username, u.email, u.country
    FROM transactions t
    JOIN users u ON t.user_id = u.id
    WHERE {$whereClause}
    ORDER BY {$orderClause}
    LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $conn->prepare($sql);
if ($types !== '' && $params) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$transactions = $stmt->get_result();
$stmt->close();

// ============================================================================
// SUMMARY STATS FOR CURRENT FILTER
// ============================================================================
$summarySql = "
    SELECT 
        COUNT(*) as total_count,
        COALESCE(SUM(t.amount), 0) as total_amount,
        COALESCE(SUM(CASE WHEN t.type LIKE 'credit_%' OR t.type = 'referral_bonus' THEN t.amount ELSE 0 END), 0) as total_credits,
        COALESCE(SUM(CASE WHEN t.type LIKE 'debit_%' THEN t.amount ELSE 0 END), 0) as total_debits
    FROM transactions t
    JOIN users u ON t.user_id = u.id
    WHERE {$whereClause}
";
$summaryStmt = $conn->prepare($summarySql);
if ($types !== '' && $params) {
    $summaryStmt->bind_param($types, ...$params);
}
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc();
$summaryStmt->close();

// ============================================================================
// GET DISTINCT TRANSACTION TYPES FOR DROPDOWN
// ============================================================================
$typesResult = $conn->query("SELECT DISTINCT type FROM transactions ORDER BY type ASC");
$allTypes = [];
if ($typesResult) {
    while ($row = $typesResult->fetch_assoc()) {
        $allTypes[] = $row['type'];
    }
}

// ============================================================================
// QUICK STATS (always unfiltered)
// ============================================================================
$quickStats = [];
$quickStats['today_count'] = intval($conn->query("SELECT COUNT(*) as c FROM transactions WHERE DATE(created_at) = CURDATE()")->fetch_assoc()['c'] ?? 0);
$quickStats['today_credits'] = floatval($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM transactions WHERE (type LIKE 'credit_%' OR type = 'referral_bonus') AND status='completed' AND DATE(created_at) = CURDATE()")->fetch_assoc()['s'] ?? 0);
$quickStats['today_debits'] = floatval($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM transactions WHERE type LIKE 'debit_%' AND status='completed' AND DATE(created_at) = CURDATE()")->fetch_assoc()['s'] ?? 0);
$quickStats['pending_count'] = intval($conn->query("SELECT COUNT(*) as c FROM transactions WHERE status='pending'")->fetch_assoc()['c'] ?? 0);

// Helper
function safeTimeAgo2($dt) {
    if (empty($dt)) return 'N/A';
    return timeAgo($dt);
}

// Build current filter query string (for pagination links)
function buildFilterUrl($overrides = []) {
    $params = array_merge($_GET, $overrides);
    unset($params['page']); // page is set separately
    if (isset($overrides['page'])) $params['page'] = $overrides['page'];
    return 'transactions.php?' . http_build_query($params);
}
?>

<style>
/* ============================================================================
   TRANSACTIONS PAGE — FULLY RESPONSIVE
   ============================================================================ */
.transactions-container {
    padding: 16px;
    max-width: 1400px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 24px;
}

.page-title {
    font-size: 24px;
    font-weight: 900;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-subtitle {
    font-size: 13px;
    color: var(--text-secondary);
}

/* ---- Quick Stats Row ---- */
.quick-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    margin-bottom: 20px;
}

.quick-stat {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 16px;
    text-align: center;
    transition: transform 0.2s;
}

.quick-stat:hover {
    transform: translateY(-2px);
}

.quick-stat-value {
    font-size: 24px;
    font-weight: 900;
    color: var(--text-primary);
    line-height: 1;
    margin-bottom: 4px;
}

.quick-stat-label {
    font-size: 11px;
    color: var(--text-secondary);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.quick-stat-value.green { color: #10b981; }
.quick-stat-value.red { color: #ef4444; }
.quick-stat-value.orange { color: #f59e0b; }

/* ---- Filter Panel ---- */
.filter-panel {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 20px;
    margin-bottom: 20px;
}

.filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    cursor: pointer;
}

.filter-title {
    font-size: 15px;
    font-weight: 800;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-toggle {
    color: var(--text-secondary);
    font-size: 14px;
    transition: transform 0.3s;
}

.filter-toggle.collapsed {
    transform: rotate(-90deg);
}

.filter-body {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 14px;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.filter-group label {
    font-size: 11px;
    font-weight: 700;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.filter-group select,
.filter-group input[type="date"],
.filter-group input[type="text"] {
    padding: 10px 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--darker-bg);
    color: var(--text-primary);
    font-size: 13px;
    font-weight: 500;
    outline: none;
    transition: border-color 0.2s;
    width: 100%;
    box-sizing: border-box;
}

.filter-group select:focus,
.filter-group input:focus {
    border-color: var(--theme-color);
}

.filter-actions {
    display: flex;
    gap: 10px;
    align-items: flex-end;
    flex-wrap: wrap;
}

.btn {
    padding: 10px 18px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 700;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
    border: none;
    cursor: pointer;
    white-space: nowrap;
}

.btn-primary {
    background: var(--theme-color);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(var(--theme-rgb), 0.3);
}

.btn-outline {
    background: transparent;
    color: var(--text-secondary);
    border: 1px solid var(--border-color);
}

.btn-outline:hover {
    background: var(--darker-bg);
    color: var(--text-primary);
}

.btn-sm {
    padding: 7px 12px;
    font-size: 12px;
}

.btn-export {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

/* ---- Active Filter Pills ---- */
.active-filters {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 16px;
}

.filter-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    background: rgba(var(--theme-rgb), 0.1);
    border: 1px solid rgba(var(--theme-rgb), 0.2);
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    color: var(--theme-color);
}

.filter-pill .remove-filter {
    cursor: pointer;
    opacity: 0.7;
    transition: opacity 0.2s;
    font-size: 10px;
}

.filter-pill .remove-filter:hover {
    opacity: 1;
}

/* ---- Summary Bar ---- */
.summary-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 14px 20px;
    background: var(--darker-bg);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    margin-bottom: 16px;
    font-size: 13px;
    color: var(--text-secondary);
    align-items: center;
}

.summary-bar strong {
    color: var(--text-primary);
}

.summary-bar .green { color: #10b981; font-weight: 800; }
.summary-bar .red { color: #ef4444; font-weight: 800; }

/* ---- Transactions Table ---- */
.table-section {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    overflow: hidden;
}

.table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border-color);
    gap: 12px;
    flex-wrap: wrap;
}

.table-toolbar-left {
    font-size: 14px;
    font-weight: 700;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
}

.record-count {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    background: var(--darker-bg);
    padding: 4px 10px;
    border-radius: 6px;
}

.table-wrapper {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.table {
    width: 100%;
    border-collapse: collapse;
    min-width: 700px;
}

.table th {
    text-align: left;
    padding: 12px 16px;
    font-size: 11px;
    font-weight: 700;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    background: var(--darker-bg);
    white-space: nowrap;
    position: sticky;
    top: 0;
}

.table td {
    padding: 14px 16px;
    border-bottom: 1px solid var(--border-color);
    color: var(--text-primary);
    font-size: 13px;
    vertical-align: middle;
}

.table tbody tr {
    transition: background 0.15s;
}

.table tbody tr:hover {
    background: var(--darker-bg);
}

.table tbody tr:last-child td {
    border-bottom: none;
}

/* User cell */
.user-cell {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.user-cell .username {
    font-weight: 700;
    color: var(--text-primary);
    font-size: 13px;
}

.user-cell .user-id {
    font-size: 10px;
    color: var(--text-secondary);
}

/* Amount cell */
.amount-credit {
    color: #10b981;
    font-weight: 800;
}

.amount-debit {
    color: #ef4444;
    font-weight: 800;
}

/* Type badge */
.type-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    white-space: nowrap;
}

.type-badge.credit {
    background: rgba(16, 185, 129, 0.1);
    color: #10b981;
}

.type-badge.debit {
    background: rgba(239, 68, 68, 0.1);
    color: #ef4444;
}

.type-badge.referral {
    background: rgba(139, 92, 246, 0.1);
    color: #8b5cf6;
}

.type-badge.bonus {
    background: rgba(245, 158, 11, 0.1);
    color: #f59e0b;
}

/* Status badge */
.badge {
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    display: inline-block;
    white-space: nowrap;
}

.badge-completed { background: rgba(16, 185, 129, 0.12); color: #10b981; }
.badge-pending   { background: rgba(245, 158, 11, 0.12); color: #f59e0b; }
.badge-failed    { background: rgba(239, 68, 68, 0.12); color: #ef4444; }

/* Description cell */
.desc-cell {
    max-width: 220px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: var(--text-secondary);
    font-size: 12px;
}

.desc-cell:hover {
    white-space: normal;
    overflow: visible;
    word-break: break-word;
}

.ref-code {
    font-family: 'Courier New', monospace;
    font-size: 10px;
    color: var(--text-secondary);
    opacity: 0.7;
}

.time-cell {
    white-space: nowrap;
    font-size: 12px;
    color: var(--text-secondary);
}

.time-cell .date-full {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-primary);
}

.time-cell .date-ago {
    font-size: 10px;
    margin-top: 2px;
}

/* ---- Pagination ---- */
.pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-top: 1px solid var(--border-color);
    gap: 12px;
    flex-wrap: wrap;
}

.pagination-info {
    font-size: 13px;
    color: var(--text-secondary);
}

.pagination {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.pagination a,
.pagination span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 36px;
    height: 36px;
    padding: 0 10px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.2s;
    border: 1px solid var(--border-color);
    color: var(--text-primary);
    background: var(--card-bg);
}

.pagination a:hover {
    background: var(--darker-bg);
    border-color: var(--theme-color);
}

.pagination .active {
    background: var(--theme-color);
    color: white;
    border-color: var(--theme-color);
}

.pagination .disabled {
    opacity: 0.4;
    pointer-events: none;
}

/* ---- Empty State ---- */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-secondary);
}

.empty-state i {
    font-size: 56px;
    opacity: 0.15;
    margin-bottom: 16px;
    display: block;
}

.empty-state h3 {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 6px;
}

.empty-state p {
    font-size: 14px;
}

/* ============================================================================
   RESPONSIVE
   ============================================================================ */
@media (max-width: 1024px) {
    .filter-body {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 768px) {
    .transactions-container { padding: 12px; }
    .page-title { font-size: 20px; }

    .quick-stats {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
    }

    .quick-stat { padding: 12px; }
    .quick-stat-value { font-size: 20px; }
    .quick-stat-label { font-size: 10px; }

    .filter-panel { padding: 16px; }

    .filter-body {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }

    .filter-actions {
        grid-column: 1 / -1;
    }

    .summary-bar {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
        font-size: 12px;
        padding: 12px 16px;
    }

    .table-toolbar {
        flex-direction: column;
        align-items: flex-start;
        padding: 14px 16px;
    }

    .table { min-width: 600px; }
    .table th, .table td { padding: 10px 12px; font-size: 12px; }

    .pagination-wrapper {
        flex-direction: column;
        align-items: center;
        gap: 10px;
        padding: 14px 16px;
    }
}

@media (max-width: 480px) {
    .transactions-container { padding: 10px; }
    .page-title { font-size: 18px; }
    .page-subtitle { font-size: 12px; }

    .quick-stats { gap: 8px; }
    .quick-stat { padding: 10px; border-radius: 10px; }
    .quick-stat-value { font-size: 18px; }
    .quick-stat-label { font-size: 9px; }

    .filter-panel { padding: 12px; border-radius: 10px; }

    .filter-body {
        grid-template-columns: 1fr;
        gap: 10px;
    }

    .filter-group select,
    .filter-group input {
        padding: 9px 10px;
        font-size: 12px;
    }

    .btn { padding: 9px 14px; font-size: 12px; }

    .active-filters { gap: 6px; }
    .filter-pill { font-size: 11px; padding: 5px 10px; }

    .summary-bar { font-size: 11px; padding: 10px 12px; border-radius: 8px; }

    .table-section { border-radius: 10px; }
    .table { min-width: 520px; }
    .table th, .table td { padding: 8px 10px; font-size: 11px; }
    .desc-cell { max-width: 160px; }

    .pagination a, .pagination span {
        min-width: 32px;
        height: 32px;
        font-size: 12px;
        padding: 0 8px;
    }
}

@media (max-width: 360px) {
    .quick-stats { grid-template-columns: 1fr; }
    .quick-stat {
        display: flex;
        align-items: center;
        justify-content: space-between;
        text-align: left;
    }
    .quick-stat-value { font-size: 20px; order: 2; }
    .quick-stat-label { order: 1; }
}
</style>

<div class="transactions-container">

    <!-- Page Header -->
    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-exchange-alt"></i> Transactions</h1>
        <p class="page-subtitle">View and filter all platform transactions</p>
    </div>

    <!-- Quick Stats -->
    <div class="quick-stats">
        <div class="quick-stat">
            <div class="quick-stat-value"><?= number_format($quickStats['today_count']) ?></div>
            <div class="quick-stat-label">Today's Transactions</div>
        </div>
        <div class="quick-stat">
            <div class="quick-stat-value green"><?= $defaultCurrency ?> <?= number_format($quickStats['today_credits'], 2) ?></div>
            <div class="quick-stat-label">Credits Today</div>
        </div>
        <div class="quick-stat">
            <div class="quick-stat-value red"><?= $defaultCurrency ?> <?= number_format($quickStats['today_debits'], 2) ?></div>
            <div class="quick-stat-label">Debits Today</div>
        </div>
        <div class="quick-stat">
            <div class="quick-stat-value orange"><?= number_format($quickStats['pending_count']) ?></div>
            <div class="quick-stat-label">Pending</div>
        </div>
    </div>

    <!-- Filter Panel -->
    <div class="filter-panel">
        <div class="filter-header" onclick="toggleFilters()">
            <div class="filter-title"><i class="fas fa-filter"></i> Filters</div>
            <i class="fas fa-chevron-down filter-toggle" id="filterToggle"></i>
        </div>
        <form method="GET" action="transactions.php" id="filterForm">
            <div class="filter-body" id="filterBody">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" name="search" value="<?= htmlspecialchars($searchQuery) ?>" placeholder="Username, description, ref...">
                </div>
                <div class="filter-group">
                    <label>Category</label>
                    <select name="category">
                        <option value="all" <?= $filterCategory === 'all' ? 'selected' : '' ?>>All Categories</option>
                        <option value="credit" <?= $filterCategory === 'credit' ? 'selected' : '' ?>>💰 Credits</option>
                        <option value="debit" <?= $filterCategory === 'debit' ? 'selected' : '' ?>>📤 Debits</option>
                        <option value="referral" <?= $filterCategory === 'referral' ? 'selected' : '' ?>>👥 Referral Bonuses</option>
                        <option value="task" <?= $filterCategory === 'task' ? 'selected' : '' ?>>📋 Task Earnings</option>
                        <option value="bonus" <?= $filterCategory === 'bonus' ? 'selected' : '' ?>>🎁 Bonuses</option>
                        <option value="withdrawal" <?= $filterCategory === 'withdrawal' ? 'selected' : '' ?>>💸 Withdrawals</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Specific Type</label>
                    <select name="type">
                        <option value="all">All Types</option>
                        <?php foreach ($allTypes as $t): ?>
                            <option value="<?= htmlspecialchars($t) ?>" <?= $filterType === $t ? 'selected' : '' ?>>
                                <?= htmlspecialchars(str_replace('_', ' ', ucwords($t, '_'))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="all" <?= $filterStatus === 'all' ? 'selected' : '' ?>>All Statuses</option>
                        <option value="completed" <?= $filterStatus === 'completed' ? 'selected' : '' ?>>✅ Completed</option>
                        <option value="pending" <?= $filterStatus === 'pending' ? 'selected' : '' ?>>⏳ Pending</option>
                        <option value="failed" <?= $filterStatus === 'failed' ? 'selected' : '' ?>>❌ Failed</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>From Date</label>
                    <input type="date" name="date_from" value="<?= htmlspecialchars($filterDateFrom) ?>">
                </div>
                <div class="filter-group">
                    <label>To Date</label>
                    <input type="date" name="date_to" value="<?= htmlspecialchars($filterDateTo) ?>">
                </div>
                <div class="filter-group">
                    <label>Sort By</label>
                    <select name="sort">
                        <option value="newest" <?= $sortBy === 'newest' ? 'selected' : '' ?>>Newest First</option>
                        <option value="oldest" <?= $sortBy === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                        <option value="amount_high" <?= $sortBy === 'amount_high' ? 'selected' : '' ?>>Amount (High → Low)</option>
                        <option value="amount_low" <?= $sortBy === 'amount_low' ? 'selected' : '' ?>>Amount (Low → High)</option>
                    </select>
                </div>
                <div class="filter-actions">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Apply</button>
                    <a href="transactions.php" class="btn btn-outline"><i class="fas fa-undo"></i> Reset</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Active Filter Pills -->
    <?php
    $hasFilters = ($filterStatus !== 'all' || $filterType !== 'all' || $filterCategory !== 'all' || $filterDateFrom !== '' || $filterDateTo !== '' || $searchQuery !== '');
    if ($hasFilters):
    ?>
    <div class="active-filters">
        <?php if ($searchQuery !== ''): ?>
            <span class="filter-pill"><i class="fas fa-search"></i> "<?= htmlspecialchars($searchQuery) ?>" <a href="<?= buildFilterUrl(['search' => '']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
        <?php if ($filterCategory !== 'all'): ?>
            <span class="filter-pill"><i class="fas fa-tag"></i> <?= ucfirst($filterCategory) ?> <a href="<?= buildFilterUrl(['category' => 'all']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
        <?php if ($filterType !== 'all'): ?>
            <span class="filter-pill"><i class="fas fa-code-branch"></i> <?= htmlspecialchars(str_replace('_', ' ', $filterType)) ?> <a href="<?= buildFilterUrl(['type' => 'all']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
        <?php if ($filterStatus !== 'all'): ?>
            <span class="filter-pill"><i class="fas fa-circle"></i> <?= ucfirst($filterStatus) ?> <a href="<?= buildFilterUrl(['status' => 'all']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
        <?php if ($filterDateFrom !== ''): ?>
            <span class="filter-pill"><i class="fas fa-calendar"></i> From: <?= $filterDateFrom ?> <a href="<?= buildFilterUrl(['date_from' => '']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
        <?php if ($filterDateTo !== ''): ?>
            <span class="filter-pill"><i class="fas fa-calendar"></i> To: <?= $filterDateTo ?> <a href="<?= buildFilterUrl(['date_to' => '']) ?>" class="remove-filter"><i class="fas fa-times"></i></a></span>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Summary Bar -->
    <div class="summary-bar">
        <div>Showing <strong><?= number_format($totalRecords) ?></strong> transactions</div>
        <div>Total Credits: <span class="green"><?= $defaultCurrency ?> <?= number_format(floatval($summary['total_credits'] ?? 0), 2) ?></span></div>
        <div>Total Debits: <span class="red"><?= $defaultCurrency ?> <?= number_format(floatval($summary['total_debits'] ?? 0), 2) ?></span></div>
        <div>Net: <strong><?= $defaultCurrency ?> <?= number_format(floatval($summary['total_credits'] ?? 0) - floatval($summary['total_debits'] ?? 0), 2) ?></strong></div>
    </div>

    <!-- Transactions Table -->
    <div class="table-section">
        <div class="table-toolbar">
            <div class="table-toolbar-left">
                <i class="fas fa-list"></i> Transaction Log
                <span class="record-count"><?= number_format($totalRecords) ?> records</span>
            </div>
        </div>

        <?php if ($transactions && $transactions->num_rows > 0): ?>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Description</th>
                            <th>Reference</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($t = $transactions->fetch_assoc()):
                            $type = $t['type'] ?? 'unknown';
                            $isDebit = (stripos($type, 'debit') !== false || stripos($type, 'withdrawal') !== false);
                            $isReferral = (stripos($type, 'referral') !== false);
                            $isBonus = (stripos($type, 'bonus') !== false && !$isReferral);

                            if ($isDebit) {
                                $badgeClass = 'debit';
                                $amountClass = 'amount-debit';
                                $prefix = '-';
                            } elseif ($isReferral) {
                                $badgeClass = 'referral';
                                $amountClass = 'amount-credit';
                                $prefix = '+';
                            } elseif ($isBonus) {
                                $badgeClass = 'bonus';
                                $amountClass = 'amount-credit';
                                $prefix = '+';
                            } else {
                                $badgeClass = 'credit';
                                $amountClass = 'amount-credit';
                                $prefix = '+';
                            }

                            $statusClass = match($t['status'] ?? 'pending') {
                                'completed' => 'badge-completed',
                                'failed'    => 'badge-failed',
                                default     => 'badge-pending',
                            };

                            $displayType = str_replace('_', ' ', ucwords($type, '_'));
                            $createdAt = $t['created_at'] ?? null;
                        ?>
                        <tr>
                            <td style="font-weight: 600; color: var(--text-secondary); font-size: 12px;">#<?= intval($t['id'] ?? 0) ?></td>
                            <td>
                                <div class="user-cell">
                                    <span class="username"><?= htmlspecialchars($t['username'] ?? 'Unknown') ?></span>
                                    <span class="user-id">ID: <?= intval($t['user_id'] ?? 0) ?></span>
                                </div>
                            </td>
                            <td><span class="type-badge <?= $badgeClass ?>"><?= htmlspecialchars($displayType) ?></span></td>
                            <td class="<?= $amountClass ?>"><?= $prefix ?><?= $defaultCurrency ?> <?= number_format(floatval($t['amount'] ?? 0), 2) ?></td>
                            <td><div class="desc-cell" title="<?= htmlspecialchars($t['description'] ?? '') ?>"><?= htmlspecialchars($t['description'] ?? '-') ?></div></td>
                            <td><span class="ref-code"><?= htmlspecialchars($t['reference'] ?? '-') ?></span></td>
                            <td><span class="badge <?= $statusClass ?>"><?= ucfirst($t['status'] ?? 'pending') ?></span></td>
                            <td>
                                <div class="time-cell">
                                    <div class="date-full"><?= $createdAt ? date('M d, Y', strtotime($createdAt)) : 'N/A' ?></div>
                                    <div class="date-ago"><?= $createdAt ? date('h:i A', strtotime($createdAt)) : '' ?></div>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="pagination-wrapper">
                <div class="pagination-info">
                    Page <?= $page ?> of <?= $totalPages ?> &middot; <?= number_format($totalRecords) ?> total
                </div>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="<?= buildFilterUrl(['page' => 1]) ?>" title="First"><i class="fas fa-angle-double-left"></i></a>
                        <a href="<?= buildFilterUrl(['page' => $page - 1]) ?>"><i class="fas fa-angle-left"></i></a>
                    <?php else: ?>
                        <span class="disabled"><i class="fas fa-angle-double-left"></i></span>
                        <span class="disabled"><i class="fas fa-angle-left"></i></span>
                    <?php endif; ?>

                    <?php
                    $start = max(1, $page - 2);
                    $end   = min($totalPages, $page + 2);
                    if ($start > 1): ?>
                        <a href="<?= buildFilterUrl(['page' => 1]) ?>">1</a>
                        <?php if ($start > 2): ?><span class="disabled">...</span><?php endif; ?>
                    <?php endif;

                    for ($i = $start; $i <= $end; $i++): ?>
                        <?php if ($i === $page): ?>
                            <span class="active"><?= $i ?></span>
                        <?php else: ?>
                            <a href="<?= buildFilterUrl(['page' => $i]) ?>"><?= $i ?></a>
                        <?php endif; ?>
                    <?php endfor;

                    if ($end < $totalPages): ?>
                        <?php if ($end < $totalPages - 1): ?><span class="disabled">...</span><?php endif; ?>
                        <a href="<?= buildFilterUrl(['page' => $totalPages]) ?>"><?= $totalPages ?></a>
                    <?php endif; ?>

                    <?php if ($page < $totalPages): ?>
                        <a href="<?= buildFilterUrl(['page' => $page + 1]) ?>"><i class="fas fa-angle-right"></i></a>
                        <a href="<?= buildFilterUrl(['page' => $totalPages]) ?>" title="Last"><i class="fas fa-angle-double-right"></i></a>
                    <?php else: ?>
                        <span class="disabled"><i class="fas fa-angle-right"></i></span>
                        <span class="disabled"><i class="fas fa-angle-double-right"></i></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-exchange-alt"></i>
                <h3>No Transactions Found</h3>
                <p>
                    <?php if ($hasFilters): ?>
                        Try adjusting your filters or <a href="transactions.php" style="color: var(--theme-color); font-weight: 600;">clear all filters</a>
                    <?php else: ?>
                        Transactions will appear here once users start earning.
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
// Toggle filter panel
function toggleFilters() {
    const body = document.getElementById('filterBody');
    const toggle = document.getElementById('filterToggle');
    body.style.display = body.style.display === 'none' ? 'grid' : 'none';
    toggle.classList.toggle('collapsed');
}

// Auto-submit on select change (optional UX enhancement)
document.querySelectorAll('.filter-body select').forEach(sel => {
    sel.addEventListener('change', function() {
        // Small delay so the user can see their selection
        clearTimeout(this._debounce);
        this._debounce = setTimeout(() => {
            // Only auto-submit for category/status changes, not type
            if (this.name === 'category' || this.name === 'status') {
                document.getElementById('filterForm').submit();
            }
        }, 300);
    });
});

// Quick date presets
function setDateRange(days) {
    const to = new Date();
    const from = new Date();
    from.setDate(from.getDate() - days);
    
    document.querySelector('input[name="date_from"]').value = from.toISOString().split('T')[0];
    document.querySelector('input[name="date_to"]').value = to.toISOString().split('T')[0];
    document.getElementById('filterForm').submit();
}
</script>

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