<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/Branch.php';
require_once __DIR__ . '/../classes/MikroTik.php';
requireRole('super_admin', 'branch_admin', 'staff');
$pageTitle = 'Tambah Pelanggan';

$db = db();
$branches = Branch::all();
$packages = $db->query("SELECT * FROM packages WHERE status='active' ORDER BY name")->fetchAll();

// ============================================================================
// 1. DETEKSI ROLE & BRANCH USER YANG SEDANG LOGIN
// ============================================================================
$currentUserId = currentUserId();
$currentUser = null;
$userRole = 'super_admin';
$userBranchId = null;
$userBranchName = 'Pusat';

try {
    $stmt = $db->prepare("SELECT id, username, name, role, branch_id FROM users WHERE id = ?");
    $stmt->execute([$currentUserId]);
    $currentUser = $stmt->fetch();
    
    if ($currentUser) {
        $userRole = $currentUser['role'] ?? 'super_admin';
        $userBranchId = !empty($currentUser['branch_id']) ? (int)$currentUser['branch_id'] : null;
    }
} catch (\Throwable $e) {
    $userRole = 'super_admin';
}

foreach ($branches as $b) {
    if ((int)$b['id'] === $userBranchId) {
        $userBranchName = $b['name'];
        break;
    }
}

$isSuperAdmin = ($userRole === 'super_admin');
$isBranchAdmin = ($userRole === 'branch_admin');

// ============================================================================
// 2. TENTUKAN MODE CABANG
// ============================================================================
$branchMode = 'auto';
$autoBranchId = null;
$autoBranchLabel = '';

if ($isSuperAdmin) {
    $branchMode = 'auto';
    $autoBranchId = null;
    $autoBranchLabel = 'Pusat (Super Admin)';
} elseif ($isBranchAdmin) {
    $branchMode = 'auto';
    $autoBranchId = $userBranchId;
    $autoBranchLabel = 'Cabang: ' . $userBranchName;
} else {
    $branchMode = 'manual';
}

// ============================================================================
// 3. AMBIL DATA MIKROTIK
// ============================================================================
$existingSecrets = [];
$pppProfiles = [];
$mtConnected = false;
$mtError = '';

try {
    $mt = new MikroTik();
    $mt->connect();
    $mtConnected = true;
    
    $secrets = $mt->getAllSecrets();
    if (is_array($secrets)) {
        foreach ($secrets as $s) {
            $existingSecrets[] = [
                'name' => $s['name'],
                'disabled' => isset($s['disabled']) && $s['disabled'] === 'true'
            ];
        }
    }
    
    $profilesRaw = $mt->getPPPProfiles();
    if (is_array($profilesRaw)) {
        foreach ($profilesRaw as $p) {
            if (isset($p['name']) && !empty($p['name'])) {
                $pppProfiles[] = $p['name'];
            }
        }
    }
    
    $pppProfiles = array_unique($pppProfiles);
    sort($pppProfiles);
    
} catch (\Throwable $e) {
    $mtConnected = false;
    $mtError = $e->getMessage();
}

// ============================================================================
// 4. HANDLE POST
// ============================================================================
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    
    if ($branchMode === 'auto') {
        $finalBranchId = $autoBranchId;
    } else {
        $finalBranchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    }
    
    $pppoeUsername = '';
    $pppoePassword = '';
    $pppoeService = 'pppoe';
    $pppoeProfile = 'default';
    $useExistingSecret = false;
    
    if (isset($_POST['use_existing_secret']) && $_POST['use_existing_secret'] === '1') {
        $useExistingSecret = true;
        $pppoeUsername = $_POST['pppoe_username_existing'] ?? '';
        $pppoePassword = $_POST['pppoe_password_existing'] ?? '';
    } else {
        $pppoeUsername = $_POST['pppoe_username'] ?? '';
        $pppoePassword = $_POST['pppoe_password'] ?? '';
        $pppoeService = $_POST['pppoe_service'] ?? 'pppoe';
        $pppoeProfile = $_POST['pppoe_profile'] ?? 'default';
    }
    
    try {
        $result = Customer::create([
            'branch_id' => $finalBranchId,
            'name' => $_POST['name'],
            'pppoe_username' => $pppoeUsername,
            'pppoe_password' => $pppoePassword,
            'pppoe_service' => $pppoeService,
            'pppoe_profile' => $pppoeProfile,
            'package_id' => $_POST['package_id'],
            'phone' => $_POST['phone'],
            'email' => $_POST['email'] ?? null,
            'address' => $_POST['address'] ?? null,
            'ip_address' => $_POST['ip_address'] ?? null,
            'due_day' => (int)($_POST['due_day'] ?? 3),
            'use_existing_secret' => $useExistingSecret ? 1 : 0
        ]);
        
        if ($result['success']) {
            $branchLabel = $finalBranchId ? $userBranchName : 'Pusat';
            logActivity(currentUserId(), 'add_customer', 
                "Tambah pelanggan: {$_POST['name']} ke cabang {$branchLabel}", 
                'customer', $result['id']);
            
            $syncMsg = $result['synced'] ? 'dan berhasil disinkronkan ke MikroTik' : 'tapi GAGAL sync ke MikroTik';
            redirect('/admin/customers.php', "✅ Pelanggan berhasil ditambahkan ke <strong>{$branchLabel}</strong> $syncMsg");
        } else {
            $error = $result['error'];
        }
    } catch (\Throwable $e) {
        $error = 'Error: ' . $e->getMessage();
    }
}

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

