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

requireRole('branch_admin');
$pageTitle = 'PPPoE Status - Cabang';

$db = db();

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

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

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

$success = '';
$error = '';
$pppoeData = null;

// ============================================================================
// 2. HANDLE ACTIONS
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    $username = trim($_POST['username'] ?? '');
    
    if (!empty($username)) {
        $customerCheck = $db->prepare("SELECT id, name, branch_id FROM customers WHERE pppoe_username = ?");
        $customerCheck->execute([$username]);
        $customer = $customerCheck->fetch();
        
        if ($customer && (int)$customer['branch_id'] !== $userBranchId) {
            $error = "❌ Anda tidak memiliki akses ke user <strong>$username</strong> (milik cabang lain)";
        } else {
            try {
                $mt = new MikroTik($userBranchId);
                
                switch ($action) {
                    case 'suspend':
                        $result = $mt->suspendCustomer($username);
                        if ($result['success']) {
                            if ($customer) Customer::update($customer['id'], ['status' => 'suspended']);
                            $success = "✅ User <strong>$username</strong> berhasil di-suspend.";
                            logActivity($currentUserId, 'suspend_pppoe', "Suspend PPPoE: {$username} di cabang {$userBranchName}");
                        } else {
                            $error = "❌ Gagal suspend: " . htmlspecialchars($result['error']);
                        }
                        break;
                        
                    case 'restore':
                        $result = $mt->restoreCustomer($username);
                        if ($result['success']) {
                            if ($customer) Customer::update($customer['id'], ['status' => 'active']);
                            $success = "✅ User <strong>$username</strong> berhasil di-restore.";
                            logActivity($currentUserId, 'restore_pppoe', "Restore PPPoE: {$username} di cabang {$userBranchName}");
                        } else {
                            $error = "❌ Gagal restore: " . htmlspecialchars($result['error']);
                        }
                        break;
                        
                    case 'kick':
                        $result = $mt->kickUser($username);
                        if ($result['killed'] > 0) {
                            $success = "✅ User <strong>$username</strong> berhasil di-kick ({$result['killed']} koneksi diputus).";
                            logActivity($currentUserId, 'kick_pppoe', "Kick PPPoE: {$username} di cabang {$userBranchName}");
                        } else {
                            $error = "❌ Gagal kick: " . htmlspecialchars($result['error'] ?: 'Tidak ada koneksi aktif');
                        }
                        break;
                        
                    case 'delete':
                        if ($customer) {
                            $error = "❌ User <strong>$username</strong> terdaftar sebagai pelanggan. Hapus dari menu Pelanggan terlebih dahulu.";
                        } else {
                            $result = $mt->removeSecret($username);
                            if ($result['success']) {
                                $success = "✅ User <strong>$username</strong> berhasil dihapus.";
                                logActivity($currentUserId, 'delete_pppoe', "Hapus PPPoE: {$username} di cabang {$userBranchName}");
                            } else {
                                $error = "❌ Gagal hapus: " . htmlspecialchars($result['error']);
                            }
                        }
                        break;
                }
            } catch (\Throwable $e) {
                $error = "❌ Error: " . $e->getMessage();
            }
        }
    }
}

// ============================================================================
// 3. HANDLE ADD NEW USER
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_user' && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $newUsername = trim($_POST['new_username'] ?? '');
    $newPassword = $_POST['new_password'] ?? '';
    $newProfile = trim($_POST['new_profile'] ?? 'default');
    $newComment = trim($_POST['new_comment'] ?? '');
    
    if (!empty($newUsername) && !empty($newPassword)) {
        $check = $db->prepare("SELECT id FROM customers WHERE pppoe_username = ? AND branch_id = ?");
        $check->execute([$newUsername, $userBranchId]);
        if ($check->fetch()) {
            $error = "❌ Username <strong>$newUsername</strong> sudah terdaftar sebagai pelanggan di cabang ini.";
        } else {
            try {
                $mt = new MikroTik($userBranchId);
                $result = $mt->addSecret($newUsername, $newPassword, $newProfile, 'pppoe', $newComment);
                
                if ($result['success']) {
                    $success = "✅ User <strong>$newUsername</strong> berhasil ditambahkan ke MikroTik cabang {$userBranchName}.";
                    logActivity($currentUserId, 'add_pppoe', "Tambah PPPoE: {$newUsername} di cabang {$userBranchName}");
                } else {
                    $error = "❌ Gagal tambah user: " . htmlspecialchars($result['error']);
                }
            } catch (\Throwable $e) {
                $error = "❌ Error: " . $e->getMessage();
            }
        }
    } else {
        $error = "❌ Username dan password wajib diisi.";
    }
}

