<?php $current_page = 'transactions'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Original Transactions - Admin App</title>
    <link rel="icon" href="/favicon.svg" type="image/svg+xml">
    <link rel="icon" href="/favicon.ico" sizes="any">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <?= view('admin/partials/admin_styles') ?>
    <style>
        .page-header { margin-bottom: 1.5rem; }
        .page-title { font-size: 1.5rem; color: #1e293b; font-weight: 700; display: flex; align-items: center; gap: 0.5rem; }

        .transactions-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden;
            border: 1px solid rgba(0,0,0,0.04);
        }

        .table-container {
            overflow-x: auto;
        }

        .transactions-table {
            width: 100%;
            border-collapse: collapse;
        }

        .transactions-table th {
            background: #f8f9fa;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e9ecef;
        }

        .transactions-table td {
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            vertical-align: middle;
        }

        .transactions-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-successful {
            background: #d1fae5;
            color: #065f46;
        }

        .status-failed {
            background: #fee2e2;
            color: #991b1b;
        }

        .status-pending {
            background: #fef3c7;
            color: #92400e;
        }

        .amount {
            font-weight: 700;
            color: #10b981;
        }

        .transaction-id {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            color: #666;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #666;
        }

        .empty-state i {
            font-size: 3rem;
            color: #ddd;
            margin-bottom: 1rem;
        }

        .stats-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-item {
            background: white;
            padding: 2rem;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            text-align: center;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border: 1px solid rgba(0,0,0,0.04);
        }

        .stat-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 28px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #718096;
            font-size: 0.85rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .stat-amount { font-size: 0.85rem; font-weight: 600; margin-top: 0.25rem; }
        .stat-item.success .stat-amount { color: #059669; }
        .stat-item.failed .stat-amount { color: #dc2626; }
        .stat-item.pending .stat-amount { color: #d97706; }
        .report-section { margin-bottom: 1.5rem; }
        .report-heading { font-size: 1rem; font-weight: 700; color: #1e293b; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem; }
        .report-heading i { color: #6366f1; }

        .actions-cell {
            text-align: center;
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            justify-content: center;
        }

        .btn-success, .btn-failed {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.8rem;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
        }

        .btn-success:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }

        .btn-failed {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2);
        }

        .btn-failed:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }

        .no-actions {
            color: #999;
            font-size: 0.8rem;
            font-style: italic;
        }

        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .filter-section {
            padding: 2rem;
            border-bottom: 1px solid #e9ecef;
            background: #f8f9fc;
        }

        .filter-controls {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr 1fr auto;
            gap: 1rem;
            align-items: end;
        }

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

        .filter-input, .filter-select {
            padding: 0.85rem;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 0.9rem;
            background: white;
            transition: all 0.3s ease;
        }

        .filter-input:focus, .filter-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .export-btn {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            border: none;
            padding: 0.85rem 1.5rem;
            border-radius: 10px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(16, 185, 129, 0.2);
        }

        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }

        .bulk-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }

        .btn-danger, .btn-warning {
            padding: 0.85rem 1.5rem;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.3s ease;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            box-shadow: 0 2px 10px rgba(239, 68, 68, 0.2);
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            box-shadow: 0 2px 10px rgba(245, 158, 11, 0.2);
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
        }

        @media (max-width: 768px) {
            .page-header { flex-direction: column; align-items: flex-start; }
            .filter-controls { grid-template-columns: 1fr; }
            .bulk-actions { flex-direction: column; }
            .transactions-table th, .transactions-table td { padding: 0.5rem; font-size: 0.9rem; }
        }
    </style>
