<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

// Release session lock to allow concurrent tab loading (fast tab switching)
session_write_close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Transactions — FamGateway";
include 'includes/header.php'; 
?>
<style>
.filter-pill {
    display: inline-block;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    color: var(--color-ink-mute);
    background: transparent;
    border: 1px solid var(--color-hairline);
    text-decoration: none;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;
}
.filter-pill:hover {
    background: var(--surface-bg);
    color: var(--color-ink);
    border-color: #cbd5e1;
}
.filter-pill.active {
    background: var(--color-ink);
    color: var(--surface-page);
    border-color: var(--color-ink);
    box-shadow: 0 4px 10px rgba(15,23,42,0.15);
}

.table-responsive {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.tx-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    min-width: 800px;
}
.tx-table th {
    text-align: left;
    padding: 14px 18px;
    font-size: 12px;
    font-weight: 700;
    color: var(--color-ink-mute);
    text-transform: uppercase;
    letter-spacing: 0.8px;
    border-bottom: 2px solid var(--color-hairline);
    background: #f8fafc;
    white-space: nowrap;
}
.tx-table td {
    padding: 18px;
    font-size: 14px;
    color: var(--color-ink);
    border-bottom: 1px solid var(--color-hairline);
    vertical-align: middle;
}
.tx-table tr:hover td {
    background: #f8fafc;
}
.tx-table tr:last-child td {
    border-bottom: none;
}
.status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
}
.status-success { background: #dcfce7; color: #166534; }
.status-pending { background: #fef08a; color: #854d0e; }
.status-failed { background: #fee2e2; color: #991b1b; }
.status-expired { background: #f1f5f9; color: #475569; }

.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: var(--color-ink-mute);
}

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

.search-box {
    position: relative;
    max-width: 300px;
    flex: 1 1 200px;
}
.search-box i, .search-box svg {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--color-ink-mute);
}
.search-box input {
    width: 100%;
    padding: 8px 12px 8px 36px;
    border: 1px solid var(--color-hairline);
    border-radius: 6px;
    font-size: 14px;
    outline: none;
    transition: border-color 0.2s;
}
.search-box input:focus {
    border-color: var(--color-primary);
}

.pagination-controls {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    padding: 16px;
}
.pagination-btn {
    padding: 6px 12px;
    border: 1px solid var(--color-hairline);
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 600;
    color: var(--color-ink);
}
.pagination-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
.pagination-btn:not(:disabled):hover {
    background: var(--surface-bg);
}

.card-header-filters {
    padding: 16px;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
}
</style>
</head>
<body>
<?php include 'includes/nav.php'; ?>
    
<main class="main-content">
    <div class="wrap">

        <!-- Page Header -->
        <div class="dash-anim-right" style="margin-top: 24px; margin-bottom: 24px; display:flex; justify-content:space-between; align-items:flex-end; flex-wrap:wrap; gap:20px;">
            <div>
                <h1 style="font-size: 26px; font-weight: 800; color: var(--color-ink); letter-spacing: -0.8px;">
                    Transactions
                </h1>
                <p style="font-size: 14px; color: var(--color-ink-mute); margin-top: 6px;">View, search, and manage your payment history.</p>
            </div>
        </div>

        <div class="stat-grid dash-stagger" style="margin-bottom: 32px;">
            <div class="stat-card">
                <div class="stat-card-top">
                    <div class="stat-card-label">Success</div>
                    <div class="stat-card-icon blue"><i data-lucide="check-circle" style="width:17px;height:17px;"></i></div>
                </div>
                <div class="stat-card-value tnum" id="valSuccessCount">0</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-card-top">
                    <div class="stat-card-label">Failed</div>
                    <div class="stat-card-icon red"><i data-lucide="x-circle" style="width:17px;height:17px;"></i></div>
                </div>
                <div class="stat-card-value tnum" id="valFailedCount">0</div>
            </div>

            <div class="stat-card">
                <div class="stat-card-top">
                    <div class="stat-card-label" style="color:#16a34a;">Filtered Revenue</div>
                    <div class="stat-card-icon green"><i data-lucide="wallet" style="width:17px;height:17px;"></i></div>
                </div>
                <div class="stat-card-value tnum" style="color:#10b981;" id="valTotalRevenue">₹0.00</div>
            </div>
        </div>

        <div class="card dash-anim-up" style="padding: 0;">
            <!-- Filters & Search -->
            <div class="card-header-filters">
                <button type="button" class="filter-pill active" data-filter="all">All Time</button>
                <button type="button" class="filter-pill" data-filter="today">Today</button>
                <button type="button" class="filter-pill" data-filter="yesterday">Yesterday</button>
                <button type="button" class="filter-pill" data-filter="7days">Last 7 Days</button>
                <button type="button" class="filter-pill" data-filter="1month">1 Month</button>
                <button type="button" class="filter-pill" data-filter="6months">6 Months</button>
                <button type="button" class="filter-pill" data-filter="1year">1 Year</button>
            </div>

            <div class="toolbar">
                <div class="search-box">
                    <i data-lucide="search" style="width:16px;height:16px;"></i>
                    <input type="text" id="searchInput" placeholder="Search Order ID, UTR, Name...">
                </div>
                
                <div style="display:flex; align-items:center; gap:8px;">
                    <label style="font-size:13px; color:var(--color-ink-mute); font-weight:600;">Show:</label>
                    <select id="limitSelect" class="form-input" style="padding: 6px 10px; width:auto;">
                        <option value="10">10</option>
                        <option value="25" selected>25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                </div>
            </div>

            <!-- Transactions Table -->
            <div class="table-responsive" id="tableContainer">
                <table class="tx-table">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date & Time</th>
                            <th>UTR / TXN</th>
                            <th>Payer Info</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <tr>
                            <td colspan="6" style="text-align:center; padding: 40px;">
                                <i data-lucide="loader" style="width:24px;height:24px;animation:spin 1s linear infinite;color:var(--color-primary);"></i>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Empty State Container -->
            <div id="emptyStateContainer" style="display:none; text-align:center; padding: 60px 20px;">
                <i data-lucide="inbox" style="width:48px;height:48px;margin-bottom:12px;opacity:0.5;display:inline-block;"></i>
                <h3 style="font-size:16px;font-weight:600;color:var(--color-ink);margin-bottom:4px;">No transactions found</h3>
                <p style="font-size:13px;color:var(--color-ink-mute);">No payments match your current search and filters.</p>
            </div>

            <!-- Pagination -->
            <div class="pagination-controls" id="paginationContainer" style="justify-content: space-between; border-top: 1px solid var(--color-hairline);">
                <div style="font-size:13px; color:var(--color-ink-mute);">
                    Showing page <span id="lblCurrentPage">1</span> of <span id="lblTotalPages">1</span>
                    <span style="margin-left:8px;">(Total <span id="lblTotalRows">0</span> records)</span>
                </div>
                <div style="display:flex; gap:8px;">
                    <button class="pagination-btn" id="btnPrev" disabled><i data-lucide="chevron-left" style="width:14px;height:14px;vertical-align:bottom;"></i> Prev</button>
                    <button class="pagination-btn" id="btnNext" disabled>Next <i data-lucide="chevron-right" style="width:14px;height:14px;vertical-align:bottom;"></i></button>
                </div>
            </div>
        </div>

    </div>
</main>
</div>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    lucide.createIcons();

    // State
    let currentFilter = 'all';
    let currentSearch = '';
    let currentLimit = 25;
    let currentPage = 1;
    let totalPages = 1;

    let searchTimeout = null;

    const tableBody = document.getElementById('tableBody');
    const valSuccessCount = document.getElementById('valSuccessCount');
    const valFailedCount = document.getElementById('valFailedCount');
    const valTotalRevenue = document.getElementById('valTotalRevenue');
    const lblCurrentPage = document.getElementById('lblCurrentPage');
    const lblTotalPages = document.getElementById('lblTotalPages');
    const lblTotalRows = document.getElementById('lblTotalRows');
    const btnPrev = document.getElementById('btnPrev');
    const btnNext = document.getElementById('btnNext');

    function fetchTransactions() {
        tableBody.style.transition = 'opacity 0.2s';
        tableBody.style.opacity = '0.5';

        const params = new URLSearchParams({
            filter: currentFilter,
            search: currentSearch,
            limit: currentLimit,
            page: currentPage
        });

        fetch('api/get-transactions.php?' + params.toString())
            .then(res => res.json())
            .then(data => {
                if(data.status === 'success') {
                    tableBody.innerHTML = data.html;
                    valSuccessCount.innerText = data.successCount;
                    valFailedCount.innerText = data.failedCount;
                    valTotalRevenue.innerText = data.totalRevenue;
                    
                    totalPages = data.totalPages;
                    lblCurrentPage.innerText = data.currentPage;
                    lblTotalPages.innerText = data.totalPages;
                    lblTotalRows.innerText = data.totalRows;

                    btnPrev.disabled = (currentPage <= 1);
                    btnNext.disabled = (currentPage >= totalPages);

                    if (parseInt(data.totalRows) === 0) {
                        document.getElementById('tableContainer').style.display = 'none';
                        document.getElementById('paginationContainer').style.display = 'none';
                        document.getElementById('emptyStateContainer').style.display = 'block';
                    } else {
                        document.getElementById('tableContainer').style.display = 'block';
                        document.getElementById('paginationContainer').style.display = 'flex';
                        document.getElementById('emptyStateContainer').style.display = 'none';
                    }

                    lucide.createIcons();
                }
                tableBody.style.opacity = '1';
            })
            .catch(err => {
                document.getElementById('tableContainer').style.display = 'block';
                document.getElementById('emptyStateContainer').style.display = 'none';
                tableBody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:red; padding: 20px;">Failed to load data.</td></tr>`;
                tableBody.style.opacity = '1';
            });
    }

    // Filter Pills
    document.querySelectorAll('.filter-pill').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.filter-pill').forEach(b => b.classList.remove('active'));
            e.currentTarget.classList.add('active');
            currentFilter = e.currentTarget.getAttribute('data-filter');
            currentPage = 1; // Reset to page 1 on filter change
            fetchTransactions();
        });
    });

    // Search Input
    document.getElementById('searchInput').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentSearch = e.target.value.trim();
            currentPage = 1; // Reset to page 1 on search
            fetchTransactions();
        }, 400); // 400ms debounce
    });

    // Limit Select
    document.getElementById('limitSelect').addEventListener('change', (e) => {
        currentLimit = parseInt(e.target.value);
        currentPage = 1; // Reset to page 1 on limit change
        fetchTransactions();
    });

    // Pagination
    btnPrev.addEventListener('click', () => {
        if(currentPage > 1) {
            currentPage--;
            fetchTransactions();
        }
    });

    btnNext.addEventListener('click', () => {
        if(currentPage < totalPages) {
            currentPage++;
            fetchTransactions();
        }
    });

    // Initial load
    fetchTransactions();
</script>
</body>
</html>