<style>
/* === PAGE TITLE === */
.page-title {
    font-size: 1.4rem;
    font-weight: 700;
    color: #003D7A;
    margin: 0 0 12px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-title i {
    color: #0066CC;
}

/* === ALERT MODERN === */
.alert-modern {
    padding: 12px 16px;
    border-radius: 10px;
    margin-bottom: 12px;
    display: flex;
    align-items: flex-start;
    gap: 10px;
    font-size: 0.88rem;
    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.1rem;
    margin-top: 2px;
    flex-shrink: 0;
}

/* === FORM CARD === */
.form-card {
    background: white;
    border-radius: 14px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
}

.form-card-header {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 600;
    font-size: 0.95rem;
}

.form-card-body {
    padding: 16px 20px;
}

/* === SECTION DIVIDER === */
.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;
}

.section-title .section-badge {
    margin-left: auto;
    font-size: 0.7rem;
    padding: 2px 8px;
    background: #e3f2fd;
    color: #1565c0;
    border-radius: 10px;
    font-weight: 600;
}

/* === FORM GRID === */
.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 12px;
}

.form-grid.single {
    grid-template-columns: 1fr;
}

.form-group {
    margin: 0;
}

.form-label-modern {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 600;
    color: #003D7A;
    margin-bottom: 6px;
    font-size: 0.82rem;
}

.form-label-modern i {
    color: #0066CC;
    font-size: 0.9rem;
}

.form-label-modern .required {
    color: #DC3545;
    margin-left: 2px;
}

.form-control-modern,
.form-select-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e8f4f8;
    border-radius: 10px;
    font-size: 0.88rem;
    transition: all 0.3s ease;
    background: #f8fafc;
    font-family: inherit;
    box-sizing: border-box;
}

.form-control-modern:focus,
.form-select-modern:focus {
    outline: none;
    border-color: #0066CC;
    background: white;
    box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1);
}

textarea.form-control-modern {
    resize: vertical;
    min-height: 50px;
}

.form-hint {
    display: block;
    margin-top: 4px;
    font-size: 0.72rem;
    color: #999;
    display: flex;
    align-items: center;
    gap: 3px;
}

/* === RADIO TOGGLE === */
.secret-toggle {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 12px;
}

.secret-option {
    position: relative;
}

.secret-option input[type="radio"] {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.secret-option label {
    display: block;
    padding: 10px 12px;
    border: 2px solid #e8f4f8;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f8fafc;
    font-size: 0.82rem;
    font-weight: 600;
    color: #003D7A;
}

.secret-option label:hover {
    border-color: #0066CC;
    background: #eef5fc;
}

.secret-option input[type="radio"]:checked + label {
    border-color: #0066CC;
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    color: #003D7A;
    box-shadow: 0 2px 8px rgba(0, 102, 204, 0.15);
}

.secret-option-title {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 2px;
}

.secret-option-title i {
    color: #0066CC;
    font-size: 1rem;
}

.secret-option-desc {
    font-size: 0.72rem;
    color: #666;
    font-weight: 400;
    margin-top: 2px;
}

/* === BUTTONS === */
.btn-modern {
    padding: 10px 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: 6px;
    text-decoration: none;
}

.btn-modern.primary {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3);
}

.btn-modern.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 102, 204, 0.4);
}

.btn-modern.secondary {
    background: white;
    color: #666;
    border: 2px solid #e8f4f8;
}

