<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/iPaymu.php';
require_once __DIR__ . '/../classes/Violet.php';
requireRole('super_admin');
$pageTitle = 'Payment Gateway Settings';

$db = db();
$success = '';
$error = '';

// Load config
$config = [];
$stmt = $db->query("SELECT setting_key, setting_value FROM payment_config");
while ($row = $stmt->fetch()) {
    $config[$row['setting_key']] = $row['setting_value'];
}

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_config') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $settings = [
            // Active gateway selector
            'active_gateway' => $_POST['active_gateway'] ?? 'ipaymu',
            
            // iPaymu settings
            'ipaymu_va' => trim($_POST['ipaymu_va'] ?? ''),
            'ipaymu_api_key' => trim($_POST['ipaymu_api_key'] ?? ''),
            'ipaymu_mode' => $_POST['ipaymu_mode'] ?? 'sandbox',
            'ipaymu_notify_url' => trim($_POST['ipaymu_notify_url'] ?? ''),
            'ipaymu_return_url' => trim($_POST['ipaymu_return_url'] ?? ''),
            'ipaymu_cancel_url' => trim($_POST['ipaymu_cancel_url'] ?? ''),
            
            // Violet settings
            'violet_api_key' => trim($_POST['violet_api_key'] ?? ''),
            'violet_secret_key' => trim($_POST['violet_secret_key'] ?? ''),
            'violet_mode' => $_POST['violet_mode'] ?? 'sandbox',
            'violet_notify_url' => trim($_POST['violet_notify_url'] ?? ''),
            'violet_return_url' => trim($_POST['violet_return_url'] ?? ''),
        ];
        
        foreach ($settings as $key => $value) {
            $db->prepare("INSERT INTO payment_config (setting_key, setting_value) VALUES (?, ?) 
                         ON DUPLICATE KEY UPDATE setting_value = ?")
               ->execute([$key, $value, $value]);
        }
        
        $success = '✅ Konfigurasi Payment Gateway berhasil disimpan';
        $config = array_merge($config, $settings);
    }
}

// Handle test iPaymu
$testResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_ipaymu') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        try {
            $ipaymu = new iPaymu();
            $testResult = ['gateway' => 'ipaymu', 'result' => $ipaymu->getPaymentChannels()];
        } catch (\Throwable $e) {
            $testResult = ['gateway' => 'ipaymu', 'result' => ['success' => false, 'error' => $e->getMessage()]];
        }
    }
}

// Handle test Violet
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_violet') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        try {
            $violet = new Violet();
            $testResult = ['gateway' => 'violet', 'result' => $violet->getChannels()];
        } catch (\Throwable $e) {
            $testResult = ['gateway' => 'violet', 'result' => ['success' => false, 'error' => $e->getMessage()]];
        }
    }
}

