<?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('branch_admin');
$pageTitle = 'Manajemen Paket Internet';

$db = db();

// ============================================================================
// 1. 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');
}

// ============================================================================
// 2. AMBIL PPP PROFILES DARI MIKROTIK
// ============================================================================
$pppProfiles = [];
$mtConnected = false;
$mtError = '';

try {
    $mt = new MikroTik($userBranchId);
    $mt->connect();
    $mtConnected = 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();
}

// ============================================================================
// 3. HANDLE ACTIONS
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    try {
        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'] ?? '');
            
            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');
            
            $check = $db->prepare("SELECT id FROM packages WHERE name = ?");
            $check->execute([$name]);
            if ($check->fetch()) throw new Exception("Paket '{$name}' sudah ada");
            
            $stmt = $db->prepare("
                INSERT INTO packages (name, price, speed, ppp_profile, description, status, created_at)
                VALUES (?, ?, ?, ?, ?, 'active', NOW())
            ");
            $stmt->execute([$name, $price, $speed, $pppProfile, $description]);
            
            logActivity($currentUserId, 'add_package', "Tambah paket: {$name} (Profile: {$pppProfile})");
            redirect('/branch/packages.php', "✅ Paket '{$name}' berhasil ditambahkan");
        }
        
        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'] ?? '');
            
            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');
            
            $check = $db->prepare("SELECT id FROM packages WHERE name = ? AND id != ?");
            $check->execute([$name, $id]);
            if ($check->fetch()) throw new Exception("Paket '{$name}' sudah ada");
            
            $stmt = $db->prepare("
                UPDATE packages 
                SET name = ?, price = ?, speed = ?, ppp_profile = ?, description = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$name, $price, $speed, $pppProfile, $description, $id]);
            
            logActivity($currentUserId, 'edit_package', "Edit paket #$id: {$name}");
            redirect('/branch/packages.php', "✅ Paket berhasil diupdate");
        }
        
        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('/branch/packages.php', "✅ Status paket berhasil diubah");
        }
        
        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('/branch/packages.php', "✅ Paket berhasil dihapus");
        }
        
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = '❌ ' . $e->getMessage();
    }
}

// ============================================================================
// 4. LOAD DATA PAKET
// ============================================================================
$packages = [];
try {
    $stmt = $db->query("
        SELECT p.*, 
            (SELECT COUNT(*) FROM customers WHERE package_id = p.id) as customer_count
        FROM packages p
        ORDER BY p.price ASC
    ");
    $packages = $stmt->fetchAll();
} catch (\Throwable $e) {}

// Stats
$totalPackages = count($packages);
$activePackages = count(array_filter($packages, fn($p) => $p['status'] === 'active'));
$inactivePackages = $totalPackages - $activePackages;
$totalCustomers = array_sum(array_column($packages, 'customer_count'));

$flashError = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_error']);

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

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

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

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

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

.navbar-left {
    display: flex;
    align-items: center;
    gap: 14px;
    flex: 1;
    min-width: 0;
}

.burger-btn {
    background: rgba(255,255,255,0.2);
    border: 2px solid rgba(255,255,255,0.3);
    color: white;
    width: 42px;
    height: 42px;
    border-radius: 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.3rem;
    transition: all 0.3s ease;
    flex-shrink: 0;
}

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

.navbar-info {
    min-width: 0;
    flex: 1;
}

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

.navbar-title {
    color: white;
    font-size: 1.15rem;
    font-weight: 700;
    margin: 2px 0 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

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

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

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

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

.page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

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

.page-title i {
    font-size: 1.8rem;
    color: #0066CC;
}

.branch-badge {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    color: #003D7A;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.btn-add {
    padding: 12px 24px;
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 0.95rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    box-shadow: 0 4px 15px rgba(0, 102, 204, 0.3);
}

.btn-add:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 102, 204, 0.4);
    color: white;
}

