<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <!-- Notification Container -->
    <div id="notification" class="position-fixed top-0 end-0 p-3" style="z-index: 1050; display: none;">
        <div class="toast align-items-center text-white" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body"></div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h5 class="card-title">Successful Transactions</h5>
                    <h2 class="mb-2"><?= number_format($stats['successful_amount'], 2) ?> UGX</h2>
                    <span class="badge bg-light text-dark"><?= $stats['successful_count'] ?> transactions</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-danger text-white">
                <div class="card-body">
                    <h5 class="card-title">Failed Transactions</h5>
                    <h2 class="mb-2"><?= number_format($stats['failed_amount'], 2) ?> UGX</h2>
                    <span class="badge bg-light text-dark"><?= $stats['failed_count'] ?> transactions</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <h5 class="card-title">Total Transactions</h5>
                    <h2 class="mb-0"><?= $stats['total_transactions'] ?></h2>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Transactions</h3>
                    <div class="card-tools">
                        <div class="input-group input-group-sm" style="width: 150px;">
                            <input type="text" id="searchInput" class="form-control float-right" placeholder="Search">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-default">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <select class="form-control" id="statusFilter">
                                <option value="all">All Status</option>
                                <option value="PENDING">Pending</option>
                                <option value="SUCCESS">Success</option>
                                <option value="FAILED">Failed</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="date" class="form-control" id="startDate" value="<?= $start_date ?? '' ?>">
                        </div>
                        <div class="col-md-3">
                            <input type="date" class="form-control" id="endDate" value="<?= $end_date ?? '' ?>">
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" id="exportBtn">
                                <i class="fas fa-file-excel"></i> Export to Excel
                            </button>
                        </div>
                    </div>
                    <table id="transactionsTable" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Transaction ID</th>
                                <th>Reference</th>
                                <th>Phone Number</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Created At</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $transaction): ?>
                                <tr>
                                    <td><?= $transaction['transaction_id'] ?></td>
                                    <td><?= $transaction['reference'] ?></td>
                                    <td><?= $transaction['msisdn'] ?></td>
                                    <td><?= number_format($transaction['amount'], 2) ?></td>
                                    <td>
                                        <?php
                                        $statusClass = '';
                                        $statusText = '';
                                        switch ($transaction['status']) {
                                            case 'SUCCESS':
                                                $statusClass = 'bg-success';
                                                $statusText = 'Success';
                                                break;
                                            case 'FAILED':
                                                $statusClass = 'bg-danger';
                                                $statusText = 'Failed';
                                                break;
                                            case 'PENDING':
                                                $statusClass = 'bg-warning';
                                                $statusText = 'Pending';
                                                break;
                                        }
                                        ?>
                                        <span class="badge rounded-pill <?= $statusClass ?> text-white px-3 py-2">
                                            <?= $statusText ?>
                                        </span>
                                    </td>
                                    <td><?= date('Y-m-d H:i:s', strtotime($transaction['created_at'])) ?></td>
                                    <td>
                                        <?php if ($transaction['status'] === 'PENDING'): ?>
                                            <button class="btn btn-sm btn-success update-status"
                                                data-id="<?= $transaction['id'] ?>"
                                                data-status="SUCCESS"
                                                data-transaction-id="<?= $transaction['transaction_id'] ?>"
                                                data-reference="<?= $transaction['reference'] ?>">
                                                <i class="fas fa-check"></i> Success
                                            </button>
                                            <button class="btn btn-sm btn-danger update-status"
                                                data-id="<?= $transaction['id'] ?>"
                                                data-status="FAILED"
                                                data-transaction-id="<?= $transaction['transaction_id'] ?>"
                                                data-reference="<?= $transaction['reference'] ?>">
                                                <i class="fas fa-times"></i> Failed
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
    $(document).ready(function() {
        let debounceTimer;

        // Show notification
        function showNotification(message, type = 'success') {
            const notification = $('#notification');
            const toast = notification.find('.toast');

            toast.removeClass('bg-success bg-danger bg-warning')
                .addClass(`bg-${type}`);

            toast.find('.toast-body').text(message);
            notification.show();

            const bsToast = new bootstrap.Toast(toast[0]);
            bsToast.show();
        }

        // Filter transactions
        function filterTransactions() {
            const status = $('#statusFilter').val();
            const search = $('#searchInput').val();
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();

            $.get('<?= base_url('transactions/filter') ?>', {
                status: status,
                search: search,
                start_date: startDate,
                end_date: endDate
            }, function(response) {
                let html = '';
                response.forEach(function(transaction) {
                    let statusClass = '';
                    let statusText = '';

                    switch (transaction.status) {
                        case 'SUCCESS':
                            statusClass = 'bg-success';
                            statusText = 'Success';
                            break;
                        case 'FAILED':
                            statusClass = 'bg-danger';
                            statusText = 'Failed';
                            break;
                        case 'PENDING':
                            statusClass = 'bg-warning';
                            statusText = 'Pending';
                            break;
                    }

                    html += `
                    <tr>
                        <td>${transaction.transaction_id}</td>
                        <td>${transaction.reference}</td>
                        <td>${transaction.msisdn}</td>
                        <td>${parseFloat(transaction.amount).toFixed(2)}</td>
                        <td>
                            <span class="badge rounded-pill ${statusClass} text-white px-3 py-2">
                                ${statusText}
                            </span>
                        </td>
                        <td>${new Date(transaction.created_at).toLocaleString()}</td>
                        <td>
                            ${transaction.status === 'PENDING' ? `
                                <button class="btn btn-sm btn-success update-status" 
                                        data-id="${transaction.id}" 
                                        data-status="SUCCESS"
                                        data-transaction-id="${transaction.transaction_id}"
                                        data-reference="${transaction.reference}">
                                    <i class="fas fa-check"></i> Success
                                </button>
                                <button class="btn btn-sm btn-danger update-status" 
                                        data-id="${transaction.id}" 
                                        data-status="FAILED"
                                        data-transaction-id="${transaction.transaction_id}"
                                        data-reference="${transaction.reference}">
                                    <i class="fas fa-times"></i> Failed
                                </button>
                            ` : ''}
                        </td>
                    </tr>
                `;
                });

                $('#transactionsTable tbody').html(html);
            });
        }

        // Event listeners
        $('#statusFilter').on('change', filterTransactions);
        $('#startDate, #endDate').on('change', filterTransactions);

        $('#searchInput').on('input', function() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(filterTransactions, 500);
        });

        // Export to Excel
        $('#exportBtn').on('click', function() {
            const status = $('#statusFilter').val();
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();

            let url = '<?= base_url('transactions/export') ?>?';
            if (status && status !== 'all') {
                url += `status=${status}&`;
            }
            if (startDate) {
                url += `start_date=${startDate}&`;
            }
            if (endDate) {
                url += `end_date=${endDate}`;
            }

            window.location.href = url;
        });

        // Update status
        $(document).on('click', '.update-status', function() {
            const button = $(this);
            const transactionId = button.data('transaction-id');
            const status = button.data('status');

            // Show loading state
            button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');

            $.ajax({
                url: `<?= base_url('transactions/update-status/') ?>${transactionId}`,
                type: 'POST',
                dataType: 'json',
                data: {
                    status: status
                },
                success: function(response) {
                    showNotification(`Status updated to ${status}`, 'success');
                    // Refresh the table
                    filterTransactions();
                },
                error: function(xhr) {
                    const errorMessage = xhr.responseJSON?.message || 'Failed to update status';
                    showNotification(errorMessage, 'danger');
                    // Reset button state
                    button.prop('disabled', false).html(
                        status === 'SUCCESS' ? '<i class="fas fa-check"></i> Success' : '<i class="fas fa-times"></i> Failed'
                    );
                }
            });
        });
    });
</script>
<?= $this->endSection() ?>