<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/MikroTik.php';

requireRole('branch_admin');
$pageTitle = 'MikroTik Settings - Cabang';

$db = db();

// ============================================================================
// 1. DETEKSI CABANG USER
// ============================================================================
$currentUserId = currentUserId();
$userBranchId = null;
$userBranchName = 'Unknown';

try {
    $stmt = $db->prepare("SELECT u.branch_id, b.name as branch_name 
                          FROM users u LEFT JOIN branches b ON u.branch_id = b.id 
                          WHERE u.id = ?");
    $stmt->execute([$currentUserId]);
    $row = $stmt->fetch();
    $userBranchId = $row ? (int)$row['branch_id'] : null;
    $userBranchName = $row['branch_name'] ?? 'Unknown';
} catch (\Throwable $e) {}

if (!$userBranchId) {
    redirect('/branch/dashboard.php', '❌ Akun Anda tidak terdaftar di cabang manapun.', 'error');
}

// ============================================================================
// 2. FUNGSI LOAD CONFIG
// ============================================================================
function loadMtConfig($db, $branchId) {
    $config = [];
    try {
        $stmt = $db->prepare("
            SELECT setting_key, setting_value 
            FROM mikrotik_config 
            WHERE branch_id = ?
        ");
        $stmt->execute([$branchId]);
        while ($row = $stmt->fetch()) {
            $config[$row['setting_key']] = $row['setting_value'];
        }
    } catch (\Throwable $e) {
        $config = [];
    }
    return $config;
}

// ============================================================================
// 3. FUNGSI SIMPAN CONFIG (DIPERBAIKI: Sesuai struktur tabel baru)
// ============================================================================
function saveMtConfig($db, $branchId, $key, $value) {
    try {
        // ⭐ Menggunakan UNIQUE KEY (branch_id, setting_key) yang baru
        $stmt = $db->prepare("
            INSERT INTO mikrotik_config (branch_id, setting_key, setting_value, updated_at) 
            VALUES (?, ?, ?, NOW()) 
            ON DUPLICATE KEY UPDATE 
                setting_value = VALUES(setting_value),
                updated_at = NOW()
        ");
        $stmt->execute([$branchId, $key, $value]);
        return true;
    } catch (\Throwable $e) {
        // Fallback: delete + insert
        try {
            $stmt = $db->prepare("DELETE FROM mikrotik_config WHERE branch_id = ? AND setting_key = ?");
            $stmt->execute([$branchId, $key]);
            
            $stmt = $db->prepare("INSERT INTO mikrotik_config (branch_id, setting_key, setting_value, updated_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$branchId, $key, $value]);
            return true;
        } catch (\Throwable $e2) {
            throw new Exception("Gagal menyimpan config: " . $e2->getMessage());
        }
    }
}

// ============================================================================
// 4. LOAD CONFIG AWAL
// ============================================================================
$config = loadMtConfig($db, $userBranchId);
$isConfigured = !empty($config['host']) && !empty($config['user']);

$success = '';
$error = '';
$testResult = null;

// ============================================================================
// 5. HANDLE SAVE CONFIG
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_config') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        $settings = [
            'host'          => trim($_POST['host'] ?? ''),
            'user'          => trim($_POST['user'] ?? ''),
            'pass'          => $_POST['pass'] ?? '',
            'port'          => (int)($_POST['port'] ?? 8728),
            'timeout'       => (int)($_POST['timeout'] ?? 3),
            'pppoe_service' => trim($_POST['pppoe_service'] ?? 'pppoe'),
        ];
        
        if (empty($settings['host']) || empty($settings['user'])) {
            $error = 'Host dan Username wajib diisi';
        } else {
            try {
                $db->beginTransaction();
                
                foreach ($settings as $key => $value) {
                    saveMtConfig($db, $userBranchId, $key, $value);
                }
                
                $db->commit();
                
                // ⭐ RELOAD dari DB untuk memastikan data terbaru
                $config = loadMtConfig($db, $userBranchId);
                
                $success = '✅ Konfigurasi MikroTik untuk cabang <strong>' . htmlspecialchars($userBranchName) . '</strong> berhasil disimpan';
                
                logActivity($currentUserId, 'save_mikrotik_config', 
                    "Update konfigurasi MikroTik cabang {$userBranchName}");
            } catch (\Throwable $e) {
                if ($db->inTransaction()) $db->rollBack();
                $error = '❌ Gagal menyimpan: ' . $e->getMessage();
            }
        }
    }
}

// ============================================================================
// 6. HANDLE TEST CONNECTION
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_connection') {
    if (verifyCsrf($_POST['csrf_token'] ?? '')) {
        try {
            $mt = new MikroTik($userBranchId);
            $testResult = $mt->testConnection();
            
            if ($testResult['success']) {
                $success = '✅ Koneksi ke MikroTik cabang <strong>' . htmlspecialchars($userBranchName) . '</strong> BERHASIL!';
            } else {
                $error = '❌ Koneksi GAGAL: ' . $testResult['error'];
            }
        } catch (\Throwable $e) {
            $error = '❌ Error: ' . $e->getMessage();
        }
    }
}