/* === SUMMARY CARDS === */
.summary-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 14px;
    margin-bottom: 22px;
}

.summary-card {
    background: white;
    border-radius: 16px;
    padding: 18px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.06);
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border-left: 4px solid transparent;
}

.summary-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 25px rgba(0,0,0,0.1);
}

.summary-card.primary { border-left-color: #0066CC; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.info { border-left-color: #00B8D4; }

.summary-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.summary-card-title {
    color: #666;
    font-size: 0.78rem;
    font-weight: 600;
    margin: 0;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.summary-card-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.15rem;
}

.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }

.summary-card-value {
    font-size: 1.6rem;
    font-weight: 800;
    margin-bottom: 4px;
    letter-spacing: -0.5px;
    color: #003D7A;
    line-height: 1.1;
}

.summary-card-footer {
    font-size: 0.78rem;
    color: #999;
    display: flex;
    align-items: center;
    gap: 5px;
}

/* === STATUS TABS === */
.status-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 20px;
    overflow-x: auto;
    padding-bottom: 4px;
}

.status-tab {
    padding: 10px 18px;
    border-radius: 10px;
    text-decoration: none;
    font-size: 0.88rem;
    font-weight: 600;
    white-space: nowrap;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border: 2px solid #e8f4f8;
    background: white;
    color: #666;
}

.status-tab:hover {
    border-color: #0066CC;
    color: #0066CC;
}

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

.status-tab.success.active {
    background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%);
    box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3);
}

.status-tab.warning.active {
    background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%);
    box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3);
}

.status-tab-count {
    background: rgba(255,255,255,0.3);
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 0.75rem;
    font-weight: 700;
}

.status-tab:not(.active) .status-tab-count {
    background: #e8f4f8;
    color: #666;
}

/* === ALERT MODERN === */
.alert-modern {
    padding: 14px 18px;
    border-radius: 12px;
    margin-bottom: 16px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 0.92rem;
    border: 2px solid;
}

.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }

.alert-modern i {
    font-size: 1.2rem;
    margin-top: 2px;
    flex-shrink: 0;
}

/* === FILTER CARD === */
.card-modern {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
    margin-bottom: 20px;
    border: none;
}

.card-header-modern {
    color: white;
    padding: 16px 20px;
    font-size: 1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
}

.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }

.card-header-modern .title-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.card-body-modern {
    padding: 20px;
}

/* === FILTER FORM === */
.filter-form {
    display: grid;
    grid-template-columns: 2fr 1fr auto auto;
    gap: 12px;
    align-items: end;
}

.form-group-filter {
    margin-bottom: 0;
}

.form-label-filter {
    display: block;
    font-weight: 600;
    color: #003D7A;
    margin-bottom: 6px;
    font-size: 0.8rem;
}

.form-control-filter,
.form-select-filter {
    width: 100%;
    padding: 10px 14px;
    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-filter:focus,
.form-select-filter:focus {
    outline: none;
    border-color: #0066CC;
    background: white;
    box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1);
}

.btn-filter {
    padding: 10px 16px;
    border: none;
    border-radius: 10px;
    font-size: 0.88rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    text-decoration: none;
    white-space: nowrap;
    height: 42px;
}

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

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

/* === TABLE MODERN === */
.table-wrapper {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    overflow: hidden;
    margin-bottom: 20px;
}

.table-header {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
}

.table-header-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 600;
    font-size: 1rem;
}

.table-header-count {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.82rem;
    font-weight: 600;
}