$activeGateway = $config['active_gateway'] ?? 'ipaymu';
$baseUrl = 'https://' . $_SERVER['HTTP_HOST'];

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* === PAGE HEADER === */
.page-header { margin-bottom: 25px; }
.page-title {
    font-size: 1.8rem; font-weight: 700; color: #003D7A;
    margin-bottom: 8px; display: flex; align-items: center; gap: 12px;
}
.page-title i { font-size: 2rem; color: #0066CC; }
.page-subtitle { color: #666; font-size: 0.95rem; margin: 0; }

/* === CARD MODERN === */
.card-modern {
    background: white; border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden; margin-bottom: 20px; border: none;
}
.card-header-modern {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white; padding: 18px 24px; font-size: 1.1rem; font-weight: 600;
    display: flex; align-items: center; gap: 10px;
}
.card-header-modern.violet { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); }
.card-header-modern.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.card-header-modern.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.card-header-modern.active { background: linear-gradient(135deg, #059669 0%, #10b981 100%); }
.card-body-modern { padding: 24px; }

/* === FORM === */
.form-group-modern { margin-bottom: 22px; }
.form-label-modern {
    display: block; font-weight: 600; color: #003D7A;
    margin-bottom: 8px; font-size: 0.95rem;
}
.form-control-modern, .form-select-modern {
    width: 100%; padding: 12px 16px;
    border: 2px solid #e8f4f8; border-radius: 12px;
    font-size: 0.95rem; transition: all 0.3s ease; background: #f8fafc;
}
.form-control-modern:focus, .form-select-modern:focus {
    outline: none; border-color: #0066CC; background: white;
    box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1);
}
.form-text-modern { display: block; margin-top: 6px; font-size: 0.85rem; color: #666; }

/* === ALERT === */
.alert-modern {
    padding: 16px 20px; border-radius: 12px; margin-bottom: 20px;
    display: flex; align-items: flex-start; gap: 12px; font-size: 0.95rem;
}
.alert-modern.info { background: #e3f2fd; border: 2px solid #90caf9; color: #1565c0; }
.alert-modern.success { background: #e8f5e9; border: 2px solid #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border: 2px solid #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border: 2px solid #ffd54f; color: #856404; }
.alert-modern i { font-size: 1.3rem; margin-top: 2px; }

/* === BUTTON === */
.btn-modern {
    padding: 12px 24px; border: none; border-radius: 12px;
    font-size: 0.95rem; font-weight: 600; cursor: pointer;
    transition: all 0.3s ease; display: inline-flex;
    align-items: center; gap: 8px; text-decoration: none;
}
.btn-modern.primary {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white; box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3);
}
.btn-modern.primary:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4); }
.btn-modern.success {
    background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%);
    color: white; box-shadow: 0 4px 15px rgba(0, 200, 83, 0.3);
}
.btn-modern.success:hover { transform: translateY(-2px); }
.btn-modern.violet {
    background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%);
    color: white; box-shadow: 0 4px 15px rgba(124, 58, 237, 0.3);
}
.btn-modern.violet:hover { transform: translateY(-2px); }

.btn-group-modern { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 24px; }

