<?php
require_once '../includes/db.php';
require_once '../includes/auth.php';

requireLogin();

// Function to format age in human-readable format
function formatAge($seconds) {
    if ($seconds < 60) {
        return $seconds . 's ago';
    } elseif ($seconds < 3600) {
        $minutes = floor($seconds / 60);
        return $minutes . 'm ago';
    } elseif ($seconds < 86400) {
        $hours = floor($seconds / 3600);
        return $hours . 'h ago';
    } else {
        $days = floor($seconds / 86400);
        return $days . 'd ago';
    }
}

$transactions = $pdo->query("SELECT * FROM transactions ORDER BY created_at DESC LIMIT 100")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transactions - Shinda Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">Shinda Admin</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="dashboard.php">Dashboard</a>
                <a class="nav-link" href="logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">Dashboard</a>
                        </li>
                        <?php if (hasPermission('admin')): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="users.php">Users</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="services.php">Services</a>
                        </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a class="nav-link active" href="transactions.php">Transactions</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="results.php">Game Results</a>
                        </li>
                        <?php if (hasPermission('super_admin')): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="settings.php">Settings</a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </div>
            </nav>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Transactions</h1>
                    <div>
                        <button class="btn btn-primary" onclick="exportCSV()">Export CSV</button>
                        <small class="text-muted ms-3">Auto-refreshing every 3 seconds...</small>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped" id="transactionsTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Phone</th>
                                <th>Amount</th>
                                <th>Receipt</th>
                                <th>Status</th>
                                <th>Age</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody id="transactionsBody">
                            <?php foreach ($transactions as $transaction): ?>
                                <tr data-tx-id="<?php echo $transaction['id']; ?>" data-created="<?php echo $transaction['created_at']; ?>">
                                    <td><?php echo $transaction['id']; ?></td>
                                    <td><?php echo htmlspecialchars($transaction['phone']); ?></td>
                                    <td>Ksh <?php echo number_format($transaction['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($transaction['receipt'] ?? 'Pending'); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $transaction['status'] === 'completed' ? 'success' : ($transaction['status'] === 'pending' ? 'warning' : 'danger'); ?>" data-status="<?php echo $transaction['status']; ?>">
                                            <?php 
                                            $statusIcon = '';
                                            if ($transaction['status'] === 'completed') {
                                                $statusIcon = '✅';
                                            } elseif ($transaction['status'] === 'failed') {
                                                $statusIcon = '❌';
                                            } else {
                                                $statusIcon = '⏳';
                                            }
                                            echo $statusIcon . ' ' . ucfirst($transaction['status']);
                                            ?>
                                        </span>
                                    </td>
                                    <td class="age-cell" data-timestamp="<?php echo strtotime($transaction['created_at']); ?>">
                                        <small class="text-muted"><?php 
                                            $age = time() - strtotime($transaction['created_at']);
                                            echo formatAge($age);
                                        ?></small>
                                    </td>
                                    <td><small><?php echo $transaction['created_at']; ?></small></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    </div>

    <script>
        function formatAge(seconds) {
            if (seconds < 60) {
                return seconds + 's ago';
            } else if (seconds < 3600) {
                const minutes = Math.floor(seconds / 60);
                return minutes + 'm ago';
            } else if (seconds < 86400) {
                const hours = Math.floor(seconds / 3600);
                return hours + 'h ago';
            } else {
                const days = Math.floor(seconds / 86400);
                return days + 'd ago';
            }
        }

        function updateAges() {
            const ageCells = document.querySelectorAll('.age-cell');
            ageCells.forEach(cell => {
                const timestamp = parseInt(cell.dataset.timestamp);
                const age = Math.floor(Date.now() / 1000) - timestamp;
                cell.innerHTML = '<small class="text-muted">' + formatAge(age) + '</small>';
            });
        }

        async function refreshTransactions() {
            try {
                const response = await fetch('/Shinda/api/get_recent_transactions.php');
                const data = await response.json();
                
                if (data.success && data.transactions) {
                    data.transactions.forEach(tx => {
                        const row = document.querySelector(`tr[data-tx-id="${tx.id}"]`);
                        if (row) {
                            // Update status badge
                            const statusCell = row.querySelector('[data-status]');
                            if (statusCell) {
                                const statusIcon = tx.status === 'completed' ? '✅' : (tx.status === 'failed' ? '❌' : '⏳');
                                const statusColor = tx.status === 'completed' ? 'success' : (tx.status === 'failed' ? 'danger' : 'warning');
                                statusCell.textContent = statusIcon + ' ' + tx.status.charAt(0).toUpperCase() + tx.status.slice(1);
                                statusCell.className = 'badge bg-' + statusColor;
                                statusCell.dataset.status = tx.status;
                            }
                            
                            // Update receipt if changed
                            const receiptCell = row.cells[3];
                            if (receiptCell && tx.receipt) {
                                receiptCell.textContent = tx.receipt;
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('Refresh error:', error);
            }
        }

        // Update ages every second
        setInterval(updateAges, 1000);
        
        // Refresh transaction data every 3 seconds
        setInterval(refreshTransactions, 3000);
        
        // Initial update
        updateAges();

        function exportCSV() {
            const table = document.getElementById('transactionsTable');
            let csv = [];
            for (let row of table.rows) {
                let rowData = [];
                for (let cell of row.cells) {
                    rowData.push(cell.innerText);
                }
                csv.push(rowData.join(','));
            }
            const csvContent = csv.join('\n');
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'transactions.csv';
            a.click();
            window.URL.revokeObjectURL(url);
        }
    </script>
</body>
</html>