</head>
<body>
<?= view('admin/partials/header_sidebar', ['current_page' => $current_page]) ?>

    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-credit-card"></i> Original Transactions</h1>
    </div>

    <div class="report-section">
        <h3 class="report-heading"><i class="fas fa-chart-pie"></i> Financial Report</h3>
        <div class="stats-summary">
            <div class="stat-item">
                <div class="stat-number"><?= number_format($stat_total ?? 0) ?></div>
                <div class="stat-label">Total</div>
            </div>
            <div class="stat-item success">
                <div class="stat-number"><?= number_format($stat_success_count ?? 0) ?></div>
                <div class="stat-label">Successful</div>
                <div class="stat-amount"><?= number_format($stat_success_amount ?? 0, 0) ?> UGX</div>
            </div>
            <div class="stat-item failed">
                <div class="stat-number"><?= number_format($stat_failed_count ?? 0) ?></div>
                <div class="stat-label">Failed</div>
                <div class="stat-amount"><?= number_format($stat_failed_amount ?? 0, 0) ?> UGX</div>
            </div>
            <div class="stat-item pending">
                <div class="stat-number"><?= number_format($stat_pending_count ?? 0) ?></div>
                <div class="stat-label">Pending</div>
                <div class="stat-amount"><?= number_format($stat_pending_amount ?? 0, 0) ?> UGX</div>
            </div>
            <div class="stat-item total">
                <div class="stat-number"><?= number_format(($stat_success_amount ?? 0) + ($stat_failed_amount ?? 0) + ($stat_pending_amount ?? 0), 0) ?></div>
                <div class="stat-label">Total UGX</div>
            </div>
        </div>
    </div>

        <div class="transactions-card">
            <div class="filter-section">
                <div class="filter-controls">
                    <div class="filter-group">
                        <input type="text" id="searchInput" class="filter-input" placeholder="Search by phone number or transaction ID..." value="<?= $search ?? '' ?>">
                    </div>
                    <div class="filter-group">
                        <select id="statusFilter" class="filter-select">
                            <option value="all" <?= ($status ?? '') === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="PENDING" <?= ($status ?? '') === 'PENDING' ? 'selected' : '' ?>>Pending</option>
                            <option value="SUCCESS" <?= ($status ?? '') === 'SUCCESS' ? 'selected' : '' ?>>Success</option>
                            <option value="FAILED" <?= ($status ?? '') === 'FAILED' ? 'selected' : '' ?>>Failed</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <input type="date" id="startDate" class="filter-input" value="<?= $start_date ?? '' ?>">
                    </div>
                    <div class="filter-group">
                        <input type="date" id="endDate" class="filter-input" value="<?= $end_date ?? '' ?>">
                    </div>
                    <div class="filter-group">
                        <button id="exportBtn" class="export-btn">
                            <i class="fas fa-file-excel"></i> Export
                        </button>
                    </div>
                </div>
                <div class="bulk-actions">
                    <button id="deleteFailedBtn" class="btn-danger">
                        <i class="fas fa-trash"></i> Delete All Failed
                    </button>
                    <button id="markPendingFailedBtn" class="btn-warning">
                        <i class="fas fa-exclamation-triangle"></i> Mark All Pending as Failed
                    </button>
                </div>
            </div>

            <?php if(empty($transactions)): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>No Transactions Found</h3>
                    <p>There are no transactions to display at the moment.</p>
                </div>
            <?php else: ?>
                <div class="table-container">
                    <table class="transactions-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>MSISDN</th>
                                <th>Amount</th>
                                <th>Transaction ID</th>
                                <th>Status</th>
                                <th>Created At</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($transactions as $t): ?>
                            <tr>
                                <td><?= $t['id'] ?></td>
                                <td><?= $t['msisdn'] ?></td>
                                <td class="amount">$<?= number_format($t['amount'], 2) ?></td>
                                <td class="transaction-id"><?= $t['transaction_id'] ?></td>
                                <td>
                                    <span class="status-badge status-<?= strtolower($t['status']) ?>">
                                        <?= $t['status'] ?>
                                    </span>
                                </td>
                                <td><?= date('M j, Y g:i A', strtotime($t['created_at'])) ?></td>
                                <td class="actions-cell">
                                    <?php if($t['status'] === 'PENDING'): ?>
                                        <div class="action-buttons">
                                            <button class="btn-success" onclick="updateStatus('<?= $t['transaction_id'] ?>', 'SUCCESS')">
                                                <i class="fas fa-check"></i> Success
                                            </button>
                                            <button class="btn-failed" onclick="updateStatus('<?= $t['transaction_id'] ?>', 'FAILED')">
                                                <i class="fas fa-times"></i> Failed
                                            </button>
                                        </div>
                                    <?php else: ?>
                                        <span class="no-actions">No actions available</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        let debounceTimer;

        // Filter transactions
        function filterTransactions() {
            const status = document.getElementById('statusFilter').value;
            const search = document.getElementById('searchInput').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // Build query parameters
            const params = new URLSearchParams();
            if (status && status !== 'all') params.append('status', status);
            if (search) params.append('search', search);
            if (startDate) params.append('start_date', startDate);
            if (endDate) params.append('end_date', endDate);

            // Update URL without reloading
            const newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
            window.history.pushState({}, '', newUrl);

            // Make AJAX request
            fetch('<?= site_url('admin/transactions/filter') ?>?' + params.toString())
                .then(response => response.json())
                .then(data => {
                    updateTable(data);
                    updateStats(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error filtering transactions: ' + error.message);
                });
        }

        // Update table with filtered data
        function updateTable(transactions) {
            const tbody = document.querySelector('.transactions-table tbody');
            
            if (transactions.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="empty-state">
                            <i class="fas fa-inbox"></i>
                            <h3>No Transactions Found</h3>
                            <p>No transactions match your current filters.</p>
                        </td>
                    </tr>
                `;
                return;
            }

            let html = '';
            transactions.forEach(transaction => {
                const statusClass = `status-${transaction.status.toLowerCase()}`;
                const formattedDate = new Date(transaction.created_at).toLocaleString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true
                });

                const actionButtons = transaction.status === 'PENDING' ? `
                    <div class="action-buttons">
                        <button class="btn-success" onclick="updateStatus('${transaction.transaction_id}', 'SUCCESS')">
                            <i class="fas fa-check"></i> Success
                        </button>
                        <button class="btn-failed" onclick="updateStatus('${transaction.transaction_id}', 'FAILED')">
                            <i class="fas fa-times"></i> Failed
                        </button>
                    </div>
                ` : '<span class="no-actions">No actions available</span>';

                html += `
                    <tr>
                        <td>${transaction.id}</td>
                        <td>${transaction.msisdn}</td>
                        <td class="amount">$${parseFloat(transaction.amount).toFixed(2)}</td>
                        <td class="transaction-id">${transaction.transaction_id}</td>
                        <td>
                            <span class="status-badge ${statusClass}">
                                ${transaction.status}
                            </span>
                        </td>
                        <td>${formattedDate}</td>
                        <td class="actions-cell">
                            ${actionButtons}
                        </td>
                    </tr>
                `;
            });

            tbody.innerHTML = html;
        }

        // Update statistics based on filtered data
        function updateStats(transactions) {
            let successfulCount = 0;
            let failedCount = 0;
            let pendingCount = 0;
            let successfulAmount = 0;
            let failedAmount = 0;
            let pendingAmount = 0;

            transactions.forEach(transaction => {
                const amount = parseFloat(transaction.amount);
                switch(transaction.status.toUpperCase()) {
                    case 'SUCCESS':
                        successfulCount++;
                        successfulAmount += amount;
                        break;
                    case 'FAILED':
                        failedCount++;
                        failedAmount += amount;
                        break;
                    case 'PENDING':
                        pendingCount++;
                        pendingAmount += amount;
                        break;
                }
            });

            const totalAmount = successfulAmount + failedAmount + pendingAmount;

            // Update stat numbers
            document.querySelectorAll('.stat-number')[0].textContent = transactions.length.toLocaleString();
            document.querySelectorAll('.stat-number')[1].textContent = successfulCount.toLocaleString();
            document.querySelectorAll('.stat-number')[2].textContent = failedCount.toLocaleString();
            document.querySelectorAll('.stat-number')[3].textContent = pendingCount.toLocaleString();
            document.querySelectorAll('.stat-number')[4].textContent = totalAmount.toLocaleString() + ' UGX';
        }

        // Export functionality
        function exportTransactions() {
            const status = document.getElementById('statusFilter').value;
            const search = document.getElementById('searchInput').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            let url = '<?= site_url('admin/transactions/export') ?>?';
            const params = new URLSearchParams();
            
            if (status && status !== 'all') params.append('status', status);
            if (search) params.append('search', search);
            if (startDate) params.append('start_date', startDate);
            if (endDate) params.append('end_date', endDate);

            url += params.toString();
            window.location.href = url;
        }

        // Event listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Search input with debouncing
            document.getElementById('searchInput').addEventListener('input', function() {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(filterTransactions, 500);
            });

            // Status filter
            document.getElementById('statusFilter').addEventListener('change', filterTransactions);

            // Date filters
            document.getElementById('startDate').addEventListener('change', filterTransactions);
            document.getElementById('endDate').addEventListener('change', filterTransactions);

            // Export button
            document.getElementById('exportBtn').addEventListener('click', exportTransactions);

            // Bulk action buttons
            document.getElementById('deleteFailedBtn').addEventListener('click', deleteFailedTransactions);
            document.getElementById('markPendingFailedBtn').addEventListener('click', markPendingAsFailed);
        });

        function updateStatus(transactionId, status) {
            if (!confirm(`Are you sure you want to mark this transaction as ${status}?`)) {
                return;
            }

            // Add loading state
            const button = event.target.closest('button');
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            button.classList.add('loading');

            // Make AJAX request
            fetch('<?= site_url('admin/transactions/update-status/') ?>' + transactionId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'status=' + status
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Reload the page immediately to reflect changes
                location.reload();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating transaction status: ' + error.message);
                // Restore button state
                button.innerHTML = originalText;
                button.classList.remove('loading');
            });
        }

        // Delete all failed transactions
        function deleteFailedTransactions() {
            if (!confirm('Are you sure you want to delete ALL failed transactions? This action cannot be undone.')) {
                return;
            }

            const button = document.getElementById('deleteFailedBtn');
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';
            button.disabled = true;

            fetch('<?= site_url('admin/transactions/delete-failed') ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error deleting failed transactions: ' + error.message);
            })
            .finally(() => {
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }

        // Mark all pending transactions as failed
        function markPendingAsFailed() {
            if (!confirm('Are you sure you want to mark ALL pending transactions as failed? This action cannot be undone.')) {
                return;
            }

            const button = document.getElementById('markPendingFailedBtn');
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            button.disabled = true;

            fetch('<?= site_url('admin/transactions/mark-pending-failed') ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating pending transactions: ' + error.message);
            })
            .finally(() => {
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }
    </script>
<?= view('admin/partials/footer') ?>
</body>
</html>
