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

requireLogin();

$user = getCurrentUser();
$earnings = getEarningsForUser($user);
$totalPlayers = getTotalPlayers();
$totalPlays = getTotalPlays();
$newPlayers = getNewPlayers();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shinda Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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">
                <span class="navbar-text me-3">
                    PesaPal: <span class="badge bg-<?php echo getPesapalMode() === 'production' ? 'success' : 'warning'; ?>"><?php echo ucfirst(getPesapalMode()); ?></span>
                </span>
                <span class="navbar-text me-3">Welcome, <?php echo htmlspecialchars($user['name']); ?> (<?php echo ucfirst(str_replace('_', ' ', $user['role'])); ?>)</span>
                <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 active" 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" 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">Dashboard</h1>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Total Earnings</h5>
                                <h3 class="text-success">Ksh <?php echo number_format($earnings, 2); ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Total Players</h5>
                                <h3><?php echo $totalPlayers; ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Total Plays</h5>
                                <h3><?php echo $totalPlays; ?></h3>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">New Players (30 days)</h5>
                                <h3 class="text-primary"><?php echo $newPlayers; ?></h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Successful Transactions</h5>
                                <h3 class="text-success"><?php echo getTransactionsCount(); ?></h3>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-md-12">
                        <canvas id="earningsChart"></canvas>
                    </div>
                </div>

                <?php if (hasPermission('super_admin') || hasPermission('admin')): ?>
                <div class="row mt-5">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">📱 Test USSD Flow</h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted small">Test USSD menu navigation</p>
                                <form id="ussdTestForm">
                                    <div class="mb-3">
                                        <label class="form-label">Phone Number</label>
                                        <input type="text" class="form-control" id="ussdPhone" placeholder="254712345678 or 0712345678" required>
                                        <small class="text-muted">Kenya format</small>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">USSD Text</label>
                                        <input type="text" class="form-control" id="ussdText" value="*500#" placeholder="*500# or *500*1# or *500*1*1#" required>
                                    </div>
                                    <button type="submit" class="btn btn-info w-100">Send USSD</button>
                                </form>
                                <div id="ussdResult" style="display: none; margin-top: 15px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>

    <script>
        // USSD Test Handler
        document.getElementById('ussdTestForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const phone = document.getElementById('ussdPhone').value;
            const text = document.getElementById('ussdText').value;
            const resultDiv = document.getElementById('ussdResult');

            resultDiv.innerHTML = '<div class="alert alert-info"><strong>⏳ Testing...</strong></div>';
            resultDiv.style.display = 'block';

            try {
                const response = await fetch(`/Shinda/api/ussd_test.php?phone=${encodeURIComponent(phone)}&text=${encodeURIComponent(text)}`);
                const data = await response.json();

                if (data.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            <strong>✅ USSD Response:</strong>
                            <div style="background: #f0f0f0; padding: 10px; border-radius: 5px; margin-top: 10px; white-space: pre-wrap; font-family: monospace; font-size: 13px;">
                                ${escapeHtml(data.response)}
                            </div>
                            <small class="text-muted mt-2 d-block">Phone: ${escapeHtml(phone)}</small>
                        </div>
                    `;
                    
                    // Show quick navigation for menu
                    if (data.response.includes('Welcome to Shinda')) {
                        resultDiv.innerHTML += '<p class="mt-2"><strong>Select a box:</strong><br>';
                        for (let i = 1; i <= 9; i++) {
                            resultDiv.innerHTML += `<button type="button" class="btn btn-sm btn-outline-primary me-1 mb-1" onclick="testUSSD('${escapeHtml(phone)}', '*500*${i}#')">Box ${i}</button>`;
                        }
                        resultDiv.innerHTML += '</p>';
                    } else if (data.response.includes('Confirm Payment')) {
                        resultDiv.innerHTML += '<p class="mt-2"><strong>Confirm payment:</strong><br>';
                        resultDiv.innerHTML += `<button type="button" class="btn btn-sm btn-success me-1" onclick="testUSSD('${escapeHtml(phone)}', '*500*${extractBoxNumber(data.input)}*1#')">Confirm (1)</button>`;
                        resultDiv.innerHTML += '</p>';
                    }
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <strong>❌ Error:</strong> ${escapeHtml(data.error)}
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <strong>❌ Error:</strong> ${escapeHtml(error.message)}
                    </div>
                `;
            }
        });

        function testUSSD(phone, text) {
            document.getElementById('ussdPhone').value = phone;
            document.getElementById('ussdText').value = text;
            document.getElementById('ussdTestForm').dispatchEvent(new Event('submit'));
        }

        function extractBoxNumber(text) {
            const match = text.match(/\*500\*(\d+)/);
            return match ? match[1] : '1';
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        // Sample chart data - replace with real data
        const ctx = document.getElementById('earningsChart').getContext('2d');
        const earningsChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                datasets: [{
                    label: 'Earnings',
                    data: [1200, 1900, 3000, 5000, 2000, 3000],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            }
        });

        // Transaction Notification System
        let lastNotificationCheck = Math.floor(Date.now() / 1000);
        const notifiedTransactions = new Set();

        async function checkTransactionNotifications() {
            try {
                const response = await fetch(`/Shinda/api/get_transaction_notifications.php?last_check=${lastNotificationCheck}`);
                const data = await response.json();
                
                if (data.success && data.transactions && data.transactions.length > 0) {
                    data.transactions.forEach(tx => {
                        if (!notifiedTransactions.has(tx.id)) {
                            notifiedTransactions.add(tx.id);
                            showTransactionNotification(tx);
                        }
                    });
                    lastNotificationCheck = data.current_time;
                }
            } catch (error) {
                console.error('Notification check error:', error);
            }
        }

        function showTransactionNotification(transaction) {
            const isCompleted = transaction.status === 'completed';
            const statusIcon = isCompleted ? '✅' : '❌';
            const statusColor = isCompleted ? 'success' : 'danger';
            const title = isCompleted ? 'Payment Completed!' : 'Payment Failed';
            
            // Create and show Bootstrap modal
            const modalHtml = `
                <div class="modal fade" id="notificationModal_${transaction.id}" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content border-${statusColor}">
                            <div class="modal-header bg-${statusColor} text-white">
                                <h5 class="modal-title">${statusIcon} ${title}</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-3">
                                    <strong>Phone:</strong> ${transaction.phone.slice(-10)}
                                </div>
                                <div class="mb-3">
                                    <strong>Amount:</strong> Ksh ${transaction.amount}
                                </div>
                                ${transaction.receipt ? `<div class="mb-3"><strong>Receipt:</strong> ${transaction.receipt}</div>` : ''}
                                <div class="mb-3">
                                    <strong>Status:</strong> <span class="badge bg-${statusColor}">${transaction.status.toUpperCase()}</span>
                                </div>
                                <div class="mb-3">
                                    <strong>Time:</strong> ${new Date(transaction.updated_at).toLocaleString()}
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Add modal to body
            const modalContainer = document.createElement('div');
            modalContainer.innerHTML = modalHtml;
            document.body.appendChild(modalContainer);
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById(`notificationModal_${transaction.id}`));
            modal.show();
            
            // Auto-close after 5 seconds
            setTimeout(() => {
                modal.hide();
            }, 5000);
        }

        // Start checking for transaction notifications every 2 seconds
        setInterval(checkTransactionNotifications, 2000);
    </script>
</body>
</html>