// ============================================================================
// 4. LOAD PPPoE STATUS
// ============================================================================
try {
    $mt = new MikroTik($userBranchId);
    $pppoeData = $mt->getPPPoEStatus();
} catch (\Throwable $e) {
    $pppoeData = ['success' => false, 'error' => $e->getMessage(), 'online' => [], 'offline' => [], 'total_secrets' => 0, 'total_online' => 0, 'total_offline' => 0, 'total_disabled' => 0];
}

// ============================================================================
// 5. LOAD PPP PROFILES
// ============================================================================
$pppProfiles = [];
try {
    $mt = new MikroTik($userBranchId);
    $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) {}

// Search filter
$search = trim($_GET['search'] ?? '');
$filter = $_GET['filter'] ?? 'all';

// ============================================================================
// 6. LOAD DATA PELANGGAN CABANG
// ============================================================================
$branchCustomers = [];
try {
    $stmt = $db->prepare("SELECT id, name, customer_number, pppoe_username, status FROM customers WHERE branch_id = ?");
    $stmt->execute([$userBranchId]);
    foreach ($stmt->fetchAll() as $c) {
        $branchCustomers[$c['pppoe_username']] = $c;
    }
} catch (\Throwable $e) {}

// Filter users
$allUsers = array_merge($pppoeData['online'] ?? [], $pppoeData['offline'] ?? []);

if ($filter === 'online') {
    $allUsers = array_filter($allUsers, fn($u) => $u['status'] === 'online');
} elseif ($filter === 'offline') {
    $allUsers = array_filter($allUsers, fn($u) => $u['status'] === 'offline' && !$u['disabled']);
} elseif ($filter === 'disabled') {
    $allUsers = array_filter($allUsers, fn($u) => $u['disabled']);
}

if (!empty($search)) {
    $allUsers = array_filter($allUsers, fn($u) => stripos($u['name'], $search) !== false);
}

