<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>STK Transactions - Admin Panel</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- Meta Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '675576561988267');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=675576561988267&ev=PageView&noscript=1"
/></noscript>
<!-- End Meta Pixel Code -->
    <style>
        .transactions-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 1.5rem;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stats-card.success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        
        .stats-card.warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .stats-card.info {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .stats-card.danger {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
        
        .btn-primary {
            background-color: #6c04f5;
            border-color: #6c04f5;
        }
        
        .btn-primary:hover {
            background-color: #5a03d1;
            border-color: #5a03d1;
        }
        
        .search-filters {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background-color: #6c04f5;
            color: white;
            border: none;
            font-weight: 600;
        }
        
        .table td {
            vertical-align: middle;
        }
        
        .status-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        
        .status-launched {
            background-color: #28a745;
            color: white;
        }
        
        .status-failed {
            background-color: #dc3545;
            color: white;
        }
        
        .status-canceled {
            background-color: #ffc107;
            color: #212529;
        }
        
        .status-timeout {
            background-color: #17a2b8;
            color: white;
        }
        
        .status-insufficient {
            background-color: #fd7e14;
            color: white;
        }
        
        /* DataTables Custom Styling */
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_filter,
        .dataTables_wrapper .dataTables_info,
        .dataTables_wrapper .dataTables_processing,
        .dataTables_wrapper .dataTables_paginate {
            margin: 0.5rem 0;
        }
        
        .dataTables_wrapper .dataTables_length select {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 0.375rem 0.75rem;
        }
        
        .dataTables_wrapper .dataTables_filter input {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 0.375rem 0.75rem;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 0.375rem !important;
            margin: 0 0.125rem;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #6c04f5 !important;
            border-color: #6c04f5 !important;
            color: white !important;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #5a03d1 !important;
            border-color: #5a03d1 !important;
            color: white !important;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter {
                text-align: left;
                margin-bottom: 0.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="transactions-container">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">STK Transactions</h4>
                        <div class="card-tools">
                            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addTransactionModal">
                                <i class="fas fa-plus"></i> Add Transaction
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Statistics Cards -->
                        <div class="row mb-4">
                            <div class="col-lg-3 col-6">
                                <div class="small-box bg-info">
                                    <div class="inner">
                                        <h3 id="totalTransactions">0</h3>
                                        <p>Total Transactions</p>
                                    </div>
                                    <div class="icon">
                                        <i class="fas fa-chart-bar"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="small-box bg-success">
                                    <div class="inner">
                                        <h3 id="launchedTransactions">0</h3>
                                        <p>Launched</p>
                                    </div>
                                    <div class="icon">
                                        <i class="fas fa-check"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="small-box bg-warning">
                                    <div class="inner">
                                        <h3 id="failedTransactions">0</h3>
                                        <p>Failed</p>
                                    </div>
                                    <div class="icon">
                                        <i class="fas fa-times"></i>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-6">
                                <div class="small-box bg-danger">
                                    <div class="inner">
                                        <h3 id="totalAmount">KES 0</h3>
                                        <p>Total Amount</p>
                                    </div>
                                    <div class="icon">
                                        <i class="fas fa-money-bill"></i>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Filters -->
                        <div class="row mb-3">
                            <div class="col-md-3">
                                <select class="form-control" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="Launched">Launched</option>
                                    <option value="Failed">Failed</option>
                                    <option value="Canceled">Canceled</option>
                                    <option value="Timeout">Timeout</option>
                                    <option value="Insufficient-funds">Insufficient Funds</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <input type="text" class="form-control" id="ticketReferenceFilter" placeholder="Ticket Reference">
                            </div>
                            <div class="col-md-2">
                                <input type="date" class="form-control" id="startDateFilter" placeholder="Start Date">
                            </div>
                            <div class="col-md-2">
                                <input type="date" class="form-control" id="endDateFilter" placeholder="End Date">
                            </div>
                            <div class="col-md-2">
                                <button type="button" class="btn btn-secondary" onclick="loadTransactions()">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                            </div>
                        </div>

                        <!-- Transactions Table -->
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="transactionsTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Ticket Reference</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Transaction Date</th>
                                        <th>Checkout Request ID</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="transactionsTableBody">
                                    <!-- Transactions will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Transaction Modal -->
    <div class="modal fade" id="addTransactionModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add STK Transaction</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form id="addTransactionForm">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Ticket Reference Number</label>
                                    <input type="text" class="form-control" name="ticket_reference_number" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Amount</label>
                                    <input type="number" step="0.01" class="form-control" name="amount" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Transaction Type</label>
                                    <input type="text" class="form-control" name="transaction_type" value="STK" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Status</label>
                                    <select class="form-control" name="stk_status" required>
                                        <option value="Launched">Launched</option>
                                        <option value="Failed">Failed</option>
                                        <option value="Canceled">Canceled</option>
                                        <option value="Timeout">Timeout</option>
                                        <option value="Insufficient-funds">Insufficient Funds</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>STK Request (JSON)</label>
                            <textarea class="form-control" name="stk_request" rows="3"></textarea>
                        </div>
                        <div class="form-group">
                            <label>STK Response (JSON)</label>
                            <textarea class="form-control" name="stk_response" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Transaction</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Transaction Modal -->
    <div class="modal fade" id="viewTransactionModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Transaction Details</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="transactionDetails">
                    <!-- Transaction details will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

    <script>
    let currentPage = 1;
    let dataTable;

    $(document).ready(function() {
        loadStatistics();
        loadTransactions();

        // Add transaction form submission
        $('#addTransactionForm').on('submit', function(e) {
            e.preventDefault();
            addTransaction();
        });
    });

    function loadStatistics() {
        $.ajax({
            url: '/api/v1/stk-transactions/statistics',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    $('#totalTransactions').text(response.statistics.total_transactions);
                    $('#launchedTransactions').text(response.statistics.launched);
                    $('#failedTransactions').text(response.statistics.failed);
                    $('#totalAmount').text('KES ' + response.statistics.total_amount.toLocaleString());
                }
            },
            error: function(xhr) {
                console.error('Error loading statistics:', xhr);
            }
        });
    }

    function loadTransactions(page = 1) {
        const filters = {
            status: $('#statusFilter').val(),
            ticket_reference: $('#ticketReferenceFilter').val(),
            start_date: $('#startDateFilter').val(),
            end_date: $('#endDateFilter').val(),
            page: page
        };

        $.ajax({
            url: '/api/v1/stk-transactions',
            method: 'GET',
            data: filters,
            success: function(response) {
                if (response.success) {
                    displayTransactions(response.transactions.data);
                    if (dataTable) {
                        dataTable.destroy();
                    }
                    initializeDataTable();
                }
            },
            error: function(xhr) {
                console.error('Error loading transactions:', xhr);
            }
        });
    }

    function displayTransactions(transactions) {
        const tbody = $('#transactionsTableBody');
        tbody.empty();

        transactions.forEach(function(transaction) {
            const statusClass = getStatusClass(transaction.stk_status);
            const row = `
                <tr>
                    <td>${transaction.id}</td>
                    <td>${transaction.ticket_reference_number}</td>
                    <td>KES ${parseFloat(transaction.amount).toLocaleString()}</td>
                    <td><span class="badge badge-${statusClass}">${transaction.stk_status}</span></td>
                    <td>${formatDate(transaction.transaction_date)}</td>
                    <td>${transaction.checkout_request_id || 'N/A'}</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewTransaction(${transaction.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="updateStatus(${transaction.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    function initializeDataTable() {
        dataTable = $('#transactionsTable').DataTable({
            responsive: true,
            pageLength: 25,
            lengthMenu: [[25, 50, 100, 200], [25, 50, 100, 200]],
            order: [[0, 'desc']], // Sort by ID descending
            language: {
                search: "Search transactions:",
                lengthMenu: "Show _MENU_ transactions per page",
                info: "Showing _START_ to _END_ of _TOTAL_ transactions",
                infoEmpty: "Showing 0 to 0 of 0 transactions",
                infoFiltered: "(filtered from _MAX_ total transactions)",
                paginate: {
                    first: "First",
                    last: "Last",
                    next: "Next",
                    previous: "Previous"
                }
            },
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                 '<"row"<"col-sm-12"tr>>' +
                 '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
            columnDefs: [
                {
                    targets: [0], // ID column
                    width: '60px',
                    className: 'text-center'
                },
                {
                    targets: [1], // Ticket Reference column
                    width: '150px'
                },
                {
                    targets: [2], // Amount column
                    width: '120px',
                    className: 'text-end'
                },
                {
                    targets: [3], // Status column
                    width: '100px',
                    className: 'text-center'
                },
                {
                    targets: [4], // Transaction Date column
                    width: '150px',
                    className: 'text-center'
                },
                {
                    targets: [5], // Checkout Request ID column
                    width: '150px'
                },
                {
                    targets: [6], // Actions column
                    width: '100px',
                    className: 'text-center'
                }
            ]
        });
    }

    function addTransaction() {
        const formData = new FormData($('#addTransactionForm')[0]);

        $.ajax({
            url: '/api/v1/stk-transactions/log',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#addTransactionModal').modal('hide');
                    $('#addTransactionForm')[0].reset();
                    loadStatistics();
                    loadTransactions();
                    alert('Transaction added successfully!');
                }
            },
            error: function(xhr) {
                console.error('Error adding transaction:', xhr);
                alert('Error adding transaction. Please try again.');
            }
        });
    }

    function viewTransaction(transactionId) {
        // This would need a separate endpoint to get transaction details
        // For now, we'll show a placeholder
        $('#transactionDetails').html('<p>Transaction details will be displayed here.</p>');
        $('#viewTransactionModal').modal('show');
    }

    function updateStatus(transactionId) {
        const newStatus = prompt('Enter new status (Launched, Failed, Canceled, Timeout, Insufficient-funds):');
        if (newStatus && ['Launched', 'Failed', 'Canceled', 'Timeout', 'Insufficient-funds'].includes(newStatus)) {
            $.ajax({
                url: `/api/v1/stk-transactions/${transactionId}/status`,
                method: 'PUT',
                data: {
                    stk_status: newStatus,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        loadStatistics();
                        loadTransactions();
                        alert('Status updated successfully!');
                    }
                },
                error: function(xhr) {
                    console.error('Error updating status:', xhr);
                    alert('Error updating status. Please try again.');
                }
            });
        }
    }

    function getStatusClass(status) {
        switch(status) {
            case 'Launched': return 'success';
            case 'Failed': return 'danger';
            case 'Canceled': return 'warning';
            case 'Timeout': return 'info';
            case 'Insufficient-funds': return 'insufficient';
            default: return 'secondary';
        }
    }

    function formatDate(dateString) {
        return new Date(dateString).toLocaleString();
    }
    </script>
</body>
</html> 