<?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('branch_admin');
$pageTitle = 'Tambah Pelanggan';

$db = db();

// Ambil info 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');
}

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

// Ambil data MikroTik
$existingSecrets = [];
$pppProfiles = [];
$mtConnected = false;
$mtError = '';

try {
    $mt = new MikroTik($userBranchId);
    $mt->connect();
    $mtConnected = true;
    
    $secrets = $mt->getAllSecrets();
    foreach ($secrets as $s) {
        $existingSecrets[] = [
            'name' => $s['name'],
            'disabled' => isset($s['disabled']) && $s['disabled'] === 'true'
        ];
    }
    
    $profilesRaw = $mt->getPPPProfiles();
    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();
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $pppoeUsername = '';
    $pppoePassword = '';
    $pppoeService = 'pppoe';
    $pppoeProfile = 'default';
    $useExisting = false;
    
    if (isset($_POST['use_existing_secret']) && $_POST['use_existing_secret'] === '1') {
        $useExisting = 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' => $userBranchId,
            '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,
            'installation_date' => $_POST['installation_date'] ?? date('Y-m-d'),
            'use_existing_secret' => $useExisting ? 1 : 0
        ]);
        
        if ($result['success']) {
            logActivity($currentUserId, 'add_customer', 
                "Tambah pelanggan: {$_POST['name']} di cabang {$userBranchName} | " .
                "Instalasi: " . ($_POST['installation_date'] ?? date('Y-m-d')) . " | " .
                "Tagihan pertama: #{$result['bill_number']} (JT: {$result['first_due_date']})"
            );
            
            $syncMsg = $result['synced'] ? 'dan sinkron ke MikroTik berhasil' : 'tapi GAGAL sync ke MikroTik';
            $billMsg = "Tagihan pertama <strong>#{$result['bill_number']}</strong> otomatis digenerate (Jatuh tempo: " . date('d/m/Y', strtotime($result['first_due_date'])) . ")";
            
            redirect('/branch/customers.php', 
                "✅ Pelanggan ditambahkan ke cabang <strong>$userBranchName</strong> $syncMsg. $billMsg");
        } else {
            $error = $result['error'];
        }
    } catch (\Throwable $e) {
        $error = 'Error: ' . $e->getMessage();
    }
}

// Default tanggal instalasi = hari ini
$defaultInstallationDate = date('Y-m-d');

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

<style>
/* === NAVBAR MODERN === */
.navbar-modern {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    padding: 15px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    position: sticky;
    top: 0;
    z-index: 1000;
}

.navbar-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.burger-btn {
    background: rgba(255,255,255,0.15);
    border: none;
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.3rem;
    transition: all 0.3s ease;
}

.burger-btn:hover {
    background: rgba(255,255,255,0.25);
    transform: scale(1.05);
}

.navbar-title {
    color: white;
    font-size: 1.2rem;
    font-weight: 700;
    margin: 0;
}

.navbar-subtitle {
    color: rgba(255,255,255,0.85);
    font-size: 0.78rem;
    margin: 0;
}

.navbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
}

