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

requireRole('super_admin');
$pageTitle = 'Manajemen Paket Internet (Pusat)';

$db = db();

// ============================================================================
// 1. AMBIL DAFTAR CABANG
// ============================================================================
$branches = Branch::all();

// ============================================================================
// 2. HANDLE ACTIONS
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    try {
        // TAMBAH PAKET BARU
        if ($action === 'add') {
            $name = trim($_POST['name'] ?? '');
            $price = (float)($_POST['price'] ?? 0);
            $speed = trim($_POST['speed'] ?? '');
            $pppProfile = trim($_POST['ppp_profile'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
            
            if (empty($name)) throw new Exception('Nama paket wajib diisi');
            if ($price <= 0) throw new Exception('Harga harus lebih dari 0');
            if (empty($speed)) throw new Exception('Kecepatan wajib diisi');
            if (empty($pppProfile)) throw new Exception('PPP Profile wajib dipilih');
            
            // Cek duplikasi nama (dalam scope cabang yang sama)
            if ($branchId === null) {
                $check = $db->prepare("SELECT id FROM packages WHERE name = ? AND branch_id IS NULL");
                $check->execute([$name]);
            } else {
                $check = $db->prepare("SELECT id FROM packages WHERE name = ? AND (branch_id = ? OR branch_id IS NULL)");
                $check->execute([$name, $branchId]);
            }
            if ($check->fetch()) throw new Exception("Paket '{$name}' sudah ada");
            
            $stmt = $db->prepare("
                INSERT INTO packages (name, price, speed, ppp_profile, description, branch_id, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())
            ");
            $stmt->execute([$name, $price, $speed, $pppProfile, $description, $branchId]);
            
            $branchLabel = $branchId ? getBranchName($branchId) : 'Global (Semua Cabang)';
            logActivity(currentUserId(), 'add_package', "Tambah paket: {$name} untuk {$branchLabel}");
            redirect('/admin/packages.php', "✅ Paket '{$name}' berhasil ditambahkan untuk <strong>{$branchLabel}</strong>");
        }
        
        // EDIT PAKET
        if ($action === 'edit') {
            $id = (int)($_POST['id'] ?? 0);
            $name = trim($_POST['name'] ?? '');
            $price = (float)($_POST['price'] ?? 0);
            $speed = trim($_POST['speed'] ?? '');
            $pppProfile = trim($_POST['ppp_profile'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $branchId = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
            
            if ($id <= 0) throw new Exception('ID paket tidak valid');
            if (empty($name)) throw new Exception('Nama paket wajib diisi');
            if ($price <= 0) throw new Exception('Harga harus lebih dari 0');
            if (empty($speed)) throw new Exception('Kecepatan wajib diisi');
            if (empty($pppProfile)) throw new Exception('PPP Profile wajib dipilih');
            
            $stmt = $db->prepare("
                UPDATE packages 
                SET name = ?, price = ?, speed = ?, ppp_profile = ?, description = ?, branch_id = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$name, $price, $speed, $pppProfile, $description, $branchId, $id]);
            
            logActivity(currentUserId(), 'edit_package', "Edit paket #$id: {$name}");
            redirect('/admin/packages.php', "✅ Paket berhasil diupdate");
        }
        
        // TOGGLE STATUS
        if ($action === 'toggle_status') {
            $id = (int)($_POST['id'] ?? 0);
            $newStatus = $_POST['new_status'] ?? 'inactive';
            
            if ($id <= 0) throw new Exception('ID paket tidak valid');
            
            $stmt = $db->prepare("UPDATE packages SET status = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$newStatus, $id]);
            
            logActivity(currentUserId(), 'toggle_package', "Toggle paket #$id ke {$newStatus}");
            redirect('/admin/packages.php', "✅ Status paket berhasil diubah");
        }
        
        // HAPUS PAKET
        if ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);
            
            if ($id <= 0) throw new Exception('ID paket tidak valid');
            
            $check = $db->prepare("SELECT COUNT(*) as count FROM customers WHERE package_id = ?");
            $check->execute([$id]);
            $usage = $check->fetch()['count'] ?? 0;
            
            if ($usage > 0) {
                throw new Exception("Paket tidak bisa dihapus karena sedang digunakan oleh {$usage} pelanggan.");
            }
            
            $stmt = $db->prepare("DELETE FROM packages WHERE id = ?");
            $stmt->execute([$id]);
            
            logActivity(currentUserId(), 'delete_package', "Hapus paket #$id");
            redirect('/admin/packages.php', "✅ Paket berhasil dihapus");
        }
        
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = '❌ ' . $e->getMessage();
    }
}

// ============================================================================
// 3. LOAD DATA PAKET
// ============================================================================
$packages = [];
try {
    $stmt = $db->query("
        SELECT p.*, b.name as branch_name,
            (SELECT COUNT(*) FROM customers WHERE package_id = p.id) as customer_count
        FROM packages p
        LEFT JOIN branches b ON p.branch_id = b.id
        ORDER BY p.branch_id IS NULL DESC, b.name ASC, p.price ASC
    ");
    $packages = $stmt->fetchAll();
} catch (\Throwable $e) {}

// Filter
$filterBranch = $_GET['branch'] ?? '';
$filterStatus = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

if ($filterBranch || $filterStatus || $search) {
    $filtered = [];
    foreach ($packages as $p) {
        if ($filterBranch === 'global' && $p['branch_id'] !== null) continue;
        if ($filterBranch && $filterBranch !== 'global' && $p['branch_id'] != $filterBranch) continue;
        if ($filterStatus && $p['status'] !== $filterStatus) continue;
        if ($search && stripos($p['name'] . ' ' . $p['ppp_profile'] . ' ' . $p['speed'], $search) === false) continue;
        $filtered[] = $p;
    }
    $packages = $filtered;
}

// Stats
$totalPackages = count($packages);
$activePackages = count(array_filter($packages, fn($p) => $p['status'] === 'active'));
$globalPackages = count(array_filter($packages, fn($p) => $p['branch_id'] === null));
$branchPackages = $totalPackages - $globalPackages;
$totalCustomers = array_sum(array_column($packages, 'customer_count'));
$totalRevenue = array_sum(array_map(fn($p) => $p['price'] * $p['customer_count'], $packages));

// Ambil error flash
$flashError = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_error']);

// Helper function
function getBranchName($branchId) {
    global $branches;
    foreach ($branches as $b) {
        if ($b['id'] == $branchId) return $b['name'];
    }
    return 'Unknown';
}

// Ambil data untuk edit
$editPackage = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    foreach ($packages as $p) {
        if ($p['id'] === $editId) {
            $editPackage = $p;
            break;
        }
    }
}

// ============================================================================
// 4. AMBIL PPP PROFILES DARI MIKROTIK (untuk modal tambah/edit)
// ============================================================================
$pppProfilesByBranch = [];
$mtErrors = [];

// Ambil dari MikroTik pusat (jika ada)
try {
    $mt = new MikroTik();
    $mt->connect();
    $profilesRaw = $mt->getPPPProfiles();
    $profiles = [];
    foreach ($profilesRaw as $p) {
        if (isset($p['name']) && !empty($p['name'])) {
            $profiles[] = $p['name'];
        }
    }
    $pppProfilesByBranch[0] = array_unique($profiles);
} catch (\Throwable $e) {
    $mtErrors[0] = $e->getMessage();
}

// Ambil dari setiap cabang
foreach ($branches as $b) {
    try {
        $mt = new MikroTik($b['id']);
        $mt->connect();
        $profilesRaw = $mt->getPPPProfiles();
        $profiles = [];
        foreach ($profilesRaw as $p) {
            if (isset($p['name']) && !empty($p['name'])) {
                $profiles[] = $p['name'];
            }
        }
        $pppProfilesByBranch[$b['id']] = array_unique($profiles);
    } catch (\Throwable $e) {
        $mtErrors[$b['id']] = $e->getMessage();
        $pppProfilesByBranch[$b['id']] = [];
    }
}

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

<div class="main-content">
  <!-- Top Bar -->
  <div class="top-bar">
    <div class="top-bar-left">
      <button class="menu-toggle" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
      <div>
        <h3>
          <i class="bi bi-box-seam me-2"></i>Manajemen Paket Internet
          <span class="badge bg-danger ms-2"><i class="bi bi-shield-check"></i> Pusat</span>
        </h3>
        <small class="text-muted">
          Total: <?= $totalPackages ?> paket | 
          Aktif: <span class="text-success"><?= $activePackages ?></span> | 
          Global: <span class="text-info"><?= $globalPackages ?></span> | 
          Per Cabang: <span class="text-warning"><?= $branchPackages ?></span> | 
          Total Pelanggan: <span class="text-primary"><?= $totalCustomers ?></span> |
          Potensi Pendapatan: <strong class="text-success">Rp <?= number_format($totalRevenue) ?></strong>
        </small>
      </div>
    </div>
    <div class="top-bar-right">
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#packageModal" onclick="resetForm()">
        <i class="bi bi-plus-lg"></i> <span class="d-none d-md-inline">Tambah Paket</span>
      </button>
    </div>
  </div>

  <?= flashMessage() ?>
  
  <?php if ($flashError): ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <?= htmlspecialchars($flashError) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <!-- Info -->
  <div class="alert alert-info alert-dismissible fade show">
    <i class="bi bi-info-circle"></i> 
    <strong>Mode Pusat:</strong> Anda dapat membuat paket <strong>Global</strong> (berlaku untuk semua cabang) 
    atau paket <strong>Per Cabang</strong> (hanya untuk cabang tertentu). Setiap paket diintegrasikan dengan 
    <strong>PPP Profile</strong> dari MikroTik cabang yang dipilih.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>

  <!-- Filter -->
  <div class="card mb-3">
    <div class="card-body">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label small mb-1">Cari</label>
          <input type="text" name="search" class="form-control form-control-sm" 
                 value="<?= htmlspecialchars($search) ?>" placeholder="Nama paket, profile, speed...">
        </div>
        <div class="col-md-3">
          <label class="form-label small mb-1">Cabang</label>
          <select name="branch" class="form-select form-select-sm">
            <option value="">Semua (Global + Cabang)</option>
            <option value="global" <?= $filterBranch === 'global' ? 'selected' : '' ?>>🌐 Global Saja</option>
            <?php foreach ($branches as $b): ?>
              <option value="<?= $b['id'] ?>" <?= $filterBranch == $b['id'] ? 'selected' : '' ?>>
                🏢 <?= htmlspecialchars($b['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Status</label>
          <select name="status" class="form-select form-select-sm">
            <option value="">Semua</option>
            <option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Aktif</option>
            <option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Nonaktif</option>
          </select>
        </div>
        <div class="col-md-3 d-flex gap-1">
          <button type="submit" class="btn btn-primary btn-sm flex-fill"><i class="bi bi-funnel"></i> Filter</button>
          <a href="/admin/packages.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-x-lg"></i></a>
        </div>
      </form>
    </div>
  </div>

  <!-- List Paket -->
  <?php if (empty($packages)): ?>
    <div class="card">
      <div class="card-body text-center py-5">
        <i class="bi bi-box-seam" style="font-size: 5rem; color: var(--text-muted);"></i>
        <h5 class="mt-3 text-muted">Belum ada paket internet</h5>
        <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#packageModal" onclick="resetForm()">
          <i class="bi bi-plus-lg"></i> Tambah Paket Pertama
        </button>
      </div>
    </div>
  <?php else: ?>
    <div class="row g-3">
      <?php foreach ($packages as $p): ?>
        <div class="col-md-6 col-xl-4">
          <div class="card h-100 <?= $p['status'] === 'active' ? 'border-success' : 'border-secondary' ?> shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center <?= $p['status'] === 'active' ? 'bg-success bg-opacity-10' : 'bg-secondary bg-opacity-10' ?>">
              <div>
                <strong class="fs-5"><?= htmlspecialchars($p['name']) ?></strong>
                <div class="mt-1">
                  <?php if ($p['branch_id'] === null): ?>
                    <span class="badge bg-info"><i class="bi bi-globe"></i> Global</span>
                  <?php else: ?>
                    <span class="badge bg-warning text-dark">
                      <i class="bi bi-building"></i> <?= htmlspecialchars($p['branch_name'] ?? 'Unknown') ?>
                    </span>
                  <?php endif; ?>
                  <?php if ($p['status'] === 'active'): ?>
                    <span class="badge bg-success">Aktif</span>
                  <?php else: ?>
                    <span class="badge bg-secondary">Nonaktif</span>
                  <?php endif; ?>
                </div>
              </div>
              <div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                  <i class="bi bi-three-dots-vertical"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li>
                    <a class="dropdown-item" href="#" onclick='editPackage(<?= json_encode($p) ?>)'>
                      <i class="bi bi-pencil me-2"></i>Edit
                    </a>
                  </li>
                  <li>
                    <?php if ($p['status'] === 'active'): ?>
                      <form method="POST" class="d-inline">
                        <?= csrfField() ?>
                        <input type="hidden" name="action" value="toggle_status">
                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                        <input type="hidden" name="new_status" value="inactive">
                        <button type="submit" class="dropdown-item" onclick="return confirm('Nonaktifkan paket ini?')">
                          <i class="bi bi-pause-circle me-2"></i>Nonaktifkan
                        </button>
                      </form>
                    <?php else: ?>
                      <form method="POST" class="d-inline">
                        <?= csrfField() ?>
                        <input type="hidden" name="action" value="toggle_status">
                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                        <input type="hidden" name="new_status" value="active">
                        <button type="submit" class="dropdown-item">
                          <i class="bi bi-play-circle me-2"></i>Aktifkan
                        </button>
                      </form>
                    <?php endif; ?>
                  </li>
                  <li><hr class="dropdown-divider"></li>
                  <li>
                    <form method="POST" class="d-inline">
                      <?= csrfField() ?>
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="id" value="<?= $p['id'] ?>">
                      <button type="submit" class="dropdown-item text-danger" 
                              onclick="return confirm('Yakin hapus paket <?= htmlspecialchars($p['name']) ?>?')">
                        <i class="bi bi-trash me-2"></i>Hapus
                      </button>
                    </form>
                  </li>
                </ul>
              </div>
            </div>
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                  <div class="text-muted small">Harga / bulan</div>
                  <div class="h3 mb-0 text-primary fw-bold">
                    Rp <?= number_format($p['price'], 0, ',', '.') ?>
                  </div>
                </div>
                <div class="text-end">
                  <div class="text-muted small">Kecepatan</div>
                  <div class="h4 mb-0 fw-bold">
                    <i class="bi bi-speedometer2 text-success"></i>
                    <?= htmlspecialchars($p['speed']) ?>
                  </div>
                </div>
              </div>
              
              <!-- PPP Profile Info -->
              <div class="alert alert-light border mb-3 py-2">
                <div class="d-flex align-items-center gap-2">
                  <i class="bi bi-router text-info fs-5"></i>
                  <div class="flex-grow-1">
                    <div class="text-muted small">PPP Profile (MikroTik)</div>
                    <div class="fw-semibold">
                      <?php if (!empty($p['ppp_profile'])): ?>
                        <code class="text-info"><?= htmlspecialchars($p['ppp_profile']) ?></code>
                      <?php else: ?>
                        <span class="text-muted fst-italic">Belum diintegrasikan</span>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
              </div>
              
              <?php if (!empty($p['description'])): ?>
                <div class="small text-muted mb-3">
                  <i class="bi bi-info-circle me-1"></i>
                  <?= htmlspecialchars($p['description']) ?>
                </div>
              <?php endif; ?>
              
              <!-- Customer Count & Revenue -->
              <div class="d-flex justify-content-between align-items-center pt-2 border-top">
                <div>
                  <small class="text-muted d-block">
                    <i class="bi bi-people"></i> 
                    <strong><?= $p['customer_count'] ?></strong> pelanggan
                  </small>
                  <small class="text-success d-block">
                    <i class="bi bi-cash"></i> 
                    Rp <?= number_format($p['price'] * $p['customer_count']) ?>/bln
                  </small>
                </div>
                <a href="/admin/customers.php?search=<?= urlencode($p['name']) ?>" 
                   class="btn btn-sm btn-outline-primary" title="Lihat pelanggan">
                  <i class="bi bi-eye"></i> Lihat
                </a>
              </div>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<!-- ============================================================================ -->
<!-- MODAL TAMBAH / EDIT PAKET -->
<!-- ============================================================================ -->
<div class="modal fade" id="packageModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="POST" id="packageForm">
      <?= csrfField() ?>
      <input type="hidden" name="action" id="formAction" value="add">
      <input type="hidden" name="id" id="packageId">
      
      <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title" id="modalTitle">
            <i class="bi bi-plus-circle me-2"></i>Tambah Paket Internet
          </h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <!-- Scope: Global atau Cabang -->
          <div class="mb-3">
            <label class="form-label fw-bold">
              <i class="bi bi-geo-alt me-1"></i>Scope Paket *
            </label>
            <select name="branch_id" id="pkgBranch" class="form-select" required onchange="updatePPPProfiles()">
              <option value="">🌐 Global (Berlaku untuk Semua Cabang)</option>
              <?php foreach ($branches as $b): ?>
                <option value="<?= $b['id'] ?>">🏢 <?= htmlspecialchars($b['name']) ?></option>
              <?php endforeach; ?>
            </select>
            <small class="text-muted">
              <strong>Global</strong> = paket bisa dipilih oleh semua cabang. 
              <strong>Per Cabang</strong> = paket hanya untuk cabang tertentu.
            </small>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label fw-bold">Nama Paket *</label>
              <input type="text" name="name" id="pkgName" class="form-control" required
                     placeholder="Contoh: Paket Silver 10 Mbps">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label fw-bold">Kecepatan *</label>
              <input type="text" name="speed" id="pkgSpeed" class="form-control" required
                     placeholder="Contoh: 10 Mbps / 3 Mbps">
            </div>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label fw-bold">Harga / Bulan (Rp) *</label>
              <input type="number" name="price" id="pkgPrice" class="form-control" required
                     min="0" step="1000" placeholder="150000">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label fw-bold">
                <i class="bi bi-router me-1"></i>PPP Profile (MikroTik) *
              </label>
              <select name="ppp_profile" id="pkgProfile" class="form-select" required>
                <option value="">-- Pilih PPP Profile --</option>
              </select>
              <small class="text-muted" id="profileHint">
                Pilih scope paket terlebih dahulu untuk melihat daftar profile.
              </small>
            </div>
          </div>
          
          <div class="mb-3">
            <label class="form-label fw-bold">Deskripsi (Opsional)</label>
            <textarea name="description" id="pkgDescription" class="form-control" rows="2"></textarea>
          </div>
          
          <!-- Warning jika MikroTik error -->
          <div id="mtWarning" class="alert alert-warning mb-0" style="display: none;">
            <i class="bi bi-exclamation-triangle"></i> 
            <strong>Peringatan:</strong> MikroTik untuk scope ini tidak terhubung. 
            PPP Profile tidak dapat dimuat. Anda tetap bisa menyimpan paket, tapi pastikan nama profile benar.
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-save"></i> <span id="submitText">Simpan Paket</span>
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

<script>
// Data PPP Profiles per cabang (dari PHP)
const pppProfilesByBranch = <?= json_encode($pppProfilesByBranch) ?>;
const mtErrors = <?= json_encode($mtErrors) ?>;

function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('active');
    document.getElementById('sidebarOverlay').classList.toggle('active');
}

function resetForm() {
    document.getElementById('packageForm').reset();
    document.getElementById('formAction').value = 'add';
    document.getElementById('packageId').value = '';
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-plus-circle me-2"></i>Tambah Paket Internet';
    document.getElementById('submitText').textContent = 'Simpan Paket';
    document.getElementById('pkgBranch').value = '';
    updatePPPProfiles();
}

function editPackage(pkg) {
    document.getElementById('formAction').value = 'edit';
    document.getElementById('packageId').value = pkg.id;
    document.getElementById('pkgName').value = pkg.name || '';
    document.getElementById('pkgSpeed').value = pkg.speed || '';
    document.getElementById('pkgPrice').value = pkg.price || '';
    document.getElementById('pkgDescription').value = pkg.description || '';
    
    // Set branch (null = global)
    document.getElementById('pkgBranch').value = pkg.branch_id || '';
    
    // Update dropdown PPP profiles dulu
    updatePPPProfiles();
    
    // Set profile setelah dropdown terisi
    setTimeout(() => {
        document.getElementById('pkgProfile').value = pkg.ppp_profile || '';
    }, 100);
    
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-pencil me-2"></i>Edit Paket: ' + pkg.name;
    document.getElementById('submitText').textContent = 'Update Paket';
    
    new bootstrap.Modal(document.getElementById('packageModal')).show();
}

function updatePPPProfiles() {
    const branchId = document.getElementById('pkgBranch').value;
    const profileSelect = document.getElementById('pkgProfile');
    const profileHint = document.getElementById('profileHint');
    const mtWarning = document.getElementById('mtWarning');
    
    // Clear current options
    profileSelect.innerHTML = '<option value="">-- Pilih PPP Profile --</option>';
    
    // Key untuk lookup: 0 = global, branch_id = cabang
    const key = branchId === '' ? 0 : branchId;
    const profiles = pppProfilesByBranch[key] || [];
    const error = mtErrors[key];
    
    if (error) {
        mtWarning.style.display = 'block';
        mtWarning.innerHTML = `<i class="bi bi-exclamation-triangle"></i> 
            <strong>MikroTik tidak terhubung:</strong> ${error}`;
        profileHint.textContent = 'Tidak ada profile yang tersedia (MikroTik offline).';
    } else {
        mtWarning.style.display = 'none';
        
        if (profiles.length === 0) {
            profileHint.textContent = 'Tidak ada PPP Profile di MikroTik ini.';
        } else {
            profileHint.textContent = `${profiles.length} profiles tersedia dari MikroTik.`;
            profiles.forEach(p => {
                const opt = document.createElement('option');
                opt.value = p;
                opt.textContent = p;
                profileSelect.appendChild(opt);
            });
        }
    }
}

// Auto-open modal jika ada parameter edit di URL
<?php if ($editPackage): ?>
window.addEventListener('DOMContentLoaded', function() {
    editPackage(<?= json_encode($editPackage) ?>);
});
<?php endif; ?>
</script>

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