// Get connection status for status card
if (!$testResult) {
    try {
        $mt_status = new MikroTik($userBranchId);
        $testResult = $mt_status->testConnection();
    } catch (\Throwable $e) {
        $testResult = ['success' => false, 'error' => $e->getMessage(), 'identity' => '', 'version' => '', 'board' => '', 'uptime' => ''];
    }
}

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.15); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 14px; flex: 1; min-width: 0; }
.burger-btn { background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); color: white; width: 42px; height: 42px; border-radius: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; flex-shrink: 0; }
.burger-btn:hover, .burger-btn:active { background: rgba(255,255,255,0.35); transform: scale(1.05); }
.navbar-info { min-width: 0; flex: 1; }
.navbar-greeting { color: rgba(255,255,255,0.85); font-size: 0.75rem; margin: 0; }
.navbar-title { color: white; font-size: 1.15rem; font-weight: 700; margin: 2px 0 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.navbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.main-content {
    padding: 16px;
    max-width: 900px;
    margin: 0 auto;

    display: flex;
    flex-direction: column;
    gap: 20px; /* jarak antar div */
}

.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.page-title i { font-size: 1.8rem; color: #0066CC; }
.branch-badge { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #003D7A; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600; display: inline-flex; align-items: center; gap: 5px; }

.status-card { border-radius: 14px; padding: 18px; margin-bottom: 20px; display: flex; align-items: center; gap: 14px; }
.status-card.connected { background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%); border: 2px solid #a5d6a7; }
.status-card.disconnected { background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%); border: 2px solid #ef9a9a; }
.status-icon-large { width: 50px; height: 50px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; color: white; flex-shrink: 0; }
.status-card.connected .status-icon-large { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.status-card.disconnected .status-icon-large { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.status-content { flex: 1; min-width: 0; }
.status-title { font-weight: 700; font-size: 0.95rem; margin-bottom: 2px; }
.status-card.connected .status-title { color: #1b5e20; }
.status-card.disconnected .status-title { color: #c62828; }
.status-subtitle { font-size: 0.78rem; color: #666; margin-bottom: 6px; }
.status-details { display: flex; gap: 12px; flex-wrap: wrap; font-size: 0.75rem; }
.status-details code { background: rgba(255,255,255,0.7); padding: 2px 6px; border-radius: 4px; font-size: 0.72rem; color: #333; }

.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.92rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern i { font-size: 1.2rem; margin-top: 2px; flex-shrink: 0; }

.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 { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 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.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }

/* ⭐ TWO COLUMN LAYOUT (PENGGANTI BOOTSTRAP) */
.two-col-layout { display: grid; grid-template-columns: 1fr; gap: 20px; }
@media (min-width: 992px) { .two-col-layout { grid-template-columns: 2fr 1fr; } }

.form-section { margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px dashed #e8f4f8; }
.form-section:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.section-title { display: flex; align-items: center; gap: 8px; font-size: 0.92rem; font-weight: 700; color: #003D7A; margin: 0 0 12px; }
.section-title i { color: #0066CC; font-size: 1rem; }

.form-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 12px; margin-bottom: 12px; }
.form-grid.equal { grid-template-columns: 1fr 1fr; }
.form-group-modern { margin-bottom: 0; }
.form-label-modern { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.form-label-modern i { color: #0066CC; }
.form-label-modern .required { color: #DC3545; margin-left: 2px; }
.form-control-modern { width: 100%; padding: 11px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.9rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; box-sizing: border-box; }
.form-control-modern:focus { outline: none; border-color: #0066CC; background: white; box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1); }
.form-hint { display: flex; align-items: center; gap: 4px; margin-top: 6px; font-size: 0.75rem; color: #999; }

.btn-modern { padding: 11px 20px; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: 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); box-shadow: 0 6px 20px rgba(0, 200, 83, 0.4); }
.btn-modern.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); color: white; box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }
.btn-modern.info:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 184, 212, 0.4); }
.btn-group-modern { display: flex; gap: 10px; margin-top: 16px; flex-wrap: wrap; }

.code-block { background: #1e293b; border-radius: 12px; overflow: hidden; margin-bottom: 14px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.code-block-header { background: #0f172a; padding: 10px 16px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #334155; }
.code-block-title { color: #94a3b8; font-size: 0.78rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; gap: 6px; }
.code-block-dots { display: flex; gap: 6px; }
.code-block-dots span { width: 10px; height: 10px; border-radius: 50%; }
.code-block-dots span:nth-child(1) { background: #ef4444; }
.code-block-dots span:nth-child(2) { background: #f59e0b; }
.code-block-dots span:nth-child(3) { background: #10b981; }
.code-block-content { padding: 14px 16px; color: #e2e8f0; font-family: 'Courier New', monospace; font-size: 0.82rem; line-height: 1.6; overflow-x: auto; white-space: pre; margin: 0; }
.code-block-content .cmd { color: #60a5fa; }
.code-block-content .param { color: #fbbf24; }
.code-block-content .value { color: #34d399; }

.mikrotik-info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
.mikrotik-info-item { background: #f8fafc; border-radius: 12px; padding: 14px; text-align: center; border-left: 3px solid #0066CC; }
.mikrotik-info-label { font-size: 0.72rem; color: #666; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; margin-bottom: 6px; }
.mikrotik-info-value { font-size: 0.95rem; font-weight: 700; color: #003D7A; word-break: break-word; }
.mikrotik-info-item.identity { border-left-color: #0066CC; }
.mikrotik-info-item.version { border-left-color: #00B8D4; }
.mikrotik-info-item.board { border-left-color: #607D8B; }
.mikrotik-info-item.uptime { border-left-color: #00C853; }

.trouble-list { display: grid; gap: 8px; }
.trouble-item { display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; background: #f8fafc; border-radius: 10px; border-left: 3px solid #FF9900; font-size: 0.85rem; }
.trouble-item i { color: #FF9900; margin-top: 2px; flex-shrink: 0; }
.trouble-item code { background: #fff3cd; padding: 1px 6px; border-radius: 4px; font-size: 0.78rem; color: #856404; font-weight: 700; }

.quick-check { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); border-radius: 12px; padding: 14px; margin-top: 12px; }
.quick-check-title { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.quick-check-list { list-style: none; padding: 0; margin: 0; }
.quick-check-list li { padding: 4px 0; color: #1565c0; font-size: 0.82rem; display: flex; align-items: flex-start; gap: 8px; }
.quick-check-list li i { color: #0066CC; margin-top: 2px; flex-shrink: 0; }

.quick-actions-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.quick-action-card { background: white; border: 2px solid #f0f0f0; border-radius: 12px; padding: 14px; text-align: center; text-decoration: none; transition: all 0.3s ease; color: inherit; display: block; }
.quick-action-card:hover { border-color: #0066CC; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 102, 204, 0.12); color: inherit; }
.quick-action-icon { width: 42px; height: 42px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; color: white; margin: 0 auto 8px; }
.quick-action-icon.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.quick-action-icon.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.quick-action-title { font-weight: 700; color: #003D7A; font-size: 0.82rem; }

@media (max-width: 992px) { .form-grid, .form-grid.equal { grid-template-columns: 1fr; } }
@media (max-width: 768px) {
    .navbar-modern { padding: 10px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-greeting, .navbar-badge { display: none; }
    .main-content { padding: 15px; }
    .page-header { flex-direction: column; align-items: stretch; }
    .page-title { font-size: 1.3rem; }
    .page-title i { font-size: 1.5rem; }
    .card-header-modern { padding: 14px 16px; font-size: 0.95rem; }
    .card-body-modern { padding: 16px; }
    .status-card { flex-direction: column; text-align: center; padding: 16px; }
    .status-details { justify-content: center; }
    .btn-group-modern { flex-direction: column; }
    .btn-modern { width: 100%; padding: 12px; }
    .mikrotik-info-grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 480px) {
    .navbar-modern { padding: 8px 12px; }
    .burger-btn { width: 38px; height: 38px; font-size: 1.15rem; }
    .navbar-title { font-size: 0.95rem; }
    .main-content { padding: 12px; }
    .page-title { font-size: 1.15rem; gap: 8px; }
    .card-header-modern { padding: 12px 14px; font-size: 0.9rem; }
    .card-body-modern { padding: 14px; }
    .form-control-modern { padding: 10px 12px; font-size: 0.88rem; }
    .status-icon-large { width: 44px; height: 44px; font-size: 1.3rem; }
    .mikrotik-info-grid { grid-template-columns: 1fr; }
}
</style>


<div class="content-wrapper">
<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>
        <div class="navbar-info">
            <p class="navbar-greeting">Pengaturan router MikroTik</p>
            <h1 class="navbar-title">MikroTik - <?= htmlspecialchars($userBranchName) ?></h1>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge"><i class="bi bi-router"></i> MikroTik</span>
    </div>
</div>
    <div class="page-header">
        
        <h2 class="page-title">
            <i class="bi bi-router"></i>
            <span>MikroTik Settings</span>
            <span class="branch-badge"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></span>
        </h2>
    </div>

    <?= flashMessage() ?>
    
    <?php if ($success): ?>
        <div class="alert-modern success"><i class="bi bi-check-circle-fill"></i><div><?= $success ?></div></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert-modern danger"><i class="bi bi-exclamation-circle-fill"></i><div><?= $error ?></div></div>
    <?php endif; ?>

    <div class="status-card <?= $testResult['success'] ? 'connected' : 'disconnected' ?>">
        <div class="status-icon-large">
            <i class="bi bi-<?= $testResult['success'] ? 'check-circle-fill' : 'x-circle-fill' ?>"></i>
        </div>
        <div class="status-content">
            <div class="status-title"><?= $testResult['success'] ? '✅ Terhubung ke MikroTik' : '❌ Tidak Terhubung' ?></div>
            <div class="status-subtitle">
                Cabang: <?= htmlspecialchars($userBranchName) ?>
                <?php if ($testResult['success'] && !empty($testResult['identity'])): ?>
                    · Identity: <strong><?= htmlspecialchars($testResult['identity']) ?></strong>
                <?php endif; ?>
            </div>
            <?php if ($testResult['success']): ?>
                <div class="status-details">
                    <span><strong>Host:</strong> <code><?= htmlspecialchars($config['host'] ?? '-') ?>:<?= htmlspecialchars($config['port'] ?? '-') ?></code></span>
                    <span><strong>Version:</strong> <code><?= htmlspecialchars($testResult['version'] ?? '-') ?></code></span>
                </div>
            <?php else: ?>
                <div class="status-details">
                    <span><strong>Error:</strong> <code><?= htmlspecialchars($testResult['error'] ?? 'Unknown') ?></code></span>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($testResult['success']): ?>
    <div class="card-modern">
        <div class="card-header-modern success">
            <div class="title-left"><i class="bi bi-info-circle-fill"></i><span>Informasi MikroTik</span></div>
        </div>
        <div class="card-body-modern">
            <div class="mikrotik-info-grid">
                <div class="mikrotik-info-item identity">
                    <div class="mikrotik-info-label">🏷️ Identity</div>
                    <div class="mikrotik-info-value"><?= htmlspecialchars($testResult['identity'] ?? '-') ?></div>
                </div>
                <div class="mikrotik-info-item version">
                    <div class="mikrotik-info-label">📦 RouterOS</div>
                    <div class="mikrotik-info-value"><?= htmlspecialchars($testResult['version'] ?? '-') ?></div>
                </div>
                <div class="mikrotik-info-item board">
                    <div class="mikrotik-info-label">🖥️ Board</div>
                    <div class="mikrotik-info-value"><?= htmlspecialchars($testResult['board'] ?? '-') ?></div>
                </div>
                <div class="mikrotik-info-item uptime">
                    <div class="mikrotik-info-label">⏱️ Uptime</div>
                    <div class="mikrotik-info-value"><?= htmlspecialchars($testResult['uptime'] ?? '-') ?></div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="two-col-layout">
        <div>
            <div class="card-modern">
                <div class="card-header-modern primary">
                    <div class="title-left"><i class="bi bi-gear-fill"></i><span>Konfigurasi Koneksi</span></div>
                </div>
                <div class="card-body-modern">
                    <form method="POST">
                        <?= csrfField() ?>
                        <input type="hidden" name="action" value="save_config">
                        
                        <div class="form-section">
                            <h3 class="section-title"><i class="bi bi-link-45deg"></i><span>Koneksi API</span></h3>
                            
                            <div class="form-grid">
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-hdd-network"></i>IP Address / Hostname <span class="required">*</span></label>
                                    <input type="text" name="host" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['host'] ?? '192.168.88.1') ?>" 
                                           required placeholder="192.168.88.1">
                                </div>
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-plug"></i>API Port <span class="required">*</span></label>
                                    <input type="number" name="port" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['port'] ?? 8728) ?>" 
                                           required min="1" max="65535">
                                    <small class="form-hint"><i class="bi bi-info-circle"></i>Default: 8728</small>
                                </div>
                            </div>
                            
                            <div class="form-grid equal">
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-person"></i>Username <span class="required">*</span></label>
                                    <input type="text" name="user" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['user'] ?? 'admin') ?>" required>
                                </div>
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-key-fill"></i>Password</label>
                                    <input type="password" name="pass" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['pass'] ?? '') ?>" 
                                           placeholder="Kosongkan jika tidak ada">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h3 class="section-title"><i class="bi bi-sliders"></i><span>Setting Lanjutan</span></h3>
                            
                            <div class="form-grid equal">
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-clock-fill"></i>Timeout (detik)</label>
                                    <input type="number" name="timeout" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['timeout'] ?? 3) ?>" min="1" max="30">
                                    <small class="form-hint"><i class="bi bi-info-circle"></i>Disarankan 3 detik</small>
                                </div>
                                <div class="form-group-modern">
                                    <label class="form-label-modern"><i class="bi bi-broadcast"></i>PPPoE Service Name</label>
                                    <input type="text" name="pppoe_service" class="form-control-modern" 
                                           value="<?= htmlspecialchars($config['pppoe_service'] ?? 'pppoe-service') ?>">
                                    <small class="form-hint"><i class="bi bi-info-circle"></i>Nama service PPPoE di MikroTik</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="btn-group-modern">
                            <button type="submit" class="btn-modern primary"><i class="bi bi-save-fill"></i><span>Simpan Konfigurasi</span></button>
                            <button type="submit" name="action" value="test_connection" class="btn-modern success"><i class="bi bi-plug-fill"></i><span>Test Koneksi</span></button>
                            <a href="/branch/mikrotik_status.php" class="btn-modern info"><i class="bi bi-list-ul"></i><span>Status PPPoE</span></a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card-modern">
                <div class="card-header-modern info">
                    <div class="title-left"><i class="bi bi-book-fill"></i><span>Cara Konfigurasi MikroTik</span></div>
                </div>
                <div class="card-body-modern">
                    <div class="form-section">
                        <h3 class="section-title"><i class="bi bi-1-circle-fill"></i><span>Enable API di MikroTik</span></h3>
                        <div class="code-block">
                            <div class="code-block-header">
                                <div class="code-block-title"><i class="bi bi-terminal-fill"></i>MikroTik Terminal</div>
                                <div class="code-block-dots"><span></span><span></span><span></span></div>
                            </div>
                            <pre class="code-block-content"><span class="cmd">/ip service</span>
<span class="cmd">set</span> <span class="param">api</span> <span class="value">disabled=no</span> <span class="param">port</span>=<span class="value">8728</span></pre>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h3 class="section-title"><i class="bi bi-2-circle-fill"></i><span>Buat User untuk API</span></h3>
                        <div class="code-block">
                            <div class="code-block-header">
                                <div class="code-block-title"><i class="bi bi-terminal-fill"></i>MikroTik Terminal</div>
                                <div class="code-block-dots"><span></span><span></span><span></span></div>
                            </div>
                            <pre class="code-block-content"><span class="cmd">/user</span>
<span class="cmd">add</span> <span class="param">name</span>=<span class="value">phpapi</span> <span class="param">group</span>=<span class="value">full</span> <span class="param">password</span>=<span class="value">YourPassword</span></pre>
                        </div>
                    </div>
                    
                    <div class="form-section" style="margin-bottom: 0; padding-bottom: 0;">
                        <h3 class="section-title"><i class="bi bi-3-circle-fill"></i><span>Setup PPPoE Server</span></h3>
                        <div class="code-block" style="margin-bottom: 0;">
                            <div class="code-block-header">
                                <div class="code-block-title"><i class="bi bi-terminal-fill"></i>MikroTik Terminal</div>
                                <div class="code-block-dots"><span></span><span></span><span></span></div>
                            </div>
                            <pre class="code-block-content"><span class="cmd">/interface pppoe-server server</span>
<span class="cmd">add</span> <span class="param">interface</span>=<span class="value">ether2</span> <span class="param">service-name</span>=<span class="value">pppoe-service</span> \
    <span class="param">authentication</span>=<span class="value">mschap2,mschap1,chap</span> \
    <span class="param">one-session-per-host</span>=<span class="value">yes</span> <span class="param">default-profile</span>=<span class="value">default</span></pre>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div>
            <div class="card-modern">
                <div class="card-header-modern warning">
                    <div class="title-left"><i class="bi bi-tools"></i><span>Troubleshooting</span></div>
                </div>
                <div class="card-body-modern">
                    <div class="trouble-list">
                        <div class="trouble-item"><i class="bi bi-exclamation-triangle-fill"></i><div><code>"Cannot connect"</code><br>IP salah atau port API belum dibuka.</div></div>
                        <div class="trouble-item"><i class="bi bi-exclamation-triangle-fill"></i><div><code>"Login failed"</code><br>Username/password salah.</div></div>
                        <div class="trouble-item"><i class="bi bi-exclamation-triangle-fill"></i><div><code>"Timeout"</code><br>MikroTik tidak reachable dari server.</div></div>
                        <div class="trouble-item"><i class="bi bi-exclamation-triangle-fill"></i><div><code>"Connection refused"</code><br>API service disabled di MikroTik.</div></div>
                    </div>
                    
                    <div class="quick-check">
                        <div class="quick-check-title"><i class="bi bi-lightning-fill"></i>Quick Check</div>
                        <ul class="quick-check-list">
                            <li><i class="bi bi-check-circle-fill"></i><span>Pastikan API enabled di MikroTik</span></li>
                            <li><i class="bi bi-check-circle-fill"></i><span>Cek firewall tidak blocking port 8728</span></li>
                            <li><i class="bi bi-check-circle-fill"></i><span>Test ping dari server ke IP MikroTik</span></li>
                        </ul>
                    </div>
                    
                    <div class="alert-modern info" style="margin-top: 12px; margin-bottom: 0;">
                        <i class="bi bi-person-fill"></i>
                        <div><strong>Hubungi Super Admin jika:</strong><br>Belum punya MikroTik atau perlu bantuan konfigurasi jaringan.</div>
                    </div>
                </div>
            </div>

            <div class="card-modern">
                <div class="card-header-modern primary">
                    <div class="title-left"><i class="bi bi-lightning-fill"></i><span>Aksi Cepat</span></div>
                </div>
                <div class="card-body-modern">
                    <div class="quick-actions-grid">
                        <a href="/branch/mikrotik_status.php" class="quick-action-card">
                            <div class="quick-action-icon primary"><i class="bi bi-list-ul"></i></div>
                            <div class="quick-action-title">Status PPPoE</div>
                        </a>
                        <a href="/branch/customers.php" class="quick-action-card">
                            <div class="quick-action-icon success"><i class="bi bi-people-fill"></i></div>
                            <div class="quick-action-title">Daftar Pelanggan</div>
                        </a>
                    </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' : '';
    }
}
</script>

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