.navbar-badge {
    background: rgba(255,255,255,0.2);
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.82rem;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

/* === MAIN CONTENT === */
.main-content {
    padding: 16px;
    max-width: 900px;
    margin: 0 auto;

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

.page-title {
    font-size: 1.4rem;
    font-weight: 700;
    color: #003D7A;
    margin: 0 0 12px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.page-title i {
    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;
}

/* === 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: flex;
    align-items: center;
    gap: 3px;
    margin-top: 4px;
    font-size: 0.72rem;
    color: #999;
}

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

/* === INFO/WARNING 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;
}

/* === ⭐ INSTALLATION DATE PREVIEW === */
.installation-preview {
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    border: 2px solid #a5d6a7;
    border-radius: 12px;
    padding: 14px 16px;
    margin-top: 12px;
    margin-bottom: 12px;
}

.installation-preview-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.85rem;
    font-weight: 700;
    color: #2e7d32;
    margin-bottom: 10px;
}

.installation-preview-title i {
    font-size: 1.1rem;
}

.preview-grid {
    display: grid;
    grid-template-columns: 1fr auto 1fr auto 1fr;
    gap: 8px;
    align-items: center;
}

.preview-item {
    text-align: center;
    padding: 8px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

.preview-item-label {
    font-size: 0.68rem;
    color: #666;
    text-transform: uppercase;
    font-weight: 600;
    letter-spacing: 0.3px;
    margin-bottom: 4px;
}

.preview-item-value {
    font-size: 0.88rem;
    font-weight: 700;
    color: #003D7A;
}

.preview-item.installation .preview-item-value {
    color: #0066CC;
}

.preview-item.due-date .preview-item-value {
    color: #f57c00;
}

.preview-item.active-until .preview-item-value {
    color: #2e7d32;
}

.preview-arrow {
    font-size: 1.2rem;
    color: #999;
    text-align: center;
}

.preview-note {
    margin-top: 10px;
    font-size: 0.75rem;
    color: #555;
    text-align: center;
    font-style: italic;
}

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

/* === RESPONSIVE === */
@media (max-width: 768px) {
    .navbar-modern {
        padding: 12px 15px;
    }
    
    .navbar-title {
        font-size: 1rem;
    }
    
    .navbar-subtitle, .navbar-badge {
        display: none;
    }
    
    .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;
    }
    
    /* Preview grid responsive */
    .preview-grid {
        grid-template-columns: 1fr;
        gap: 6px;
    }
    
    .preview-arrow {
        transform: rotate(90deg);
        font-size: 1rem;
    }
    
    .preview-item {
        padding: 6px;
    }
    
    .preview-item-value {
        font-size: 0.82rem;
    }
}

@media (max-width: 480px) {
    .navbar-modern {
        padding: 10px 12px;
    }
    
    .burger-btn {
        width: 36px;
        height: 36px;
        font-size: 1.1rem;
    }
    
    .navbar-title {
        font-size: 0.95rem;
    }
    
    .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;
    }
    
    .installation-preview {
        padding: 10px 12px;
    }
    
    .installation-preview-title {
        font-size: 0.8rem;
    }
}
</style>

<!-- Navbar -->

<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>
            <h1 class="navbar-title">Tambah Pelanggan</h1>
            <p class="navbar-subtitle">
                <i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?>
            </p>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge">
            <i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?>
        </span>
    </div>
</div>    

    <?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; ?>



    <!-- 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>
                    
                    <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-geo-alt"></i>
                                Alamat
                            </label>
                            <input type="text" name="address" class="form-control-modern" placeholder="Alamat lengkap">
                        </div>
                    </div>
                </div>

                <!-- ⭐ SECTION 2: TANGGAL INSTALASI (BARU!) -->
                <div class="form-section">
                    <h3 class="section-title">
                        <i class="bi bi-calendar-check-fill"></i>
                        <span>Tanggal Instalasi</span>
                        <span class="section-badge">⚡ Auto Jatuh Tempo</span>
                    </h3>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-calendar-event"></i>
                                Tanggal Instalasi <span class="required">*</span>
                            </label>
                            <input type="date" name="installation_date" id="installation_date" 
                                   class="form-control-modern" 
                                   value="<?= htmlspecialchars($defaultInstallationDate) ?>" 
                                   max="<?= date('Y-m-d') ?>"
                                   required 
                                   onchange="updatePreview()">
                            <small class="form-hint">
                                <i class="bi bi-info-circle"></i>
                                Tanggal pemasangan internet pelanggan
                            </small>
                        </div>
                        <div class="form-group">
                            <label class="form-label-modern">
                                <i class="bi bi-calendar-x"></i>
                                Jatuh Tempo (Otomatis)
                            </label>
                            <input type="text" id="due_date_display" class="form-control-modern" 
                                   readonly style="background: #fff8e1; color: #f57c00; font-weight: 700; cursor: not-allowed;"
                                   value="<?= date('d/m/Y', strtotime('+1 month', strtotime($defaultInstallationDate))) ?>">
                            <small class="form-hint">
                                <i class="bi bi-lightning-charge"></i>
                                Otomatis = Tanggal Instalasi + 1 bulan
                            </small>
                        </div>
                    </div>
                    
                    <!-- ⭐ PREVIEW BOX -->
                    <div class="installation-preview" id="installationPreview">
                        <div class="installation-preview-title">
                            <i class="bi bi-eye-fill"></i>
                            <span>Preview Jadwal</span>
                        </div>
                        <div class="preview-grid">
                            <div class="preview-item installation">
                                <div class="preview-item-label">📅 Tanggal Instalasi</div>
                                <div class="preview-item-value" id="preview_installation">
                                    <?= date('d M Y', strtotime($defaultInstallationDate)) ?>
                                </div>
                            </div>
                            <div class="preview-arrow">
                                <i class="bi bi-arrow-right"></i>
                            </div>
                            <div class="preview-item due-date">
                                <div class="preview-item-label">⏰ Jatuh Tempo Pertama</div>
                                <div class="preview-item-value" id="preview_due_date">
                                    <?= date('d M Y', strtotime('+1 month', strtotime($defaultInstallationDate))) ?>
                                </div>
                            </div>
                            <div class="preview-arrow">
                                <i class="bi bi-arrow-right"></i>
                            </div>
                            <div class="preview-item active-until">
                                <div class="preview-item-label">✅ Masa Aktif Sampai</div>
                                <div class="preview-item-value" id="preview_active_until">
                                    <?= date('d M Y', strtotime('+1 month', strtotime($defaultInstallationDate))) ?>
                                </div>
                            </div>
                        </div>
                        <div class="preview-note" id="preview_note">
                            💡 Tagihan pertama akan otomatis digenerate. Pelanggan harus bayar sebelum tanggal jatuh tempo.
                        </div>
                    </div>
                </div>

                <!-- SECTION 3: 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 4: 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="/branch/customers.php" class="btn-modern secondary">
                        <i class="bi bi-x-circle"></i>
                        <span>Batal</span>
                    </a>
                </div>
            </form>
        </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 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;
}