/* === TABLE === */
.table-modern { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.9rem; }
.table-modern thead { background: #f8fafc; }
.table-modern th {
    padding: 12px 16px; text-align: left; font-weight: 600;
    color: #003D7A; border-bottom: 2px solid #e8f4f8;
}
.table-modern td { padding: 12px 16px; border-bottom: 1px solid #f0f0f0; }
.table-modern tbody tr:hover { background: #f8fafc; }

/* === BADGE === */
.badge-modern { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; }
.badge-modern.secondary { background: #e0e0e0; color: #424242; }
.badge-modern.success { background: #c8e6c9; color: #2e7d32; }
.badge-modern.warning { background: #fff9c4; color: #f57f17; }
.badge-modern.active { background: #10b981; color: white; }

/* === GATEWAY SELECTOR === */
.gateway-selector {
    display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;
}
.gateway-option {
    position: relative; padding: 20px; border: 3px solid #e8f4f8;
    border-radius: 16px; cursor: pointer; transition: all 0.3s ease;
    background: #f8fafc;
}
.gateway-option:hover { border-color: #0066CC; background: white; }
.gateway-option.active {
    border-color: #10b981; background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.2);
}
.gateway-option input[type="radio"] { position: absolute; opacity: 0; }
.gateway-option-header {
    display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;
}
.gateway-option-title { font-size: 1.1rem; font-weight: 700; color: #003D7A; }
.gateway-option-desc { font-size: 0.85rem; color: #666; line-height: 1.5; }
.gateway-active-badge {
    display: none; background: #10b981; color: white;
    padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600;
}
.gateway-option.active .gateway-active-badge { display: inline-block; }

/* === DIVIDER === */
.divider-modern { border: none; border-top: 2px dashed #e8f4f8; margin: 20px 0; }

/* === GUIDE === */
.guide-section { background: #f8fafc; border-radius: 12px; padding: 20px; margin-bottom: 16px; }
.guide-section h6 {
    color: #003D7A; font-weight: 700; margin-bottom: 12px;
    display: flex; align-items: center; gap: 8px;
}
.guide-section ol, .guide-section ul { margin-bottom: 0; padding-left: 20px; }
.guide-section li { margin-bottom: 8px; color: #555; line-height: 1.6; }

/* === RESPONSIVE === */
@media (max-width: 768px) {
    .page-title { font-size: 1.4rem; flex-wrap: wrap; }
    .card-header-modern { padding: 15px 18px; font-size: 1rem; }
    .card-body-modern { padding: 18px; }
    .form-control-modern, .form-select-modern { padding: 10px 14px; font-size: 0.9rem; }
    .btn-modern { padding: 10px 18px; font-size: 0.9rem; flex: 1; justify-content: center; }
    .btn-group-modern { flex-direction: column; }
    .gateway-selector { grid-template-columns: 1fr; }
}
</style>

<div class="main-content">
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()">
                <i class="bi bi-list"></i>
            </button>
            <h1 class="navbar-title">Payment Gateway</h1>
        </div>
        <div class="navbar-right">
            <span class="navbar-badge">
                <i class="bi bi-shield-check"></i> Super Admin
            </span>
        </div>
    </div>

    <div class="content-wrapper">
        <div class="page-header">
            <h2 class="page-title">
                <i class="bi bi-credit-card-2-front"></i>
                <span>Payment Gateway Settings</span>
            </h2>
            <p class="page-subtitle">Konfigurasi gateway pembayaran iPaymu & Violet untuk transaksi otomatis</p>
        </div>
        
        <?php if ($success): ?>
            <div class="alert-modern success">
                <i class="bi bi-check-circle-fill"></i>
                <div><?= htmlspecialchars($success) ?></div>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert-modern danger">
                <i class="bi bi-exclamation-circle-fill"></i>
                <div><?= htmlspecialchars($error) ?></div>
            </div>
        <?php endif; ?>

        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="save_config">
            
            <!-- ============================================
                 GATEWAY SELECTOR (PILIHAN ADMIN)
                 ============================================ -->
            <div class="card-modern">
                <div class="card-header-modern active">
                    <i class="bi bi-toggles"></i>
                    <span>Pilih Gateway Pembayaran Aktif</span>
                </div>
                <div class="card-body-modern">
                    <div class="alert-modern info">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>
                            Pilih gateway yang akan digunakan untuk semua transaksi pelanggan. 
                            Pelanggan <strong>tidak bisa memilih</strong> — sistem otomatis menggunakan gateway yang Anda pilih di sini.
                        </div>
                    </div>
                    
                    <div class="gateway-selector">
                        <!-- iPaymu Option -->
                        <label class="gateway-option <?= $activeGateway === 'ipaymu' ? 'active' : '' ?>" id="opt-ipaymu">
                            <input type="radio" name="active_gateway" value="ipaymu" 
                                   <?= $activeGateway === 'ipaymu' ? 'checked' : '' ?>
                                   onchange="selectGateway('ipaymu')">
                            <div class="gateway-option-header">
                                <div class="gateway-option-title">
                                    <i class="bi bi-wallet2" style="color:#ff6b35;"></i> iPaymu
                                </div>
                                <span class="gateway-active-badge">
                                    <i class="bi bi-check-circle-fill"></i> AKTIF
                                </span>
                            </div>
                            <div class="gateway-option-desc">
                                Payment gateway Indonesia dengan dukungan VA, QRIS, E-Wallet, Minimarket, dan Kartu Kredit.
                            </div>
                        </label>
                        
                        <!-- Violet Option -->
                        <label class="gateway-option <?= $activeGateway === 'violet' ? 'active' : '' ?>" id="opt-violet">
                            <input type="radio" name="active_gateway" value="violet"
                                   <?= $activeGateway === 'violet' ? 'checked' : '' ?>
                                   onchange="selectGateway('violet')">
                            <div class="gateway-option-header">
                                <div class="gateway-option-title">
                                    <i class="bi bi-gem" style="color:#7c3aed;"></i> Violet MediaPay
                                </div>
                                <span class="gateway-active-badge">
                                    <i class="bi bi-check-circle-fill"></i> AKTIF
                                </span>
                            </div>
                            <div class="gateway-option-desc">
                                Payment gateway alternatif dengan QRIS, VA, dan berbagai channel pembayaran populer.
                            </div>
                        </label>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" class="btn-modern primary">
                            <i class="bi bi-save-fill"></i>
                            <span>Simpan Pilihan Gateway</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- ============================================
                 iPaymu CONFIGURATION
                 ============================================ -->
            <div class="card-modern">
                <div class="card-header-modern">
                    <i class="bi bi-wallet2"></i>
                    <span>Konfigurasi iPaymu</span>
                    <?php if ($activeGateway === 'ipaymu'): ?>
                        <span class="badge-modern active ms-auto">🟢 AKTIF</span>
                    <?php else: ?>
                        <span class="badge-modern secondary ms-auto">⚪ Nonaktif</span>
                    <?php endif; ?>
                </div>
                <div class="card-body-modern">
                    <div class="alert-modern info">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>
                            Dapatkan VA dan API Key di dashboard iPaymu: 
                            <a href="https://sandbox.ipaymu.com" target="_blank" style="color:#1565c0;font-weight:600;">sandbox.ipaymu.com</a> (testing) atau
                            <a href="https://my.ipaymu.com" target="_blank" style="color:#1565c0;font-weight:600;">my.ipaymu.com</a> (production)
                        </div>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Mode</label>
                        <select name="ipaymu_mode" class="form-select-modern">
                            <option value="sandbox" <?= ($config['ipaymu_mode'] ?? 'sandbox') === 'sandbox' ? 'selected' : '' ?>>🧪 Sandbox (Testing)</option>
                            <option value="production" <?= ($config['ipaymu_mode'] ?? '') === 'production' ? 'selected' : '' ?>>🚀 Production (Live)</option>
                        </select>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Virtual Account (VA) Number</label>
                        <input type="text" name="ipaymu_va" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['ipaymu_va'] ?? '') ?>" 
                               placeholder="Masukkan VA Number">
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">API Key</label>
                        <input type="text" name="ipaymu_api_key" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['ipaymu_api_key'] ?? '') ?>" 
                               placeholder="Masukkan API Key">
                    </div>
                    
                    <hr class="divider-modern">
                    
                    <h6 style="color:#003D7A;font-weight:700;margin-bottom:16px;">
                        <i class="bi bi-link-45deg"></i> URL Callback iPaymu
                    </h6>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Callback URL (Notify URL)</label>
                        <input type="text" name="ipaymu_notify_url" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['ipaymu_notify_url'] ?? $baseUrl . '/public/payment_callback.php') ?>">
                        <small class="form-text-modern">URL ini akan dipanggil iPaymu setelah pembayaran</small>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Return URL</label>
                        <input type="text" name="ipaymu_return_url" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['ipaymu_return_url'] ?? $baseUrl . '/public/pay.php') ?>">
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Cancel URL</label>
                        <input type="text" name="ipaymu_cancel_url" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['ipaymu_cancel_url'] ?? $baseUrl . '/public/pay.php') ?>">
                    </div>
                    
                    <div class="btn-group-modern">
                        <button type="submit" name="action" value="test_ipaymu" class="btn-modern success">
                            <i class="bi bi-plug-fill"></i>
                            <span>Test Koneksi iPaymu</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- ============================================
                 VIOLET CONFIGURATION
                 ============================================ -->
            <div class="card-modern">
                <div class="card-header-modern violet">
                    <i class="bi bi-gem"></i>
                    <span>Konfigurasi Violet MediaPay</span>
                    <?php if ($activeGateway === 'violet'): ?>
                        <span class="badge-modern active ms-auto">🟢 AKTIF</span>
                    <?php else: ?>
                        <span class="badge-modern secondary ms-auto">⚪ Nonaktif</span>
                    <?php endif; ?>
                </div>
                <div class="card-body-modern">
                    <div class="alert-modern info">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>
                            Dapatkan API Key & Secret Key di dashboard Violet: 
                            <a href="https://violetmediapay.com" target="_blank" style="color:#1565c0;font-weight:600;">violetmediapay.com</a>
                        </div>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Mode</label>
                        <select name="violet_mode" class="form-select-modern">
                            <option value="sandbox" <?= ($config['violet_mode'] ?? 'sandbox') === 'sandbox' ? 'selected' : '' ?>>🧪 Sandbox (Testing)</option>
                            <option value="production" <?= ($config['violet_mode'] ?? '') === 'production' ? 'selected' : '' ?>>🚀 Production (Live)</option>
                        </select>
                        <small class="form-text-modern">⚠️ Violet sandbox URL menggunakan typo "sanbox" (sudah dihandle otomatis)</small>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">API Key</label>
                        <input type="text" name="violet_api_key" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['violet_api_key'] ?? '') ?>" 
                               placeholder="Masukkan API Key Violet">
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Secret Key</label>
                        <input type="text" name="violet_secret_key" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['violet_secret_key'] ?? '') ?>" 
                               placeholder="Masukkan Secret Key Violet">
                        <small class="form-text-modern">Digunakan untuk generate signature HMAC-SHA256</small>
                    </div>
                    
                    <hr class="divider-modern">
                    
                    <h6 style="color:#003D7A;font-weight:700;margin-bottom:16px;">
                        <i class="bi bi-link-45deg"></i> URL Callback Violet
                    </h6>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Callback URL (Notify URL)</label>
                        <input type="text" name="violet_notify_url" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['violet_notify_url'] ?? $baseUrl . '/public/violet_callback.php') ?>">
                        <small class="form-text-modern">URL ini akan dipanggil Violet setelah pembayaran</small>
                    </div>
                    
                    <div class="form-group-modern">
                        <label class="form-label-modern">Return URL</label>
                        <input type="text" name="violet_return_url" class="form-control-modern" 
                               value="<?= htmlspecialchars($config['violet_return_url'] ?? $baseUrl . '/public/pay.php') ?>">
                    </div>
                    
                    <div class="alert-modern warning">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <strong>Penting:</strong> Jika server Anda menggunakan whitelist IP, tambahkan IP Violet berikut:
                            <ul style="margin:8px 0 0 0;padding-left:20px;">
                                <li><code>202.155.132.37</code> (IPv4)</li>
                                <li><code>2001:df7:5300:9::122</code> (IPv6)</li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="btn-group-modern">
                        <button type="submit" name="action" value="test_violet" class="btn-modern violet">
                            <i class="bi bi-plug-fill"></i>
                            <span>Test Koneksi Violet</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Save All Button (sticky bottom) -->
            <div class="text-center mb-4">
                <button type="submit" class="btn-modern primary" style="padding:14px 40px;font-size:1rem;">
                    <i class="bi bi-save-fill"></i>
                    <span>Simpan Semua Konfigurasi</span>
                </button>
            </div>
        </form>

        <!-- ============================================
             TEST RESULT
             ============================================ -->
        <?php if ($testResult): ?>
            <div class="card-modern">
                <div class="card-header-modern info">
                    <i class="bi bi-list-check"></i>
                    <span>Hasil Test Koneksi — <?= strtoupper($testResult['gateway']) ?></span>
                </div>
                <div class="card-body-modern">
                    <?php 
                    $result = $testResult['result'];
                    if ($result['success'] ?? false): 
                    ?>
                        <div class="alert-modern success">
                            <i class="bi bi-check-circle-fill"></i>
                            <div>Koneksi ke <strong><?= strtoupper($testResult['gateway']) ?></strong> BERHASIL!</div>
                        </div>
                        <h6 style="color:#003D7A;font-weight:700;margin-bottom:12px;">
                            <i class="bi bi-cash-stack"></i> Payment Channels Tersedia:
                        </h6>
                        <div class="table-responsive">
                            <table class="table-modern">
                                <thead>
                                    <tr>
                                        <th>ID/Code</th>
                                        <th>Nama</th>
                                        <th>Type</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach (($result['channels'] ?? []) as $channel): ?>
                                        <tr>
                                            <td><code><?= htmlspecialchars($channel['id'] ?? $channel['code'] ?? '-') ?></code></td>
                                            <td><?= htmlspecialchars($channel['name'] ?? '-') ?></td>
                                            <td><span class="badge-modern secondary"><?= htmlspecialchars($channel['type'] ?? '-') ?></span></td>
                                            <td>
                                                <?php if (in_array(strtolower($channel['status'] ?? ''), ['available', 'active'])): ?>
                                                    <span class="badge-modern success">Available</span>
                                                <?php else: ?>
                                                    <span class="badge-modern warning"><?= htmlspecialchars($channel['status'] ?? '-') ?></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert-modern danger">
                            <i class="bi bi-x-circle-fill"></i>
                            <div>Koneksi <strong>GAGAL:</strong> <?= htmlspecialchars($result['error'] ?? 'Unknown error') ?></div>
                        </div>
                        <pre style="background:#f8fafc;padding:16px;border-radius:12px;font-size:0.85rem;overflow-x:auto;"><?= htmlspecialchars(json_encode($result['data'] ?? [], JSON_PRETTY_PRINT)) ?></pre>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- ============================================
             GUIDE SECTION
             ============================================ -->
        <div class="row g-4 mt-2">
            <div class="col-lg-6">
                <div class="card-modern">
                    <div class="card-header-modern warning">
                        <i class="bi bi-book-fill"></i>
                        <span>Cara Kerja Sistem</span>
                    </div>
                    <div class="card-body-modern">
                        <div class="guide-section">
                            <h6><i class="bi bi-gear-fill"></i> Alur Pembayaran</h6>
                            <ol>
                                <li>Admin memilih gateway aktif di halaman ini</li>
                                <li>Customer klik "Bayar Sekarang" di halaman tagihan</li>
                                <li>Sistem <strong>otomatis</strong> membuat transaksi di gateway yang dipilih admin</li>
                                <li>Customer diarahkan ke halaman pembayaran gateway</li>
                                <li>Customer bayar via VA/QRIS/E-wallet/Minimarket</li>
                                <li>Gateway kirim callback ke server kita</li>
                                <li>Sistem otomatis:
                                    <ul>
                                        <li>Update status tagihan → "paid"</li>
                                        <li>Update status customer → "active"</li>
                                        <li>Restore internet di MikroTik</li>
                                        <li>Catat saldo cabang (pending H+5)</li>
                                    </ul>
                                </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-6">
                <div class="card-modern">
                    <div class="card-header-modern info">
                        <i class="bi bi-credit-card-fill"></i>
                        <span>Perbandingan Gateway</span>
                    </div>
                    <div class="card-body-modern">
                        <div class="table-responsive">
                            <table class="table-modern">
                                <thead>
                                    <tr>
                                        <th>Fitur</th>
                                        <th>iPaymu</th>
                                        <th>Violet</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><strong>VA Bank</strong></td>
                                        <td>✅ BCA, BNI, BRI, Mandiri</td>
                                        <td>✅ BCA, BNI, BRI, Mandiri</td>
                                    </tr>
                                    <tr>
                                        <td><strong>QRIS</strong></td>
                                        <td>✅</td>
                                        <td>✅</td>
                                    </tr>
                                    <tr>
                                        <td><strong>E-Wallet</strong></td>
                                        <td>✅ GoPay, OVO, DANA, ShopeePay</td>
                                        <td>✅ GoPay, OVO, DANA, ShopeePay</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Minimarket</strong></td>
                                        <td>✅ Alfamart, Indomaret</td>
                                        <td>✅ Alfamart, Indomaret</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Kartu Kredit</strong></td>
                                        <td>✅</td>
                                        <td>❌</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Fee Transaksi</strong></td>
                                        <td><a href="https://ipaymu.com/biaya" target="_blank">Cek di sini</a></td>
                                        <td><a href="https://violetmediapay.com" target="_blank">Cek di sini</a></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function selectGateway(gw) {
    document.querySelectorAll('.gateway-option').forEach(el => el.classList.remove('active'));
    document.getElementById('opt-' + gw).classList.add('active');
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>