// Stats
$totalUsers = $pppoeData['total_secrets'] ?? 0;
$totalOnline = $pppoeData['total_online'] ?? 0;
$totalOffline = $pppoeData['total_offline'] ?? 0;
$totalDisabled = $pppoeData['total_disabled'] ?? 0;

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(180px, 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.secondary { border-left-color: #607D8B; }
.summary-card.danger { border-left-color: #DC3545; }

.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.secondary .summary-card-icon { background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 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.secondary.active {
    background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%);
    box-shadow: 0 4px 12px rgba(96, 125, 139, 0.3);
}

.status-tab.danger.active {
    background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%);
    box-shadow: 0 4px 12px rgba(220, 53, 69, 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;
}

/* === CARD MODERN === */
.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-unregistered {
    background: #fffdf5;
}

.table-modern tbody tr.row-unregistered:hover {
    background: #fffae8;
}

.table-modern tbody tr.row-disabled {
    background: #fff8f8;
    opacity: 0.85;
}

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

.user-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    color: white;
    font-size: 0.85rem;
    flex-shrink: 0;
}

.user-avatar.online { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.user-avatar.offline { background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%); }
.user-avatar.disabled { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }

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

.user-meta {
    font-size: 0.72rem;
    color: #999;
    margin-top: 1px;
}

/* === 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.online { background: #d1e7dd; color: #0f5132; }
.badge-modern.offline { background: #e9ecef; color: #41464b; }
.badge-modern.disabled { background: #f8d7da; color: #842029; }
.badge-modern.profile { background: #cff4fc; color: #055160; text-transform: none; }
.badge-modern.unregistered { background: #fff3cd; color: #856404; }

/* === 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.kick { background: #fff3cd; color: #856404; }
.btn-action.kick:hover { background: #FF9900; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }

.btn-action.suspend { background: #f8d7da; color: #842029; }
.btn-action.suspend:hover { background: #DC3545; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3); }

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

.btn-action.edit { background: #cfe2ff; color: #084298; }
.btn-action.edit:hover { background: #0066CC; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 102, 204, 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;
}

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

.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);
}

.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;
}

.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;
    }
    
    .form-grid-modal {
        grid-template-columns: 1fr;
    }
}

@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;
    }
    
    .user-avatar {
        width: 32px;
        height: 32px;
        font-size: 0.8rem;
    }
    
    .user-name {
        font-size: 0.82rem;
    }
    
    .btn-action {
        width: 30px;
        height: 30px;
        font-size: 0.82rem;
    }
    
    .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;
    }
    
    .user-cell {
        gap: 8px;
    }
    
    .user-avatar {
        width: 28px;
        height: 28px;
        font-size: 0.75rem;
    }
    
    .user-name {
        font-size: 0.78rem;
    }
    
    .badge-modern {
        font-size: 0.68rem;
        padding: 3px 8px;
    }
    
    .btn-action {
        width: 28px;
        height: 28px;
        font-size: 0.78rem;
    }
    
    .action-buttons {
        gap: 3px;
    }
}
</style>

<!-- Navbar Modern dengan Burger Icon -->

<div class="content-wrapper">
<div class="main-content">
    <div class="navbar-modern">
    <div class="navbar-left">
        <button class="burger-btn" onclick="toggleSidebar()">
            <i class="bi bi-list"></i>
        </button>
        <div class="navbar-info">
            <p class="navbar-greeting">Monitoring MikroTik</p>
            <h1 class="navbar-title">PPPoE Status - <?= htmlspecialchars($userBranchName) ?></h1>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge">
            <i class="bi bi-router"></i> MikroTik
        </span>
    </div>
</div>
    <!-- Page Header -->
    <div class="page-header">
        <h2 class="page-title">
            <i class="bi bi-ethernet"></i>
            <span>PPPoE Status</span>
            <span class="branch-badge">
                <i class="bi bi-building"></i>
                <?= htmlspecialchars($userBranchName) ?>
            </span>
        </h2>
        <button class="btn-add" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="bi bi-person-plus-fill"></i>
            <span>Tambah User</span>
        </button>
    </div>

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

    <div class="alert-modern info">
        <i class="bi bi-info-circle-fill"></i>
        <div>
            Anda hanya dapat mengelola PPPoE users yang terdaftar sebagai pelanggan di cabang <strong><?= htmlspecialchars($userBranchName) ?></strong>.
        </div>
    </div>

    <?php if (!$pppoeData['success']): ?>
        <div class="alert-modern danger">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <div>
                <strong>Gagal mengambil data PPPoE dari MikroTik cabang:</strong><br>
                <?= htmlspecialchars($pppoeData['error']) ?>
                <br><small>Pastikan konfigurasi MikroTik sudah benar di <a href="/branch/mikrotik_settings.php" style="color: #c62828; font-weight: 700;">halaman pengaturan</a>.</small>
            </div>
        </div>
    <?php else: ?>

    <!-- Summary Cards -->
    <div class="summary-row">
        <div class="summary-card primary">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Total Users</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-people-fill"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalUsers) ?></div>
            <div class="summary-card-footer">👥 Seluruh PPPoE users</div>
        </div>
        
        <div class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Online</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-wifi"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalOnline) ?></div>
            <div class="summary-card-footer">🟢 Sedang terhubung</div>
        </div>
        
        <div class="summary-card secondary">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Offline</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-wifi-off"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalOffline) ?></div>
            <div class="summary-card-footer">⚪ Tidak terhubung</div>
        </div>
        
        <div class="summary-card danger">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Disabled</h6>
                <div class="summary-card-icon">
                    <i class="bi bi-pause-circle-fill"></i>
                </div>
            </div>
            <div class="summary-card-value"><?= number_format($totalDisabled) ?></div>
            <div class="summary-card-footer">🔴 Di-suspend</div>
        </div>
    </div>

    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="mikrotik_status.php" class="status-tab <?= $filter === 'all' && empty($search) ? 'active' : '' ?>">
            <i class="bi bi-list-ul"></i> Semua
            <span class="status-tab-count"><?= count(array_merge($pppoeData['online'] ?? [], $pppoeData['offline'] ?? [])) ?></span>
        </a>
        <a href="mikrotik_status.php?filter=online" class="status-tab success <?= $filter === 'online' ? 'active' : '' ?>">
            <i class="bi bi-wifi"></i> Online
            <span class="status-tab-count"><?= $totalOnline ?></span>
        </a>
        <a href="mikrotik_status.php?filter=offline" class="status-tab secondary <?= $filter === 'offline' ? 'active' : '' ?>">
            <i class="bi bi-wifi-off"></i> Offline
            <span class="status-tab-count"><?= $totalOffline ?></span>
        </a>
        <a href="mikrotik_status.php?filter=disabled" class="status-tab danger <?= $filter === 'disabled' ? 'active' : '' ?>">
            <i class="bi bi-pause-circle"></i> Disabled
            <span class="status-tab-count"><?= $totalDisabled ?></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 Username
                    </label>
                    <input type="text" name="search" class="form-control-filter" 
                           value="<?= htmlspecialchars($search) ?>" 
                           placeholder="Ketik username...">
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter">
                        <i class="bi bi-circle"></i> Filter Status
                    </label>
                    <select name="filter" class="form-select-filter">
                        <option value="all" <?= $filter === 'all' ? 'selected' : '' ?>>Semua</option>
                        <option value="online" <?= $filter === 'online' ? 'selected' : '' ?>>🟢 Online</option>
                        <option value="offline" <?= $filter === 'offline' ? 'selected' : '' ?>>⚪ Offline</option>
                        <option value="disabled" <?= $filter === 'disabled' ? 'selected' : '' ?>>🔴 Disabled</option>
                    </select>
                </div>
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-funnel"></i>
                    <span>Filter</span>
                </button>
                <a href="mikrotik_status.php" class="btn-filter outline">
                    <i class="bi bi-arrow-counterclockwise"></i>
                    <span>Reset</span>
                </a>
            </form>
        </div>
    </div>

    <!-- User Table -->
    <div class="table-wrapper">
        <div class="table-header">
            <div class="table-header-title">
                <i class="bi bi-list-ul"></i>
                <span>Daftar User PPPoE</span>
                <span class="table-header-count"><?= count($allUsers) ?> user</span>
            </div>
        </div>
        
        <?php if (empty($allUsers)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">
                    <i class="bi bi-inbox"></i>
                </div>
                <h5 class="empty-state-title">Tidak ada user yang cocok</h5>
                <p class="empty-state-subtitle">
                    <?php if ($filter !== 'all' || !empty($search)): ?>
                        Coba ubah filter atau kata kunci pencarian.
                        <a href="mikrotik_status.php" style="color: #0066CC; font-weight: 600;">Reset filter</a>
                    <?php else: ?>
                        Belum ada user PPPoE di MikroTik cabang ini.
                    <?php endif; ?>
                </p>
            </div>
        <?php else: ?>
            <div class="table-scroll">
                <table class="table-modern">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Pelanggan</th>
                            <th>Profile</th>
                            <th>Status</th>
                            <th>IP Address</th>
                            <th>Uptime</th>
                            <th>Comment</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($allUsers as $user): 
                            $cust = $branchCustomers[$user['name']] ?? null;
                            $isBranchUser = $cust !== null;
                            
                            $rowClass = '';
                            if (!$isBranchUser) $rowClass = 'row-unregistered';
                            elseif ($user['disabled']) $rowClass = 'row-disabled';
                            
                            $avatarClass = $user['disabled'] ? 'disabled' : ($user['status'] === 'online' ? 'online' : 'offline');
                        ?>
                            <tr class="<?= $rowClass ?>">
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar <?= $avatarClass ?>">
                                            <?= strtoupper(substr($user['name'], 0, 1)) ?>
                                        </div>
                                        <div>
                                            <div class="user-name"><?= htmlspecialchars($user['name']) ?></div>
                                            <?php if (!$isBranchUser): ?>
                                                <div class="user-meta" style="color: #f57c00;">
                                                    <i class="bi bi-exclamation-triangle"></i> Unregistered
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($cust): ?>
                                        <div style="font-weight: 600; color: #003D7A; font-size: 0.85rem;">
                                            <?= htmlspecialchars($cust['name']) ?>
                                        </div>
                                        <code style="font-size: 0.72rem; background: #f8fafc; padding: 2px 6px; border-radius: 4px;">
                                            #<?= htmlspecialchars($cust['customer_number']) ?>
                                        </code>
                                    <?php else: ?>
                                        <span style="color: #ccc; font-style: italic;">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge-modern profile">
                                        <i class="bi bi-sliders"></i>
                                        <?= htmlspecialchars($user['profile']) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($user['disabled']): ?>
                                        <span class="badge-modern disabled">
                                            <i class="bi bi-pause-circle-fill"></i> Disabled
                                        </span>
                                    <?php elseif ($user['status'] === 'online'): ?>
                                        <span class="badge-modern online">
                                            <i class="bi bi-circle-fill" style="font-size: 0.5rem;"></i> Online
                                        </span>
                                    <?php else: ?>
                                        <span class="badge-modern offline">
                                            <i class="bi bi-circle"></i> Offline
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <code style="font-size: 0.78rem; background: #f8fafc; padding: 3px 8px; border-radius: 6px; border-left: 3px solid #0066CC;">
                                        <?= htmlspecialchars($user['address'] ?? '-') ?>
                                    </code>
                                </td>
                                <td>
                                    <div style="font-size: 0.85rem; font-weight: 600; color: #003D7A;">
                                        <?= htmlspecialchars($user['uptime'] ?? '-') ?>
                                    </div>
                                </td>
                                <td>
                                    <small style="color: #666;">
                                        <?= htmlspecialchars($user['comment'] ?: '-') ?>
                                    </small>
                                </td>
                                <td>
                                    <div class="action-buttons" style="justify-content: center;">
                                        <?php if ($user['status'] === 'online'): ?>
                                            <form method="POST" style="display: inline; margin: 0;" 
                                                  onsubmit="return confirm('Kick user <?= htmlspecialchars($user['name']) ?>?')">
                                                <?= csrfField() ?>
                                                <input type="hidden" name="action" value="kick">
                                                <input type="hidden" name="username" value="<?= htmlspecialchars($user['name']) ?>">
                                                <button type="submit" class="btn-action kick" title="Kick">
                                                    <i class="bi bi-lightning-fill"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                        
                                        <?php if ($user['disabled']): ?>
                                            <form method="POST" style="display: inline; margin: 0;">
                                                <?= csrfField() ?>
                                                <input type="hidden" name="action" value="restore">
                                                <input type="hidden" name="username" value="<?= htmlspecialchars($user['name']) ?>">
                                                <button type="submit" class="btn-action restore" title="Restore">
                                                    <i class="bi bi-play-fill"></i>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <form method="POST" style="display: inline; margin: 0;" 
                                                  onsubmit="return confirm('Suspend user <?= htmlspecialchars($user['name']) ?>?')">
                                                <?= csrfField() ?>
                                                <input type="hidden" name="action" value="suspend">
                                                <input type="hidden" name="username" value="<?= htmlspecialchars($user['name']) ?>">
                                                <button type="submit" class="btn-action suspend" title="Suspend">
                                                    <i class="bi bi-pause-fill"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                        
                                        <?php if (!$isBranchUser): ?>
                                            <form method="POST" style="display: inline; margin: 0;" 
                                                  onsubmit="return confirm('HAPUS user <?= htmlspecialchars($user['name']) ?>?')">
                                                <?= csrfField() ?>
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="username" value="<?= htmlspecialchars($user['name']) ?>">
                                                <button type="submit" class="btn-action delete" title="Hapus">
                                                    <i class="bi bi-trash-fill"></i>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <a href="/branch/customer_edit.php?id=<?= $cust['id'] ?>" 
                                               class="btn-action edit" title="Edit Pelanggan">
                                                <i class="bi bi-pencil-fill"></i>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <?php endif; ?>
</div>
</div>

<!-- Modal Tambah User -->
<div class="modal fade modal-modern" id="addUserModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="add_user">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-person-plus-fill"></i>
                        <span>Tambah User PPPoE</span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="info-box-modal" style="margin-top: 0; margin-bottom: 16px;">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>
                            User akan ditambahkan ke MikroTik cabang <strong><?= htmlspecialchars($userBranchName) ?></strong>.
                        </div>
                    </div>
                    
                    <div class="form-grid-modal">
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-person-badge"></i>
                                Username <span class="required">*</span>
                            </label>
                            <input type="text" name="new_username" class="form-control-modal" required
                                   placeholder="client001">
                        </div>
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-key-fill"></i>
                                Password <span class="required">*</span>
                            </label>
                            <input type="text" name="new_password" class="form-control-modal" required
                                   placeholder="password123">
                        </div>
                    </div>
                    
                    <div class="form-grid-modal">
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-sliders"></i>
                                PPP Profile
                            </label>
                            <select name="new_profile" class="form-select-modal">
                                <?php if (empty($pppProfiles)): ?>
                                    <option value="default">default (MikroTik offline)</option>
                                <?php else: ?>
                                    <?php foreach ($pppProfiles as $p): ?>
                                        <option value="<?= htmlspecialchars($p) ?>"><?= htmlspecialchars($p) ?></option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <small class="form-hint-modal">
                                <i class="bi bi-info-circle"></i>
                                <?= count($pppProfiles) ?> profiles tersedia
                            </small>
                        </div>
                        <div class="form-group-modal">
                            <label class="form-label-modal">
                                <i class="bi bi-chat-left-text"></i>
                                Comment
                            </label>
                            <input type="text" name="new_comment" class="form-control-modal" 
                                   placeholder="Opsional">
                        </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>Simpan User</span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}
</script>

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