.table-scroll {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.table-modern {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 0.88rem;
    min-width: 900px;
}

.table-modern thead {
    background: #f8fafc;
    position: sticky;
    top: 0;
    z-index: 10;
}

.table-modern th {
    padding: 12px 14px;
    text-align: left;
    font-weight: 700;
    color: #003D7A;
    border-bottom: 2px solid #e8f4f8;
    font-size: 0.78rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
}

.table-modern td {
    padding: 12px 14px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

.table-modern tbody tr {
    transition: all 0.2s ease;
}

.table-modern tbody tr:hover {
    background: #f8fafc;
}

.table-modern tbody tr:last-child td {
    border-bottom: none;
}

.table-modern tbody tr.row-inactive {
    background: #fafafa;
    opacity: 0.85;
}

.table-modern tbody tr.row-inactive:hover {
    background: #f0f0f0;
}

/* === PACKAGE CELL === */
.package-cell {
    display: flex;
    align-items: center;
    gap: 10px;
}

.package-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.1rem;
    flex-shrink: 0;
}

.package-icon.inactive {
    background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%);
}

.package-name {
    font-weight: 700;
    color: #003D7A;
    font-size: 0.9rem;
    margin: 0;
    line-height: 1.3;
}

.package-desc {
    font-size: 0.72rem;
    color: #999;
    margin-top: 2px;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* === PRICE CELL === */
.price-cell {
    font-weight: 800;
    color: #003D7A;
    font-size: 0.95rem;
}

.price-cell small {
    display: block;
    font-size: 0.7rem;
    color: #999;
    font-weight: 500;
    margin-top: 2px;
}

/* === SPEED CELL === */
.speed-cell {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 700;
    color: #00C853;
    font-size: 0.88rem;
}

.speed-cell i {
    font-size: 1rem;
}

/* === PPP PROFILE === */
.ppp-profile-box {
    background: #e3f2fd;
    border-left: 3px solid #0066CC;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 0.78rem;
    color: #1565c0;
    font-family: 'Courier New', monospace;
    font-weight: 700;
}

.ppp-profile-status {
    font-size: 0.7rem;
    margin-top: 3px;
    display: flex;
    align-items: center;
    gap: 4px;
    font-weight: 600;
}

.ppp-profile-status.valid {
    color: #00C853;
}

.ppp-profile-status.missing {
    color: #DC3545;
}

/* === CUSTOMER COUNT === */
.customer-count {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 10px;
    background: #f0f0f0;
    border-radius: 20px;
    font-size: 0.78rem;
    font-weight: 700;
    color: #003D7A;
}

.customer-count i {
    color: #0066CC;
}

/* === BADGE MODERN === */
.badge-modern {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.72rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
}

.badge-modern.active { background: #d1e7dd; color: #0f5132; }
.badge-modern.inactive { background: #e9ecef; color: #41464b; }

/* === ACTION BUTTONS === */
.action-buttons {
    display: flex;
    gap: 4px;
    flex-wrap: nowrap;
}

.btn-action {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.88rem;
    text-decoration: none;
    flex-shrink: 0;
}

.btn-action.edit { background: #fff3cd; color: #856404; }
.btn-action.edit:hover { background: #FF9900; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }

.btn-action.toggle-on { background: #d1e7dd; color: #0f5132; }
.btn-action.toggle-on:hover { background: #00C853; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3); }

.btn-action.toggle-off { background: #e9ecef; color: #41464b; }
.btn-action.toggle-off:hover { background: #607D8B; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(96, 125, 139, 0.3); }

.btn-action.view { background: #cff4fc; color: #055160; }
.btn-action.view:hover { background: #00B8D4; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 184, 212, 0.3); }

.btn-action.delete { background: #ffe5e5; color: #842029; }
.btn-action.delete:hover { background: #b02a37; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(176, 42, 55, 0.3); }

/* === EMPTY STATE === */
.empty-state {
    text-align: center;
    padding: 50px 20px;
}

.empty-state-icon {
    width: 70px;
    height: 70px;
    margin: 0 auto 16px;
    background: #f8fafc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: #ccc;
}

.empty-state-title {
    color: #666;
    font-weight: 600;
    margin-bottom: 6px;
    font-size: 1rem;
}

.empty-state-subtitle {
    color: #999;
    font-size: 0.85rem;
    margin: 0 0 16px;
}

/* === MODAL MODERN === */
.modal-modern .modal-content {
    border: none;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}

.modal-modern .modal-header {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    color: white;
    padding: 18px 24px;
    border: none;
}

.modal-modern .modal-title {
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1.1rem;
}

.modal-modern .modal-body {
    padding: 24px;
}

.modal-modern .modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    background: #f8fafc;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.form-grid-modal {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;
}

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

.form-group-modal {
    margin-bottom: 0;
}

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

.form-label-modal i {
    color: #0066CC;
}

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

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

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

textarea.form-control-modal {
    resize: vertical;
    min-height: 70px;
}

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

.info-box-modal {
    background: #e3f2fd;
    border-left: 3px solid #0066CC;
    padding: 12px 14px;
    border-radius: 8px;
    font-size: 0.85rem;
    color: #1565c0;
    margin-top: 16px;
    display: flex;
    align-items: flex-start;
    gap: 10px;
}

.info-box-modal i {
    margin-top: 2px;
    flex-shrink: 0;
    font-size: 1.1rem;
}

.info-box-modal code {
    background: rgba(255,255,255,0.6);
    padding: 1px 6px;
    border-radius: 4px;
    font-family: 'Courier New', monospace;
    font-weight: 700;
    color: #003D7A;
}

.btn-modal {
    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;
    gap: 6px;
}

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

.btn-modal.secondary:hover {
    background: #f8fafc;
}

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

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

/* === RESPONSIVE === */
@media (max-width: 992px) {
    .filter-form {
        grid-template-columns: 1fr 1fr;
    }
    
    .filter-form .form-group-filter:first-child {
        grid-column: 1 / -1;
    }
}

@media (max-width: 768px) {
    .navbar-modern {
        padding: 10px 15px;
    }
    
    .navbar-title {
        font-size: 1rem;
    }
    
    .navbar-greeting {
        display: none;
    }
    
    .navbar-badge {
        display: none;
    }
    
    .main-content {
        padding: 15px;
    }
    
    .page-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .page-title {
        font-size: 1.3rem;
    }
    
    .page-title i {
        font-size: 1.5rem;
    }
    
    .btn-add {
        width: 100%;
        justify-content: center;
    }
    
    .summary-row {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
    }
    
    .summary-card {
        padding: 14px;
    }
    
    .summary-card-value {
        font-size: 1.2rem;
    }
    
    .summary-card-title {
        font-size: 0.68rem;
    }
    
    .summary-card-icon {
        width: 34px;
        height: 34px;
        font-size: 1rem;
    }
    
    .status-tabs {
        gap: 6px;
    }
    
    .status-tab {
        padding: 8px 14px;
        font-size: 0.8rem;
    }
    
    .card-header-modern {
        padding: 14px 16px;
        font-size: 0.95rem;
    }
    
    .card-body-modern {
        padding: 16px;
    }
    
    .filter-form {
        grid-template-columns: 1fr;
    }
    
    .filter-form .form-group-filter {
        grid-column: 1 / -1;
    }
    
    .filter-form .btn-filter {
        flex: 1;
    }
    
    .table-header {
        padding: 14px 16px;
    }
    
    .table-header-title {
        font-size: 0.92rem;
    }
    
    .table-modern {
        font-size: 0.82rem;
    }
    
    .table-modern th,
    .table-modern td {
        padding: 10px 12px;
    }
    
    .package-icon {
        width: 34px;
        height: 34px;
        font-size: 1rem;
    }
    
    .package-name {
        font-size: 0.82rem;
    }
    
    .btn-action {
        width: 30px;
        height: 30px;
        font-size: 0.82rem;
    }
    
    .form-grid-modal {
        grid-template-columns: 1fr;
    }
    
    .modal-modern .modal-dialog {
        margin: 0;
        max-width: 100%;
        min-height: 100vh;
    }
    
    .modal-modern .modal-content {
        border-radius: 0;
        min-height: 100vh;
    }
}

@media (max-width: 480px) {
    .navbar-modern {
        padding: 8px 12px;
    }
    
    .burger-btn {
        width: 38px;
        height: 38px;
        font-size: 1.15rem;
    }
    
    .navbar-title {
        font-size: 0.95rem;
    }
    
    .main-content {
        padding: 12px;
    }
    
    .page-title {
        font-size: 1.15rem;
        gap: 8px;
    }
    
    .summary-row {
        grid-template-columns: 1fr 1fr;
        gap: 8px;
    }
    
    .summary-card {
        padding: 12px;
    }
    
    .summary-card-value {
        font-size: 1.05rem;
    }
    
    .summary-card-footer {
        font-size: 0.7rem;
    }
    
    .table-header {
        padding: 12px 14px;
    }
    
    .table-modern th,
    .table-modern td {
        padding: 8px 10px;
    }
    
    .package-cell {
        gap: 8px;
    }
    
    .package-icon {
        width: 30px;
        height: 30px;
        font-size: 0.9rem;
    }
    
    .package-name {
        font-size: 0.78rem;
    }
    
    .package-desc {
        display: none;
    }
    
    .badge-modern {
        font-size: 0.68rem;
        padding: 3px 8px;
    }
    
    .btn-action {
        width: 28px;
        height: 28px;
        font-size: 0.78rem;
    }
    
    .action-buttons {
        gap: 3px;
    }
}
</style>


<div class="content-wrapper">
<div class="main-content">
<!-- Navbar Modern dengan Burger Icon -->
<div class="navbar-modern">
    <div class="navbar-left">
        <button class="burger-btn" onclick="toggleSidebar()">
            <i class="bi bi-list"></i>
        </button>
        <div class="navbar-info">
            <p class="navbar-greeting">Manajemen produk internet</p>
            <h1 class="navbar-title">Paket Internet - <?= htmlspecialchars($userBranchName) ?></h1>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge">
            <i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?>
        </span>
    </div>
</div>    <!-- Page Header -->
    <div class="page-header">
        
        <button class="btn-add" data-bs-toggle="modal" data-bs-target="#packageModal" onclick="resetForm()">
            <i class="bi bi-plus-circle-fill"></i>
            <span>Tambah Paket</span>
        </button>
    </div>

    <?= flashMessage() ?>
    
    <?php if ($flashError): ?>
        <div class="alert-modern danger">
            <i class="bi bi-exclamation-circle-fill"></i>
            <div><?= htmlspecialchars($flashError) ?></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> Daftar PPP Profile tidak dapat dimuat.
                <?php if ($mtError): ?>
                    <br><small><?= htmlspecialchars($mtError) ?></small>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Summary Cards -->
    <div class="summary-row">
        <div class="summary-card primary">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Total Paket</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-box-seam"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalPackages) ?></div>
            <div class="summary-card-footer">📦 Seluruh paket</div>
        </div>
        
        <div class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Paket Aktif</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-check-circle-fill"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($activePackages) ?></div>
            <div class="summary-card-footer">✅ Bisa dipilih customer</div>
        </div>
        
        <div class="summary-card warning">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Nonaktif</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-pause-circle-fill"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($inactivePackages) ?></div>
            <div class="summary-card-footer">⏸️ Tidak ditampilkan</div>
        </div>
        
        <div class="summary-card info">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Total Pelanggan</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-people-fill"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalCustomers) ?></div>
            <div class="summary-card-footer">👥 Menggunakan paket</div>
        </div>
    </div>

    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="/branch/packages.php" class="status-tab <?= !$filterStatus ? 'active' : '' ?>">
            <i class="bi bi-list-ul"></i> Semua
            <span class="status-tab-count"><?= $totalPackages ?></span>
        </a>
        <a href="/branch/packages.php?status=active" class="status-tab success <?= $filterStatus === 'active' ? 'active' : '' ?>">
            <i class="bi bi-check-circle"></i> Aktif
            <span class="status-tab-count"><?= $activePackages ?></span>
        </a>
        <a href="/branch/packages.php?status=inactive" class="status-tab warning <?= $filterStatus === 'inactive' ? 'active' : '' ?>">
            <i class="bi bi-pause-circle"></i> Nonaktif
            <span class="status-tab-count"><?= $inactivePackages ?></span>
        </a>
    </div>

    <!-- Filter Card -->
    <div class="card-modern">
        <div class="card-header-modern primary">
            <div class="title-left">
                <i class="bi bi-funnel-fill"></i>
                <span>Filter & Pencarian</span>
            </div>
        </div>
        <div class="card-body-modern">
            <form method="GET" class="filter-form">
                <div class="form-group-filter">
                    <label class="form-label-filter">
                        <i class="bi bi-search"></i> Cari
                    </label>
                    <input type="text" name="search" class="form-control-filter" 
                           value="<?= htmlspecialchars($search) ?>" 
                           placeholder="Nama paket, kecepatan, PPP profile...">
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter">
                        <i class="bi bi-circle"></i> Status
                    </label>
                    <select name="status" class="form-select-filter">
                        <option value="">Semua</option>
                        <option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Aktif</option>
                        <option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Nonaktif</option>
                    </select>
                </div>
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-funnel"></i>
                    <span>Filter</span>
                </button>
                <a href="/branch/packages.php" class="btn-filter outline">
                    <i class="bi bi-arrow-counterclockwise"></i>
                    <span>Reset</span>
                </a>
            </form>
        </div>
    </div>

    <!-- Packages Table -->
    <div class="table-wrapper">
        <div class="table-header">
            <div class="table-header-title">
                <i class="bi bi-box-seam"></i>
                <span>Daftar Paket Internet</span>
                <span class="table-header-count"><?= count($packages) ?> paket</span>
            </div>
        </div>
        
        <?php if (empty($packages)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">
                    <i class="bi bi-box-seam"></i>
                </div>
                <h5 class="empty-state-title">Belum ada paket internet</h5>
                <p class="empty-state-subtitle">Mulai dengan menambahkan paket internet pertama Anda</p>
                <button class="btn-add" data-bs-toggle="modal" data-bs-target="#packageModal" onclick="resetForm()">
                    <i class="bi bi-plus-circle-fill"></i>
                    <span>Tambah Paket Pertama</span>
                </button>
            </div>
        <?php else: ?>
            <div class="table-scroll">
                <table class="table-modern">
                    <thead>
                        <tr>
                            <th>Paket</th>
                            <th>Harga</th>
                            <th>Kecepatan</th>
                            <th>PPP Profile</th>
                            <th>Pelanggan</th>
                            <th>Status</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($packages as $p): 
                        $rowClass = $p['status'] === 'inactive' ? 'row-inactive' : '';
                        $profileValid = $mtConnected && !empty($p['ppp_profile']) && in_array($p['ppp_profile'], $pppProfiles);
                        $profileMissing = $mtConnected && !empty($p['ppp_profile']) && !in_array($p['ppp_profile'], $pppProfiles);
                    ?>
                        <tr class="<?= $rowClass ?>">
                            <td>
                                <div class="package-cell">
                                    <div class="package-icon <?= $p['status'] === 'inactive' ? 'inactive' : '' ?>">
                                        <i class="bi bi-box-seam-fill"></i>
                                    </div>
                                    <div>
                                        <div class="package-name"><?= htmlspecialchars($p['name']) ?></div>
                                        <?php if (!empty($p['description'])): ?>
                                            <div class="package-desc" title="<?= htmlspecialchars($p['description']) ?>">
                                                <?= htmlspecialchars($p['description']) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="price-cell">
                                    Rp <?= number_format($p['price'], 0, ',', '.') ?>
                                    <small>per bulan</small>
                                </div>
                            </td>
                            <td>
                                <div class="speed-cell">
                                    <i class="bi bi-speedometer2"></i>
                                    <span><?= htmlspecialchars($p['speed']) ?></span>
                                </div>
                            </td>
                            <td>
                                <?php if (!empty($p['ppp_profile'])): ?>
                                    <div class="ppp-profile-box">
                                        <?= htmlspecialchars($p['ppp_profile']) ?>
                                    </div>
                                    <?php if ($profileValid): ?>
                                        <div class="ppp-profile-status valid">
                                            <i class="bi bi-check-circle-fill"></i> Valid di MikroTik
                                        </div>
                                    <?php elseif ($profileMissing): ?>
                                        <div class="ppp-profile-status missing">
                                            <i class="bi bi-exclamation-triangle-fill"></i> Tidak ditemukan
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span style="color: #ccc; font-size: 0.8rem;">Belum diset</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="/branch/customers.php?search=<?= urlencode($p['name']) ?>" 
                                   class="customer-count" title="Lihat pelanggan">
                                    <i class="bi bi-people-fill"></i>
                                    <span><?= $p['customer_count'] ?></span>
                                </a>
                            </td>
                            <td>
                                <?php if ($p['status'] === 'active'): ?>
                                    <span class="badge-modern active">
                                        <i class="bi bi-check-circle-fill"></i> Aktif
                                    </span>
                                <?php else: ?>
                                    <span class="badge-modern inactive">
                                        <i class="bi bi-pause-circle-fill"></i> Nonaktif
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-buttons" style="justify-content: center;">
                                    <button type="button" class="btn-action edit" 
                                            onclick='editPackage(<?= json_encode($p) ?>)' 
                                            title="Edit">
                                        <i class="bi bi-pencil-fill"></i>
                                    </button>
                                    
                                    <form method="POST" style="display: inline; margin: 0;">
                                        <?= csrfField() ?>
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="new_status" value="<?= $p['status'] === 'active' ? 'inactive' : 'active' ?>">
                                        <?php if ($p['status'] === 'active'): ?>
                                            <button type="submit" class="btn-action toggle-off" 
                                                    onclick="return confirm('Nonaktifkan paket <?= htmlspecialchars($p['name']) ?>?')" 
                                                    title="Nonaktifkan">
                                                <i class="bi bi-pause-fill"></i>
                                            </button>
                                        <?php else: ?>
                                            <button type="submit" class="btn-action toggle-on" 
                                                    onclick="return confirm('Aktifkan paket <?= htmlspecialchars($p['name']) ?>?')" 
                                                    title="Aktifkan">
                                                <i class="bi bi-play-fill"></i>
                                            </button>
                                        <?php endif; ?>
                                    </form>
                                    
                                    <a href="/branch/customers.php?search=<?= urlencode($p['name']) ?>" 
                                       class="btn-action view" title="Lihat Pelanggan">
                                        <i class="bi bi-eye-fill"></i>
                                    </a>
                                    
                                    <form method="POST" style="display: inline; margin: 0;">
                                        <?= csrfField() ?>
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn-action delete" 
                                                onclick="return confirm('Yakin hapus paket <?= htmlspecialchars($p['name']) ?>? Tindakan ini tidak bisa dibatalkan!')" 
                                                title="Hapus">
                                            <i class="bi bi-trash-fill"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal Tambah/Edit Paket -->
<div class="modal fade modal-modern" id="packageModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <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">
                    <h5 class="modal-title" id="modalTitle">
                        <i class="bi bi-plus-circle-fill"></i>
                        <span>Tambah Paket Internet</span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="form-grid-modal">
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-tag-fill"></i>
                                Nama Paket <span class="required">*</span>
                            </label>
                            <input type="text" name="name" id="pkgName" class="form-control-modal" required
                                   placeholder="Contoh: Paket Silver 10 Mbps">
                            <small class="form-hint-modal">
                                <i class="bi bi-info-circle"></i>
                                Nama unik untuk paket ini
                            </small>
                        </div>
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-speedometer2"></i>
                                Kecepatan <span class="required">*</span>
                            </label>
                            <input type="text" name="speed" id="pkgSpeed" class="form-control-modal" required
                                   placeholder="Contoh: 10 Mbps / 3 Mbps">
                            <small class="form-hint-modal">
                                <i class="bi bi-info-circle"></i>
                                Format: Upload / Download
                            </small>
                        </div>
                    </div>
                    
                    <div class="form-grid-modal">
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-currency-dollar"></i>
                                Harga / Bulan (Rp) <span class="required">*</span>
                            </label>
                            <input type="number" name="price" id="pkgPrice" class="form-control-modal" required
                                   min="0" step="1000" placeholder="150000">
                            <small class="form-hint-modal">
                                <i class="bi bi-info-circle"></i>
                                Harga langganan per bulan
                            </small>
                        </div>
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-router-fill"></i>
                                PPP Profile (MikroTik) <span class="required">*</span>
                                <?php if (!$mtConnected): ?>
                                    <span style="background: #fff3cd; color: #856404; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; margin-left: 6px;">
                                        MikroTik Offline
                                    </span>
                                <?php endif; ?>
                            </label>
                            <select name="ppp_profile" id="pkgProfile" class="form-select-modal" required onchange="updatePreview()">
                                <option value="">-- Pilih PPP Profile --</option>
                                <?php foreach ($pppProfiles as $profile): ?>
                                    <option value="<?= htmlspecialchars($profile) ?>"><?= htmlspecialchars($profile) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="form-hint-modal">
                                <i class="bi bi-info-circle"></i>
                                <?= count($pppProfiles) ?> profiles tersedia di MikroTik
                            </small>
                        </div>
                    </div>
                    
                    <div class="form-grid-modal single">
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-chat-left-text-fill"></i>
                                Deskripsi (Opsional)
                            </label>
                            <textarea name="description" id="pkgDescription" class="form-control-modal" rows="3"
                                      placeholder="Deskripsi tambahan tentang paket ini..."></textarea>
                        </div>
                    </div>
                    
                    <div class="info-box-modal">
                        <i class="bi bi-lightbulb-fill"></i>
                        <div>
                            <strong>Integrasi PPP Profile:</strong><br>
                            Ketika pelanggan memilih paket ini, mereka akan otomatis mendapatkan bandwidth 
                            dan setting sesuai profile <strong id="previewProfile">[belum dipilih]</strong> di MikroTik.
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-modal secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn-modal primary">
                        <i class="bi bi-save-fill"></i>
                        <span id="submitText">Simpan Paket</span>
                    </button>
                </div>
            </div>
        </form>
    </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 resetForm() {
    document.getElementById('packageForm').reset();
    document.getElementById('formAction').value = 'add';
    document.getElementById('packageId').value = '';
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-plus-circle-fill"></i><span>Tambah Paket Internet</span>';
    document.getElementById('submitText').textContent = 'Simpan Paket';
    document.getElementById('previewProfile').textContent = '[belum dipilih]';
}

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('pkgProfile').value = pkg.ppp_profile || '';
    document.getElementById('pkgDescription').value = pkg.description || '';
    
    document.getElementById('modalTitle').innerHTML = '<i class="bi bi-pencil-fill"></i><span>Edit Paket: ' + pkg.name + '</span>';
    document.getElementById('submitText').textContent = 'Update Paket';
    
    updatePreview();
    
    new bootstrap.Modal(document.getElementById('packageModal')).show();
}

function updatePreview() {
    const profile = document.getElementById('pkgProfile').value;
    document.getElementById('previewProfile').textContent = profile || '[belum dipilih]';
}

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