<?php
require_once '../config.php';
require_once '../config_api.php';

require_once '../app/classes/ExternalAPIService.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check admin authentication
$adminAuth->requireAuth('admin_login.php');

// Get page and limit parameters
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = isset($_GET['limit']) ? max(1, min(100, intval($_GET['limit']))) : 20;

// Initialize MTN API service
$mtnApiService = new ExternalAPIService('mtn');

// Fetch transactions from MTN API
$transactionsResponse = $mtnApiService->getTransactions($page, $limit);

// Fetch data packages from MTN API
$packagesResponse = $mtnApiService->getDataPackages('YELLO');

$transactions = [];
$pagination = [];
$packages = [];
$error = '';

if ($transactionsResponse['success']) {
    $transactions = $transactionsResponse['data']['transactions'] ?? [];
    $pagination = $transactionsResponse['data']['pagination'] ?? [];
} else {
    $error = $transactionsResponse['error'] ?? 'Failed to fetch transactions';
}

if ($packagesResponse['success']) {
    $packages = $packagesResponse['data'] ?? [];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📱 MTN API Transactions | D-Bundles Stores Admin</title>
    
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Admin Dark Theme CSS -->
    <link rel="stylesheet" href="assets/admin-dark-theme.css">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.tailwindcss.min.css">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#8B5CF6',
                        danger: '#EF4444',
                        success: '#10B981',
                        warning: '#F59E0B'
                    },
                    fontFamily: {
                        'inter': ['Inter', 'sans-serif']
                    }
                }
            }
        }
    </script>
    
    <style>
        body { font-family: 'Inter', sans-serif; }
        .card-shadow { box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
    </style>
</head>

<body class="bg-gradient-to-br from-blue-50 to-purple-50 min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between h-16">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-gradient-to-r from-yellow-500 to-red-600 rounded-xl flex items-center justify-center">
                        <i class="fas fa-mobile-alt text-white text-xl"></i>
                    </div>
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">MTN API Transactions</h1>
                        <p class="text-xs text-gray-600">Localhost API Integration</p>
                    </div>
                </div>
                
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container mx-auto px-4 py-8">
        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Transactions</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $pagination['totalItems'] ?? 0 ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-list text-blue-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Current Page</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $pagination['currentPage'] ?? 1 ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-file-alt text-green-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Pages</p>
                        <p class="text-2xl font-bold text-gray-900"><?= $pagination['totalPages'] ?? 1 ?></p>
                    </div>
                    <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-layer-group text-purple-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-2xl p-6 card-shadow">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Available Packages</p>
                        <p class="text-2xl font-bold text-gray-900"><?= count($packages) ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center">
                        <i class="fas fa-box text-yellow-600 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Error Message -->
        <?php if (!empty($error)): ?>
        <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl mb-6 flex items-center">
            <i class="fas fa-exclamation-circle mr-3"></i>
            <span><?= htmlspecialchars($error) ?></span>
        </div>
        <?php endif; ?>

        <!-- Data Packages Section -->
        <div class="bg-white rounded-2xl p-6 card-shadow mb-8">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-box mr-2 text-yellow-600"></i>Available MTN Data Packages
                </h2>
                <button onclick="refreshPackages()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-xl text-sm transition-all">
                    <i class="fas fa-sync-alt mr-2"></i>Refresh
                </button>
            </div>
            
            <?php if (!empty($packages)): ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($packages as $package): ?>
                <div class="border border-gray-200 rounded-xl p-4 hover:shadow-md transition-all">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-lg font-bold text-gray-800"><?= htmlspecialchars($package['capacity']) ?>GB</span>
                        <span class="text-sm text-gray-600"><?= htmlspecialchars($package['mb']) ?> MB</span>
                    </div>
                    <div class="text-2xl font-bold text-green-600 mb-1">₵<?= htmlspecialchars($package['price']) ?></div>
                    <div class="text-sm text-gray-600">₵<?= htmlspecialchars($package['pricePerGB']) ?>/GB</div>
                    <div class="text-xs text-gray-500 mt-2">Network: <?= htmlspecialchars($package['network']) ?></div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div class="text-center py-8 text-gray-500">
                <i class="fas fa-box-open text-4xl mb-4"></i>
                <p>No data packages available</p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Transactions Section -->
        <div class="bg-white rounded-2xl p-6 card-shadow">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold text-gray-800">
                    <i class="fas fa-list mr-2 text-blue-600"></i>MTN API Transactions
                </h2>
                <div class="flex items-center space-x-3">
                    <select id="limitSelect" onchange="changeLimit()" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
                        <option value="10" <?= $limit == 10 ? 'selected' : '' ?>>10 per page</option>
                        <option value="20" <?= $limit == 20 ? 'selected' : '' ?>>20 per page</option>
                        <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50 per page</option>
                        <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100 per page</option>
                    </select>
                    <button onclick="refreshTransactions()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-xl text-sm transition-all">
                        <i class="fas fa-sync-alt mr-2"></i>Refresh
                    </button>
                </div>
            </div>
            
            <?php if (!empty($transactions)): ?>
            <div class="overflow-x-auto bg-white rounded-lg border border-gray-200">
                <table id="transactionsTable" class="w-full">
                    <thead class="bg-gray-50">
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">ID</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Phone Number</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Package</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Amount</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Status</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Reference</th>
                            <th class="text-left py-3 px-4 font-semibold text-gray-800 bg-gray-100">Date</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($transactions as $transaction): ?>
                        <tr class="bg-white hover:bg-blue-50 transition-colors duration-150">
                            <td class="py-3 px-4 text-sm text-gray-900 font-medium"><?= htmlspecialchars($transaction['_id']) ?></td>
                            <td class="py-3 px-4 text-sm text-gray-900 font-medium"><?= htmlspecialchars($transaction['phoneNumber']) ?></td>
                            <td class="py-3 px-4 text-sm text-gray-900 font-medium"><?= htmlspecialchars($transaction['packageSize']) ?></td>
                            <td class="py-3 px-4 text-sm text-gray-900 font-semibold">₵<?= htmlspecialchars($transaction['amount']) ?></td>
                            <td class="py-3 px-4">
                                <span class="px-3 py-1 text-xs font-semibold rounded-full <?= $transaction['status'] === 'completed' ? 'bg-green-100 text-green-800 border border-green-200' : 'bg-yellow-100 text-yellow-800 border border-yellow-200' ?>">
                                    <?= htmlspecialchars($transaction['status']) ?>
                                </span>
                            </td>
                            <td class="py-3 px-4 text-sm text-gray-900 font-mono bg-gray-50"><?= htmlspecialchars($transaction['reference']) ?></td>
                            <td class="py-3 px-4 text-sm text-gray-900"><?= date('M j, Y H:i', strtotime($transaction['createdAt'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if (!empty($pagination) && $pagination['totalPages'] > 1): ?>
            <div class="flex items-center justify-between mt-6">
                <div class="text-sm text-gray-700">
                    Showing page <?= $pagination['currentPage'] ?> of <?= $pagination['totalPages'] ?>
                </div>
                <div class="flex items-center space-x-2">
                    <?php if ($pagination['currentPage'] > 1): ?>
                    <a href="?page=<?= $pagination['currentPage'] - 1 ?>&limit=<?= $limit ?>" class="bg-gray-500 hover:bg-gray-600 text-white px-3 py-2 rounded-lg text-sm transition-all">
                        <i class="fas fa-chevron-left mr-1"></i>Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php if ($pagination['currentPage'] < $pagination['totalPages']): ?>
                    <a href="?page=<?= $pagination['currentPage'] + 1 ?>&limit=<?= $limit ?>" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-2 rounded-lg text-sm transition-all">
                        Next<i class="fas fa-chevron-right ml-1"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <?php else: ?>
            <div class="text-center py-8 text-gray-500">
                <i class="fas fa-inbox text-4xl mb-4"></i>
                <p>No transactions found</p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- DataTables JS -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.tailwindcss.min.js"></script>

    <script>
        // Initialize DataTable
        $(document).ready(function() {
            $('#transactionsTable').DataTable({
                "paging": false,
                "searching": true,
                "ordering": true,
                "info": false,
                "language": {
                    "search": "Search transactions:",
                    "emptyTable": "No transactions available"
                }
            });
        });

        function refreshTransactions() {
            window.location.reload();
        }

        function refreshPackages() {
            window.location.reload();
        }

        function changeLimit() {
            const limit = document.getElementById('limitSelect').value;
            window.location.href = `?page=1&limit=${limit}`;
        }
    </script>
</body>
</html>
