<?php
session_start();
error_reporting(0);

// Check if logged in
if (!isset($_SESSION['agent_id'])) {
    header("Location: index.php");
    exit();
}

include_once('../include/db_config.php');
include_once('../lib/Agent.class.php');

$agent = new Agent();
$agentId = $_SESSION['agent_id'];
$agentData = $agent->getAgentById($agentId);

// Get agent balance
$balance = $agentData['balance'];

// Get transaction history (last 10)
$transactions = $agent->getTransactions($agentId, 10);

// Get user profiles from MikroTik for voucher generation
include_once('../lib/routeros_api.class.php');
include_once('../include/config.php');

// Get MikroTik session
$sessions = array_keys($data);
$session = null;
foreach ($sessions as $s) {
    if ($s != 'mikhmon') {
        $session = $s;
        break;
    }
}

$profiles = [];
if ($session) {
    try {
        $iphost = explode('!', $data[$session][1])[1];
        $userhost = explode('@|@', $data[$session][2])[1];
        $passwdhost = explode('#|#', $data[$session][3])[1];
        
        $API = new RouterosAPI();
        $API->debug = false;
        
        if ($API->connect($iphost, $userhost, decrypt($passwdhost))) {
            $profilesData = $API->comm("/ip/hotspot/user/profile/print");
            foreach ($profilesData as $profile) {
                if (isset($profile['name'])) {
                    $profiles[] = $profile['name'];
                }
            }
            $API->disconnect();
        }
    } catch (Exception $e) {
        // Handle connection error
    }
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agent Dashboard - MikhMon</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="agent.css">
</head>
<body>
    <div class="header">
        <h1><i class="fa fa-dashboard"></i> Agent Dashboard</h1>
        <nav>
            <a href="vouchers.php"><i class="fa fa-ticket"></i> My Vouchers</a>
            <a href="transactions.php"><i class="fa fa-history"></i> Transactions</a>
            <a href="?logout=1"><i class="fa fa-sign-out"></i> Logout</a>
        </nav>
    </div>
    
    <div class="container">
        <!-- Balance Card -->
        <div class="card balance-card">
            <div class="balance-label">Your Current Balance</div>
            <div class="balance-amount">Rp <?= number_format($balance, 0, ',', '.'); ?></div>
            <div class="balance-label">Agent Code: <?= $agentData['agent_code']; ?></div>
        </div>
        
        <div class="dashboard-grid">
            <!-- Generate Voucher Card -->
            <div class="card">
                <div class="card-header">
                    <h2><i class="fa fa-ticket"></i> Generate Voucher</h2>
                </div>
                
                <form id="generateForm">
                    <input type="hidden" name="agent_id" value="<?= $agentId; ?>">
                    <input type="hidden" name="agent_token" value="<?= $_SESSION['agent_token']; ?>">
                    
                    <div class="form-group">
                        <label>Profile</label>
                        <select name="profile" class="form-control" required>
                            <option value="">-- Select Profile --</option>
                            <?php foreach ($profiles as $profile): ?>
                            <option value="<?= $profile; ?>"><?= $profile; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Quantity</label>
                        <input type="number" name="quantity" class="form-control" min="1" max="100" value="1" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Customer Phone (Optional)</label>
                        <input type="text" name="customer_phone" class="form-control" placeholder="Customer phone number">
                    </div>
                    
                    <div class="form-group">
                        <label>Customer Name (Optional)</label>
                        <input type="text" name="customer_name" class="form-control" placeholder="Customer name">
                    </div>
                    
                    <button type="submit" class="btn btn-block" id="generateBtn">
                        <i class="fa fa-plus-circle"></i> Generate Voucher
                    </button>
                </form>
                
                <div id="voucherResult" class="voucher-result">
                    <h3><i class="fa fa-check-circle"></i> Generated Vouchers</h3>
                    <div id="voucherList" class="voucher-list"></div>
                    <div style="margin-top: 15px;">
                        <strong>New Balance:</strong> <span id="newBalance">Rp 0</span>
                    </div>
                </div>
            </div>
            
            <!-- Transaction History Card -->
            <div class="card">
                <div class="card-header">
                    <h2><i class="fa fa-history"></i> Recent Transactions</h2>
                </div>
                
                <?php if (!empty($transactions)): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $trx): ?>
                        <tr>
                            <td><?= date('d/m H:i', strtotime($trx['created_at'])); ?></td>
                            <td>
                                <span class="badge badge-<?= $trx['transaction_type']; ?>">
                                    <?= ucfirst($trx['transaction_type']); ?>
                                </span>
                            </td>
                            <td style="font-weight: bold; color: <?= $trx['transaction_type'] == 'topup' ? '#10b981' : '#ef4444'; ?>">
                                <?= $trx['transaction_type'] == 'topup' ? '+' : '-'; ?>Rp <?= number_format($trx['amount'], 0, ',', '.'); ?>
                            </td>
                            <td>
                                <?= $trx['description'] ?: ($trx['profile_name'] . ' - ' . $trx['voucher_username']); ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                <p>No transactions found.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Modern Voucher Popup Modal -->
    <div id="voucherModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fa fa-check-circle"></i> Voucher Berhasil Di-generate!</h2>
                <span class="modal-close" onclick="closeVoucherModal()">&times;</span>
            </div>
            
            <div class="modal-body">
                <div class="success-message">
                    <i class="fa fa-check-circle-o"></i>
                    <p>Berhasil generate <strong id="voucherCount">0</strong> voucher</p>
                    <p class="balance-info">Saldo Anda: <strong id="modalBalance">Rp 0</strong></p>
                </div>
                
                <div id="voucherCards" class="voucher-cards"></div>
            </div>
            
            <div class="modal-footer">
                <button onclick="printVouchers()" class="btn-modal btn-print">
                    <i class="fa fa-print"></i> Print Voucher
                </button>
                <button onclick="sendViaWhatsApp()" class="btn-modal btn-whatsapp">
                    <i class="fa fa-whatsapp"></i> Kirim via WhatsApp
                </button>
                <button onclick="closeVoucherModal()" class="btn-modal btn-close">
                    <i class="fa fa-times"></i> Tutup
                </button>
            </div>
        </div>
    </div>

    <script>
        let generatedVouchers = [];
        
        document.getElementById('generateForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const form = this;
            const submitBtn = document.getElementById('generateBtn');
            const originalBtnText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating...';
            submitBtn.disabled = true;
            
            // Prepare form data
            const formData = new FormData(form);
            
            // Send request to API
            fetch('../api/agent_generate_voucher.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Store vouchers globally
                    generatedVouchers = data.vouchers;
                    
                    // Show modal with vouchers
                    showVoucherModal(data);
                    
                    // Reset form
                    form.reset();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat generate voucher');
            })
            .finally(() => {
                // Reset button
                submitBtn.innerHTML = originalBtnText;
                submitBtn.disabled = false;
            });
        });
        
        function showVoucherModal(data) {
            const modal = document.getElementById('voucherModal');
            const voucherCards = document.getElementById('voucherCards');
            
            // Update count and balance
            document.getElementById('voucherCount').textContent = data.vouchers.length;
            document.getElementById('modalBalance').textContent = 'Rp ' + Number(data.balance).toLocaleString('id-ID');
            
            // Generate voucher cards
            let cardsHtml = '';
            data.vouchers.forEach((voucher, index) => {
                cardsHtml += `
                <div class="voucher-card-modern">
                    <div class="voucher-card-header">
                        <span class="voucher-number">#${index + 1}</span>
                        <span class="voucher-profile-badge">${voucher.profile}</span>
                    </div>
                    <div class="voucher-card-body">
                        <div class="qr-code-container">
                            <img class="qr-code-image" 
                                 alt="QR Code" 
                                 data-username="${voucher.username}"
                                 data-password="${voucher.password}">
                            <div class="qr-label">Scan untuk login</div>
                        </div>
                        <div class="voucher-field">
                            <label>Username</label>
                            <div class="voucher-value">
                                <span class="value-text">${voucher.username}</span>
                                <button onclick="copyToClipboard('${voucher.username}')" class="btn-copy" title="Copy">
                                    <i class="fa fa-copy"></i>
                                </button>
                            </div>
                        </div>
                        <div class="voucher-field">
                            <label>Password</label>
                            <div class="voucher-value">
                                <span class="value-text">${voucher.password}</span>
                                <button onclick="copyToClipboard('${voucher.password}')" class="btn-copy" title="Copy">
                                    <i class="fa fa-copy"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            });
            
            voucherCards.innerHTML = cardsHtml;
            
            // Set QR code images after DOM is ready
            setTimeout(() => {
                const qrImages = document.querySelectorAll('.qr-code-image');
                qrImages.forEach(img => {
                    const username = img.getAttribute('data-username');
                    const password = img.getAttribute('data-password');
                    const loginUrl = 'http://10.5.50.1/login?username=' + username + '&password=' + password;
                    const qrUrl = 'https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=' + encodeURIComponent(loginUrl) + '&choe=UTF-8';
                    img.src = qrUrl;
                    
                    // Fallback if Google Charts fails
                    img.onerror = function() {
                        this.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(loginUrl);
                    };
                });
            }, 100);
            
            modal.style.display = 'flex';
            
            // Add animation
            setTimeout(() => {
                modal.querySelector('.modal-content').style.transform = 'scale(1)';
                modal.querySelector('.modal-content').style.opacity = '1';
            }, 10);
        }
        
        function closeVoucherModal(skipReload = false) {
            const modal = document.getElementById('voucherModal');
            modal.querySelector('.modal-content').style.transform = 'scale(0.7)';
            modal.querySelector('.modal-content').style.opacity = '0';
            
            setTimeout(() => {
                modal.style.display = 'none';
                
                // Reload page to update balance and transaction history
                if (!skipReload) {
                    location.reload();
                }
            }, 300);
        }
        
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                // Show temporary success message
                const btn = event.target.closest('.btn-copy');
                const originalHtml = btn.innerHTML;
                btn.innerHTML = '<i class="fa fa-check"></i>';
                btn.style.background = '#10b981';
                
                setTimeout(() => {
                    btn.innerHTML = originalHtml;
                    btn.style.background = '';
                }, 1000);
            }).catch(err => {
                alert('Gagal copy: ' + err);
            });
        }
        
        function printVouchers() {
            const printWindow = window.open('', '_blank');
            const vouchers = generatedVouchers;
            
            let printContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>Print Voucher</title>
                <style>
                    body { font-family: Arial, sans-serif; padding: 20px; }
                    .voucher-print { 
                        border: 2px dashed #333; 
                        padding: 20px; 
                        margin: 20px 0; 
                        page-break-inside: avoid;
                        width: 300px;
                    }
                    .voucher-print h3 { margin: 0 0 15px 0; text-align: center; }
                    .voucher-print .field { margin: 10px 0; }
                    .voucher-print .label { font-weight: bold; font-size: 12px; color: #666; }
                    .voucher-print .value { 
                        font-size: 18px; 
                        font-family: monospace; 
                        background: #f0f0f0; 
                        padding: 8px; 
                        margin-top: 5px;
                        border-radius: 4px;
                    }
                    .voucher-print .profile { 
                        text-align: center; 
                        background: #667eea; 
                        color: white; 
                        padding: 5px; 
                        border-radius: 4px;
                        margin-bottom: 15px;
                    }
                    @media print {
                        .voucher-print { page-break-after: always; }
                    }
                </style>
            </head>
            <body>
            `;
            
            vouchers.forEach((voucher, index) => {
                const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent('http://10.5.50.1/login?username=' + voucher.username + '&password=' + voucher.password)}`;
                
                printContent += `
                <div class="voucher-print">
                    <h3>Voucher WiFi #${index + 1}</h3>
                    <div class="profile">${voucher.profile}</div>
                    <div style="text-align: center; margin: 15px 0;">
                        <img src="${qrUrl}" width="150" height="150" style="border: 2px solid #667eea; padding: 5px; border-radius: 8px;">
                        <div style="font-size: 11px; color: #666; margin-top: 5px;">Scan untuk login otomatis</div>
                    </div>
                    <div class="field">
                        <div class="label">Username:</div>
                        <div class="value">${voucher.username}</div>
                    </div>
                    <div class="field">
                        <div class="label">Password:</div>
                        <div class="value">${voucher.password}</div>
                    </div>
                </div>
                `;
            });
            
            printContent += `
            </body>
            </html>
            `;
            
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            setTimeout(() => {
                printWindow.print();
            }, 500);
            
            // Show notification
            showNotification('Voucher siap di-print! Silakan cek jendela print.', 'success');
        }
        
        function sendViaWhatsApp() {
            const phone = prompt('Masukkan nomor WhatsApp (contoh: 628123456789):');
            
            if (!phone) return;
            
            let message = '🎫 *Voucher WiFi*\n\n';
            
            generatedVouchers.forEach((voucher, index) => {
                message += `*Voucher #${index + 1}*\n`;
                message += `Profile: ${voucher.profile}\n`;
                message += `Username: \`${voucher.username}\`\n`;
                message += `Password: \`${voucher.password}\`\n\n`;
            });
            
            message += '✅ Terima kasih!';
            
            const whatsappUrl = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
            window.open(whatsappUrl, '_blank');
            
            // Show notification
            showNotification('Voucher berhasil dikirim ke WhatsApp!', 'success');
        }
        
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.innerHTML = `
                <i class="fa fa-${type === 'success' ? 'check-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            `;
            
            // Add to body
            document.body.appendChild(notification);
            
            // Show with animation
            setTimeout(() => {
                notification.classList.add('show');
            }, 10);
            
            // Remove after 3 seconds
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('voucherModal');
            if (event.target == modal) {
                if (confirm('Tutup modal? Halaman akan di-refresh untuk update saldo.')) {
                    closeVoucherModal();
                }
            }
        }
    </script>
</body>
</html>