/**
 * ⭐ Update preview saat tanggal instalasi berubah
 */
function updatePreview() {
    const inputDate = document.getElementById('installation_date').value;
    
    if (!inputDate) return;
    
    const installDate = new Date(inputDate);
    
    // Jatuh tempo = instalasi + 1 bulan
    const dueDate = new Date(installDate);
    dueDate.setMonth(dueDate.getMonth() + 1);
    
    // Active until = jatuh tempo (hari yang sama bulan depan)
    const activeUntil = new Date(dueDate);
    
    // Format tanggal dalam Bahasa Indonesia
    const bulanIndonesia = [
        'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun',
        'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'
    ];
    
    const bulanIndonesiaFull = [
        'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
        'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
    ];
    
    const formatShort = (d) => {
        return `${d.getDate()} ${bulanIndonesia[d.getMonth()]} ${d.getFullYear()}`;
    };
    
    const formatFull = (d) => {
        const hari = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
        return `${hari[d.getDay()]}, ${d.getDate()} ${bulanIndonesiaFull[d.getMonth()]} ${d.getFullYear()}`;
    };
    
    // Update preview items
    document.getElementById('preview_installation').textContent = formatShort(installDate);
    document.getElementById('preview_due_date').textContent = formatShort(dueDate);
    document.getElementById('preview_active_until').textContent = formatShort(activeUntil);
    
    // Update input jatuh tempo (readonly)
    const dueDay = dueDate.getDate().toString().padStart(2, '0');
    const dueMonth = (dueDate.getMonth() + 1).toString().padStart(2, '0');
    const dueYear = dueDate.getFullYear();
    document.getElementById('due_date_display').value = `${dueDay}/${dueMonth}/${dueYear}`;
    
    // Update note
    const daysUntilDue = Math.ceil((dueDate - new Date()) / (1000 * 60 * 60 * 24));
    let noteText = '';
    
    if (daysUntilDue > 30) {
        noteText = `💡 Tagihan pertama akan otomatis digenerate. Pelanggan punya ~${daysUntilDue} hari untuk pembayaran pertama.`;
    } else if (daysUntilDue > 0) {
        noteText = `⚠️ Jatuh tempo ${daysUntilDue} hari lagi. Tagihan pertama akan otomatis digenerate.`;
    } else {
        noteText = `⚠️ Jatuh tempo sudah lewat! Tagihan tetap digenerate, segera proses pembayaran.`;
    }
    
    document.getElementById('preview_note').textContent = noteText;
}

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

// Initialize
toggleSecretOption();
updatePreview();
</script>

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