.btn-modern.secondary:hover {
    background: #f8fafc;
    border-color: #0066CC;
    color: #0066CC;
}

.btn-group-modern {
    display: flex;
    gap: 10px;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px dashed #e8f4f8;
}

/* === INFO BOX === */
.info-box {
    background: #e3f2fd;
    border-left: 3px solid #0066CC;
    padding: 10px 12px;
    border-radius: 8px;
    font-size: 0.8rem;
    color: #1565c0;
    margin-top: 8px;
    display: flex;
    align-items: flex-start;
    gap: 8px;
}

.info-box i {
    margin-top: 2px;
    flex-shrink: 0;
}

.warning-box {
    background: #fff8e1;
    border-left: 3px solid #FF9900;
    padding: 10px 12px;
    border-radius: 8px;
    font-size: 0.8rem;
    color: #f57c00;
    margin-top: 8px;
    display: flex;
    align-items: flex-start;
    gap: 8px;
}

.warning-box i {
    margin-top: 2px;
    flex-shrink: 0;
}

/* === RESPONSIVE - MOBILE ONLY === */
@media (max-width: 768px) {
    .main-content {
        padding: 12px;
    }
    
    .page-title {
        font-size: 1.2rem;
    }
    
    .form-card-body {
        padding: 14px 16px;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .secret-toggle {
        grid-template-columns: 1fr;
    }
    
    .btn-group-modern {
        flex-direction: column;
    }
    
    .btn-modern {
        width: 100%;
        padding: 11px;
    }
    
    .form-control-modern,
    .form-select-modern {
        padding: 10px 12px;
        font-size: 0.9rem;
    }
}

@media (max-width: 480px) {
    .main-content {
        padding: 10px;
    }
    
    .page-title {
        font-size: 1.1rem;
    }
    
    .form-card-header {
        padding: 12px 16px;
        font-size: 0.9rem;
    }
    
    .form-card-body {
        padding: 12px 14px;
    }
    
    .form-section {
        margin-bottom: 12px;
        padding-bottom: 12px;
    }
    
    .section-title {
        font-size: 0.88rem;
    }
    
    .secret-option label {
        padding: 8px 10px;
        font-size: 0.8rem;
    }
    
    .form-label-modern {
        font-size: 0.8rem;
    }
}
</style>

<div class="main-content">
    <!-- Navbar Modern - Burger HANYA muncul di mobile -->
    <div class="navbar-modern">
        <div class="navbar-left">
            <!-- Burger icon: hidden di desktop, tampil di mobile -->
            <button class="burger-btn" onclick="toggleSidebar()">
                <i class="bi bi-list"></i>
            </button>
            <div>
                <h1 class="navbar-title">Tambah Pelanggan</h1>
                <p class="navbar-subtitle">
                    <?php if ($branchMode === 'auto'): ?>
                        <i class="bi bi-<?= $isSuperAdmin ? 'shield-check' : 'building' ?>"></i> 
                        <?= htmlspecialchars($autoBranchLabel) ?>
                    <?php else: ?>
                        Pilih cabang manual
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="navbar-right">
            <?php if ($isSuperAdmin): ?>
                <span class="navbar-badge">
                    <i class="bi bi-shield-check"></i> Super Admin
                </span>
            <?php elseif ($isBranchAdmin): ?>
                <span class="navbar-badge">
                    <i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?>
                </span>
            <?php else: ?>
                <span class="navbar-badge">
                    <i class="bi bi-person"></i> Staff
                </span>
            <?php endif; ?>
        </div>
    </div>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <h2 class="page-title">
            <i class="bi bi-person-plus-fill"></i>
            <span>Tambah Pelanggan Baru</span>
        </h2>

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

        <?php if (!$mtConnected): ?>
            <div class="alert-modern warning">
                <i class="bi bi-exclamation-triangle-fill"></i>
                <div>
                    <strong>MikroTik tidak terhubung.</strong>
                    <?php if (!empty($mtError)): ?>
                        <br><small><?= htmlspecialchars($mtError) ?></small>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($branchMode === 'auto'): ?>
            <div class="alert-modern info">
                <i class="bi bi-info-circle-fill"></i>
                <div>
                    <?php if ($isSuperAdmin): ?>
                        Pelanggan baru akan otomatis ditambahkan ke <strong>Pusat</strong>.
                    <?php else: ?>
                        Pelanggan baru akan otomatis ditambahkan ke cabang <strong><?= htmlspecialchars($userBranchName) ?></strong>.
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- FORM CARD -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="bi bi-person-plus-fill"></i>
                <span>Form Data Pelanggan</span>
            </div>
            <div class="form-card-body">
                <form method="POST" id="customerForm">
                    <?= csrfField() ?>
                    
                    <!-- SECTION 1: DATA PELANGGAN -->
                    <div class="form-section">
                        <h3 class="section-title">
                            <i class="bi bi-person-fill"></i>
                            <span>Data Pelanggan</span>
                        </h3>
                        
                        <?php if ($branchMode === 'manual'): ?>
                        <div class="form-grid single">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-building"></i>
                                    Cabang <span class="required">*</span>
                                </label>
                                <select name="branch_id" class="form-select-modern" required>
                                    <option value="">-- Pilih Cabang --</option>
                                    <option value="">Pusat</option>
                                    <?php foreach ($branches as $b): ?>
                                        <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <?php else: ?>
                            <input type="hidden" name="branch_id" value="<?= $autoBranchId ?? '' ?>">
                        <?php endif; ?>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-person"></i>
                                    Nama Lengkap <span class="required">*</span>
                                </label>
                                <input type="text" name="name" class="form-control-modern" required placeholder="Nama pelanggan">
                            </div>
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-telephone"></i>
                                    No. HP <span class="required">*</span>
                                </label>
                                <input type="text" name="phone" class="form-control-modern" required placeholder="08xxx">
                            </div>
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-envelope"></i>
                                    Email
                                </label>
                                <input type="email" name="email" class="form-control-modern" placeholder="email@domain.com">
                            </div>
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-calendar-event"></i>
                                    Jatuh Tempo <span class="required">*</span>
                                </label>
                                <select name="due_day" class="form-select-modern" required>
                                    <?php for ($i = 1; $i <= 28; $i++): ?>
                                        <option value="<?= $i ?>" <?= $i === 3 ? 'selected' : '' ?>>Tanggal <?= $i ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-grid single">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-geo-alt"></i>
                                    Alamat
                                </label>
                                <textarea name="address" class="form-control-modern" rows="2" placeholder="Alamat lengkap pelanggan"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- SECTION 2: PPPoE CONFIGURATION -->
                    <div class="form-section">
                        <h3 class="section-title">
                            <i class="bi bi-router-fill"></i>
                            <span>Konfigurasi PPPoE</span>
                            <span class="section-badge"><?= $mtConnected ? '🟢 MikroTik OK' : '🔴 Offline' ?></span>
                        </h3>
                        
                        <div class="secret-toggle">
                            <div class="secret-option">
                                <input type="radio" name="secret_option" id="secret_new" value="new" checked onchange="toggleSecretOption()">
                                <label for="secret_new">
                                    <div class="secret-option-title">
                                        <i class="bi bi-plus-circle-fill"></i>
                                        <span>Buat Secret Baru</span>
                                    </div>
                                    <div class="secret-option-desc">Buat PPPoE secret baru di MikroTik</div>
                                </label>
                            </div>
                            <div class="secret-option">
                                <input type="radio" name="secret_option" id="secret_existing" value="existing" onchange="toggleSecretOption()">
                                <label for="secret_existing">
                                    <div class="secret-option-title">
                                        <i class="bi bi-link-45deg"></i>
                                        <span>Pakai Secret Lama</span>
                                    </div>
                                    <div class="secret-option-desc">Gunakan secret yang sudah ada</div>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Option: New Secret -->
                        <div id="new_secret_fields">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-person-badge"></i>
                                        Username PPPoE <span class="required">*</span>
                                    </label>
                                    <input type="text" name="pppoe_username" id="pppoe_username_new" class="form-control-modern" placeholder="client001">
                                </div>
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-key-fill"></i>
                                        Password PPPoE <span class="required">*</span>
                                    </label>
                                    <input type="text" name="pppoe_password" id="pppoe_password_new" class="form-control-modern" placeholder="password123">
                                </div>
                            </div>
                            
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-broadcast"></i>
                                        Service <span class="required">*</span>
                                    </label>
                                    <input type="text" name="pppoe_service" class="form-control-modern" value="pppoe" readonly style="background: #e8f4f8;">
                                </div>
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-sliders"></i>
                                        PPP Profile <span class="required">*</span>
                                    </label>
                                    <select name="pppoe_profile" id="pppoe_profile_new" class="form-select-modern" required>
                                        <option value="">-- Pilih Profile --</option>
                                        <?php foreach ($pppProfiles as $profile): ?>
                                            <option value="<?= htmlspecialchars($profile) ?>"><?= htmlspecialchars($profile) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (empty($pppProfiles)): ?>
                                        <div class="warning-box">
                                            <i class="bi bi-exclamation-triangle-fill"></i>
                                            <span>Tidak ada PPP Profile di MikroTik</span>
                                        </div>
                                    <?php else: ?>
                                        <small class="form-hint">
                                            <i class="bi bi-info-circle"></i>
                                            <?= count($pppProfiles) ?> profiles tersedia
                                        </small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Option: Existing Secret -->
                        <div id="existing_secret_fields" style="display: none;">
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-list-check"></i>
                                        Pilih Secret <span class="required">*</span>
                                    </label>
                                    <select name="pppoe_username_existing" id="pppoe_username_existing" class="form-select-modern">
                                        <option value="">-- Pilih Secret --</option>
                                        <?php foreach ($existingSecrets as $s): ?>
                                            <option value="<?= htmlspecialchars($s['name']) ?>" <?= $s['disabled'] ? 'disabled' : '' ?>>
                                                <?= htmlspecialchars($s['name']) ?> <?= $s['disabled'] ? '(Disabled)' : '' ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="form-hint">
                                        <i class="bi bi-info-circle"></i>
                                        <?= count($existingSecrets) ?> secrets tersedia
                                    </small>
                                </div>
                                <div class="form-group">
                                    <label class="form-label-modern">
                                        <i class="bi bi-key-fill"></i>
                                        Password <span class="required">*</span>
                                    </label>
                                    <input type="text" name="pppoe_password_existing" id="pppoe_password_existing" class="form-control-modern" placeholder="Samakan dengan di MikroTik">
                                </div>
                            </div>
                            <input type="hidden" name="use_existing_secret" id="use_existing_flag" value="0">
                            <div class="info-box">
                                <i class="bi bi-info-circle-fill"></i>
                                <span>Sistem akan meng-enable secret ini. Pastikan password benar.</span>
                            </div>
                        </div>
                    </div>

                    <!-- SECTION 3: PAKET INTERNET -->
                    <div class="form-section">
                        <h3 class="section-title">
                            <i class="bi bi-box-fill"></i>
                            <span>Paket Internet</span>
                        </h3>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-speedometer2"></i>
                                    Paket <span class="required">*</span>
                                </label>
                                <select name="package_id" class="form-select-modern" required>
                                    <?php foreach ($packages as $p): ?>
                                        <option value="<?= $p['id'] ?>">
                                            <?= htmlspecialchars($p['name']) ?> - Rp <?= number_format($p['price']) ?>
                                            <?= $p['speed'] ? '(' . htmlspecialchars($p['speed']) . ')' : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="form-group">
                                <label class="form-label-modern">
                                    <i class="bi bi-hdd-network"></i>
                                    IP Address (Opsional)
                                </label>
                                <input type="text" name="ip_address" class="form-control-modern" placeholder="192.168.1.100">
                                <small class="form-hint">
                                    <i class="bi bi-info-circle"></i>
                                    Kosongkan jika menggunakan IP dinamis
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- BUTTONS -->
                    <div class="btn-group-modern">
                        <button type="submit" class="btn-modern primary" onclick="prepareForm()">
                            <i class="bi bi-save-fill"></i>
                            <span>Simpan & Sinkronkan</span>
                        </button>
                        <a href="/admin/customers.php" class="btn-modern secondary">
                            <i class="bi bi-x-circle"></i>
                            <span>Batal</span>
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- End Content Wrapper -->
</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 toggleSecretOption() {
    const isNew = document.getElementById('secret_new').checked;
    document.getElementById('new_secret_fields').style.display = isNew ? 'block' : 'none';
    document.getElementById('existing_secret_fields').style.display = isNew ? 'none' : 'block';
    
    document.getElementById('pppoe_username_new').required = isNew;
    document.getElementById('pppoe_password_new').required = isNew;
    document.getElementById('pppoe_profile_new').required = isNew;
    
    document.getElementById('pppoe_username_existing').required = !isNew;
    document.getElementById('pppoe_password_existing').required = !isNew;
}

function prepareForm() {
    const isNew = document.getElementById('secret_new').checked;
    document.getElementById('use_existing_flag').value = isNew ? '0' : '1';
}

toggleSecretOption();
</script>

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