<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/Branch.php';
require_once __DIR__ . '/../classes/MikroTik.php'; // ⭐ PASTIKAN DI-REQUIRE

requireRole(['branch_admin','staff']);
$pageTitle = 'Dashboard';

$branchId = currentBranchId();
$db = db();

// ⭐ DIPERBAIKI: Load data cabang DI AWAL
$branch = Branch::find($branchId);
$branchName = $branch['name'] ?? 'Cabang';

// ============================================================================
// STATISTIK DASAR
// ============================================================================
$stmt = $db->prepare("SELECT COUNT(*) FROM customers WHERE branch_id = ? AND status='active'");
$stmt->execute([$branchId]); 
$totalCustomers = (int)$stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM bills b JOIN customers c ON c.id=b.customer_id WHERE c.branch_id=? AND b.status='unpaid'");
$stmt->execute([$branchId]); 
$unpaidBills = (int)$stmt->fetchColumn();

$stmt = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM bills b JOIN customers c ON c.id=b.customer_id WHERE c.branch_id=? AND b.status='paid' AND MONTH(b.paid_at)=MONTH(NOW()) AND YEAR(b.paid_at)=YEAR(NOW())");
$stmt->execute([$branchId]); 
$monthlyRevenue = (float)$stmt->fetchColumn();

// ============================================================================
// SALDO CABANG (DIPERBAIKI: Handle null/0 dengan benar)
// ============================================================================
$stmt = $db->prepare("SELECT COALESCE(SUM(available_balance),0) FROM branch_balances WHERE branch_id = ?");
$stmt->execute([$branchId]);
$branchBalanceResult = $stmt->fetchColumn();
$branchBalance = ($branchBalanceResult !== false && $branchBalanceResult !== null) 
    ? (float)$branchBalanceResult 
    : (float)($branch['balance'] ?? 0);

$stmt = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM branch_withdrawals WHERE branch_id = ? AND status = 'pending'");
$stmt->execute([$branchId]);
$pendingWithdrawalResult = $stmt->fetchColumn();
$pendingWithdrawal = ($pendingWithdrawalResult !== false && $pendingWithdrawalResult !== null) 
    ? (float)$pendingWithdrawalResult 
    : (float)($branch['pending_withdrawal'] ?? 0);

$availableBalance = $branchBalance - $pendingWithdrawal;

// ============================================================================
// ⭐ STATUS ONLINE MIKROTIK (DIPERBAIKI: Pass $branchId ke constructor)
// ============================================================================
$totalOnline = 0;
$mtConnected = false;
$mtError = '';

try {
    $stmt = $db->prepare("SELECT pppoe_username FROM customers WHERE branch_id = ? AND status = 'active' AND pppoe_username IS NOT NULL AND pppoe_username != ''");
    $stmt->execute([$branchId]);
    $activeUsers = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // ⭐ DIPERBAIKI: Kirim $branchId ke constructor MikroTik
    $mt = new MikroTik($branchId);
    $actives = $mt->getActiveConnections();
    $mtConnected = empty($mt->lastError);
    $mtError = $mt->lastError ?? '';
    
    if ($mtConnected && !empty($activeUsers)) {
        foreach ($actives as $active) {
            if (isset($active['name']) && in_array($active['name'], $activeUsers)) {
                $totalOnline++;
            }
        }
    }
} catch (\Throwable $e) {
    $mtConnected = false;
    $mtError = $e->getMessage();
}

// ============================================================================
// RECENT ACTIVITIES
// ============================================================================
$recentActivities = [];
try {
    $stmt = $db->prepare("
        SELECT l.*, u.username 
        FROM activity_logs l 
        LEFT JOIN users u ON l.user_id = u.id 
        WHERE u.branch_id = ? OR u.branch_id IS NULL
        ORDER BY l.created_at DESC 
        LIMIT 6
    ");
    $stmt->execute([$branchId]);
    $recentActivities = $stmt->fetchAll();
} catch (\Throwable $e) {
    $recentActivities = [];
}

// Helper: time ago
function timeAgo($datetime) {
    try {
        $now = new DateTime();
        $past = new DateTime($datetime);
        $diff = $now->diff($past);
        if ($diff->y > 0) return $diff->y . ' thn';
        if ($diff->m > 0) return $diff->m . ' bln';
        if ($diff->d > 0) return $diff->d . ' hr';
        if ($diff->h > 0) return $diff->h . ' jm';
        if ($diff->i > 0) return $diff->i . ' mnt';
        return 'Baru';
    } catch (\Throwable $e) {
        return '-';
    }
}

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;

    margin-bottom: 20px; /* Tambahkan ini */
}

.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-user {
    display: flex; align-items: center; gap: 10px;
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.2);
    padding: 6px 14px 6px 6px;
    border-radius: 30px;
    color: white;
    text-decoration: none;
    transition: all 0.3s ease;
}
.navbar-user:hover { background: rgba(255,255,255,0.3); color: white; }
.navbar-user-avatar {
    width: 34px; height: 34px;
    border-radius: 50%;
    background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%);
    display: flex; align-items: center; justify-content: center;
    font-weight: 800; font-size: 0.9rem;
    flex-shrink: 0;
}
.navbar-user-name { font-size: 0.85rem; font-weight: 600; white-space: nowrap; }
.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: 20px auto 0;
}
/* === WELCOME BANNER === */
.welcome-banner {
    background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);
    border-radius: 20px;
    padding: 28px;
    color: white;
    margin-bottom: 22px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 102, 204, 0.2);
}
.welcome-banner::before {
    content: '';
    position: absolute;
    top: -50%; right: -20%;
    width: 400px; height: 400px;
    background: radial-gradient(circle, rgba(255,255,255,0.15) 0%, transparent 70%);
    border-radius: 50%;
}
.welcome-banner::after {
    content: '';
    position: absolute;
    bottom: -30%; left: -10%;
    width: 300px; height: 300px;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    border-radius: 50%;
}
.welcome-content {
    position: relative;
    z-index: 2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}
.welcome-text h2 { font-size: 1.7rem; font-weight: 800; margin: 0 0 6px; }
.welcome-text p { margin: 0; opacity: 0.9; font-size: 0.92rem; }
.welcome-branch-badge {
    display: inline-flex; align-items: center; gap: 6px;
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    margin-top: 8px;
}
.welcome-date {
    text-align: right;
    background: rgba(255,255,255,0.1);
    padding: 12px 18px;
    border-radius: 14px;
    backdrop-filter: blur(10px);
}
.welcome-date-day { font-size: 2rem; font-weight: 800; line-height: 1; }
.welcome-date-info { font-size: 0.85rem; opacity: 0.9; margin-top: 4px; }

/* === 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;
    cursor: pointer;
    text-decoration: none;
    color: inherit;
    display: block;
    border-left: 4px solid transparent;
}
.summary-card:hover { transform: translateY(-4px); box-shadow: 0 12px 25px rgba(0,0,0,0.1); color: inherit; }
.summary-card.primary { border-left-color: #0066CC; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card.info { border-left-color: #00B8D4; }
.summary-card.purple { border-left-color: #9C27B0; }

.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.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card.purple .summary-card-icon { background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%); }

.summary-card-value { font-size: 1.6rem; font-weight: 800; margin-bottom: 4px; letter-spacing: -0.5px; color: #003D7A; line-height: 1.1; word-break: break-word; }
.summary-card-footer { font-size: 0.78rem; color: #999; display: flex; align-items: center; gap: 5px; }
.summary-card-footer .trend-up { color: #00C853; font-weight: 700; }
.summary-card-footer .trend-down { color: #DC3545; font-weight: 700; }

/* === SECTION HEADER === */
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; margin-top: 8px; }
.section-title { font-size: 1.1rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 8px; }
.section-title i { color: #0066CC; font-size: 1.2rem; }

/* === CARD MODERN === */
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); overflow: hidden; margin-bottom: 20px; border: none; }
.card-header-modern { color: white; padding: 14px 18px; font-size: 0.95rem; 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.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.card-header-modern.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.card-header-modern.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 8px; }
.card-body-modern { padding: 18px; }

/* === QUICK ACTIONS === */
.quick-actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
}
.quick-action-card {
    background: white;
    border: 2px solid #f0f0f0;
    border-radius: 14px;
    padding: 16px 12px;
    text-align: center;
    text-decoration: none;
    transition: all 0.3s ease;
    color: inherit;
    display: block;
}
.quick-action-card:hover { border-color: #0066CC; transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0, 102, 204, 0.12); color: inherit; }
.quick-action-icon { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; color: white; margin: 0 auto 8px; }
.quick-action-icon.blue { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.quick-action-icon.green { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.quick-action-icon.orange { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.quick-action-icon.red { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.quick-action-icon.purple { background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%); }
.quick-action-icon.cyan { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.quick-action-title { font-weight: 700; color: #003D7A; font-size: 0.82rem; margin-bottom: 2px; }
.quick-action-desc { font-size: 0.7rem; color: #999; }

/* === ACTIVITY LIST === */
.activity-list { display: grid; gap: 8px; }
.activity-item { display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: #f8fafc; border-radius: 12px; transition: all 0.2s ease; }
.activity-item:hover { background: #eef5fc; transform: translateX(2px); }
.activity-icon { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.9rem; flex-shrink: 0; }
.activity-icon.success { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.activity-icon.danger { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.activity-icon.warning { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.activity-icon.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.activity-icon.info { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.activity-icon.secondary { background: linear-gradient(135deg, #607D8B 0%, #90A4AE 100%); }

.activity-content { flex: 1; min-width: 0; }
.activity-title { font-weight: 600; color: #003D7A; font-size: 0.82rem; margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.activity-meta { font-size: 0.72rem; color: #999; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.activity-time { color: #0066CC; font-weight: 600; font-size: 0.72rem; white-space: nowrap; margin-left: auto; flex-shrink: 0; }

/* === EMPTY STATE === */
.empty-state { text-align: center; padding: 30px 15px; }
.empty-state-icon { width: 60px; height: 60px; margin: 0 auto 12px; background: #f8fafc; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.7rem; color: #ccc; }
.empty-state-title { color: #666; font-weight: 600; margin-bottom: 4px; font-size: 0.95rem; }

/* === ALERT MODERN === */
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 20px; 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; }

/* === TWO COLUMN LAYOUT === */
.two-col-layout { display: grid; grid-template-columns: 1fr; gap: 20px; }
@media (min-width: 992px) { .two-col-layout { grid-template-columns: 2fr 1fr; } }

/* === BALANCE SIDEBAR === */
.balance-card { background: white; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); overflow: hidden; margin-bottom: 20px; }
.balance-display { background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%); border-radius: 14px; padding: 20px; text-align: center; margin: 18px; }
.balance-label { font-size: 0.8rem; color: #2e7d32; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }
.balance-value { font-size: 1.8rem; font-weight: 800; color: #1b5e20; letter-spacing: -0.5px; word-break: break-word; }
.balance-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 0 18px 18px; }
.balance-item { background: #f8fafc; border-radius: 10px; padding: 12px; text-align: center; }
.balance-item-label { font-size: 0.72rem; color: #666; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; font-weight: 600; }
.balance-item-value { font-size: 0.95rem; font-weight: 700; color: #003D7A; }
.balance-item-value.warning { color: #FF9900; }
.balance-item-value.success { color: #00C853; }
.btn-withdraw { display: block; margin: 0 18px 18px; padding: 12px; background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); color: white; border: none; border-radius: 12px; font-size: 0.92rem; font-weight: 700; cursor: pointer; transition: all 0.3s ease; text-align: center; text-decoration: none; box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }
.btn-withdraw:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(255, 153, 0, 0.4); color: white; }

/* === RESPONSIVE === */
@media (max-width: 768px) {
    .navbar-modern { padding: 10px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-greeting, .navbar-badge, .navbar-user-name { display: none; }
    .navbar-user { padding: 4px; }

    .welcome-banner { padding: 20px; }
    .welcome-text h2 { font-size: 1.3rem; }
    .welcome-text p { font-size: 0.85rem; }
    .welcome-date { padding: 10px 14px; }
    .welcome-date-day { font-size: 1.6rem; }
    .welcome-date-info { font-size: 0.78rem; }
    .summary-row { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .summary-card { padding: 14px; }
    .summary-card-value { font-size: 1.25rem; }
    .summary-card-title { font-size: 0.7rem; }
    .summary-card-icon { width: 34px; height: 34px; font-size: 1rem; }
    .section-title { font-size: 1rem; }
    .quick-actions-grid { grid-template-columns: repeat(3, 1fr); gap: 8px; }
    .quick-action-card { padding: 12px 8px; }
    .quick-action-icon { width: 42px; height: 42px; font-size: 1.1rem; margin-bottom: 6px; }
    .quick-action-title { font-size: 0.75rem; }
    .quick-action-desc { display: none; }
    .card-header-modern { padding: 12px 14px; font-size: 0.9rem; }
    .card-body-modern { padding: 14px; }
    .balance-value { font-size: 1.5rem; }
    .balance-grid { grid-template-columns: 1fr; }
}

@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; }
    .welcome-banner { padding: 16px; }
    .welcome-text h2 { font-size: 1.15rem; }
    .welcome-date-day { font-size: 1.4rem; }
    .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; }
    .quick-actions-grid { grid-template-columns: repeat(2, 1fr); }
    .activity-item { padding: 8px 10px; }
    .activity-icon { width: 32px; height: 32px; font-size: 0.85rem; }
    .activity-title { font-size: 0.78rem; }
    .balance-display { padding: 16px; }
    .balance-value { font-size: 1.3rem; }
}
</style>

<!-- ⭐ Navbar dipindah ke luar 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">Selamat datang kembali 👋</p>
            <h1 class="navbar-title">Dashboard <?= htmlspecialchars($branchName) ?></h1>
        </div>
    </div>
    <div class="navbar-right">
        <span class="navbar-badge">
            <i class="bi bi-building"></i> <?= htmlspecialchars($branchName) ?>
        </span>
        <a href="/logout.php" class="navbar-user" onclick="return confirm('Yakin ingin logout?')">
            <div class="navbar-user-avatar">
                <?= strtoupper(substr($_SESSION['username'] ?? 'U', 0, 1)) ?>
            </div>
            <span class="navbar-user-name"><?= htmlspecialchars($_SESSION['username'] ?? 'User') ?></span>
            <i class="bi bi-box-arrow-right"></i>
        </a>
    </div>
</div>

<div class="main-content">
    <?= flashMessage() ?>

    <!-- Welcome Banner -->
    <div class="welcome-banner">
        <div class="welcome-content">
            <div class="welcome-text">
                <h2>Halo, <?= htmlspecialchars($_SESSION['name'] ?? $_SESSION['username'] ?? 'Admin') ?>! 👋</h2>
                <p>Berikut ringkasan performa cabang Anda hari ini.</p>
                <div class="welcome-branch-badge">
                    <i class="bi bi-building-fill"></i>
                    <span>Cabang: <?= htmlspecialchars($branchName) ?></span>
                </div>
            </div>
            <div class="welcome-date">
                <div class="welcome-date-day"><?= date('d') ?></div>
                <div class="welcome-date-info">
                    <?= strftime('%B %Y', strtotime('now')) ?><br>
                    <i class="bi bi-clock"></i> <span id="liveTime"><?= date('H:i') ?> WIB</span>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Summary Cards -->
    <div class="summary-row">
        <a href="/branch/customers.php" class="summary-card primary">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Pelanggan Aktif</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">
                <?php if ($mtConnected): ?>
                    <i class="bi bi-wifi" style="color: #00C853;"></i>
                    <span class="trend-up"><?= $totalOnline ?> online</span>
                <?php else: ?>
                    <i class="bi bi-circle-fill" style="font-size: 0.5rem; color: #00C853;"></i>
                    Pelanggan aktif
                <?php endif; ?>
            </div>
        </a>
        
        <a href="/branch/bills.php?status=paid" class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Pendapatan Bulan Ini</h6>
                <div class="summary-card-icon"><i class="bi bi-cash-stack"></i></div>
            </div>
            <div class="summary-card-value">Rp <?= number_format($monthlyRevenue, 0, ',', '.') ?></div>
            <div class="summary-card-footer">
                <i class="bi bi-arrow-up-short"></i>
                <span class="trend-up">Tagihan lunas</span>
            </div>
        </a>
        
        <a href="/branch/bills.php?status=unpaid" class="summary-card warning">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Tagihan Belum Bayar</h6>
                <div class="summary-card-icon"><i class="bi bi-exclamation-triangle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($unpaidBills) ?></div>
            <div class="summary-card-footer">
                <i class="bi bi-clock"></i>
                Menunggu pembayaran
            </div>
        </a>
        
        <a href="/branch/withdrawal.php" class="summary-card info">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Pending Withdrawal</h6>
                <div class="summary-card-icon"><i class="bi bi-hourglass-split"></i></div>
            </div>
            <div class="summary-card-value">Rp <?= number_format($pendingWithdrawal, 0, ',', '.') ?></div>
            <div class="summary-card-footer">
                <?php if ($pendingWithdrawal > 0): ?>
                    <i class="bi bi-bell-fill" style="color: #FF9900;"></i>
                    <span class="trend-down">Menunggu approval</span>
                <?php else: ?>
                    <i class="bi bi-check-circle"></i>
                    Tidak ada pending
                <?php endif; ?>
            </div>
        </a>
    </div>

    <!-- ⭐ DIPERBAIKI: Layout 2 kolom dengan CSS Grid -->
    <div class="two-col-layout">
        <!-- Kolom Kiri: Quick Actions + Activities -->
        <div>
            <!-- Quick Actions -->
            <div class="section-header">
                <h3 class="section-title">
                    <i class="bi bi-lightning-charge-fill"></i>
                    <span>Aksi Cepat</span>
                </h3>
            </div>
            
            <div class="quick-actions-grid">
                <a href="/branch/customer_add.php" class="quick-action-card">
                    <div class="quick-action-icon blue"><i class="bi bi-person-plus-fill"></i></div>
                    <div class="quick-action-title">Tambah Pelanggan</div>
                    <div class="quick-action-desc">Pelanggan baru</div>
                </a>
                
                <a href="/branch/bills.php" class="quick-action-card">
                    <div class="quick-action-icon green"><i class="bi bi-receipt"></i></div>
                    <div class="quick-action-title">Kelola Tagihan</div>
                    <div class="quick-action-desc">Invoice & billing</div>
                </a>
                
                <a href="/branch/customers.php" class="quick-action-card">
                    <div class="quick-action-icon orange"><i class="bi bi-people-fill"></i></div>
                    <div class="quick-action-title">Data Pelanggan</div>
                    <div class="quick-action-desc">Lihat semua</div>
                </a>
                
              
                
                <a href="/branch/broadcast.php" class="quick-action-card">
                    <div class="quick-action-icon purple"><i class="bi bi-megaphone-fill"></i></div>
                    <div class="quick-action-title">Broadcast WA</div>
                    <div class="quick-action-desc">Pesan massal</div>
                </a>
                
                <a href="/branch/mikrotik_status.php" class="quick-action-card">
                    <div class="quick-action-icon cyan"><i class="bi bi-router"></i></div>
                    <div class="quick-action-title">MikroTik</div>
                    <div class="quick-action-desc">Status router</div>
                </a>
            </div>

            <!-- Recent Activities -->
            <div class="card-modern">
                <div class="card-header-modern primary">
                    <div class="title-left">
                        <i class="bi bi-activity"></i>
                        <span>Aktivitas Terbaru</span>
                    </div>
                </div>
                <div class="card-body-modern">
                    <?php if (empty($recentActivities)): ?>
                        <div class="empty-state">
                            <div class="empty-state-icon"><i class="bi bi-clock-history"></i></div>
                            <h5 class="empty-state-title">Belum ada aktivitas</h5>
                        </div>
                    <?php else: ?>
                        <div class="activity-list">
                            <?php foreach ($recentActivities as $act): 
                                $action = strtolower($act['action'] ?? '');
                                $icon = 'bi-circle';
                                $color = 'secondary';
                                if (strpos($action, 'login') !== false) { $icon = 'bi-box-arrow-in-right'; $color = 'success'; }
                                elseif (strpos($action, 'logout') !== false) { $icon = 'bi-box-arrow-right'; $color = 'secondary'; }
                                elseif (strpos($action, 'create') !== false || strpos($action, 'add') !== false) { $icon = 'bi-plus-circle'; $color = 'primary'; }
                                elseif (strpos($action, 'update') !== false || strpos($action, 'edit') !== false) { $icon = 'bi-pencil'; $color = 'warning'; }
                                elseif (strpos($action, 'delete') !== false) { $icon = 'bi-trash'; $color = 'danger'; }
                                elseif (strpos($action, 'approve') !== false) { $icon = 'bi-check-circle'; $color = 'success'; }
                                elseif (strpos($action, 'reject') !== false) { $icon = 'bi-x-circle'; $color = 'danger'; }
                                elseif (strpos($action, 'payment') !== false || strpos($action, 'pay') !== false) { $icon = 'bi-cash-stack'; $color = 'success'; }
                                elseif (strpos($action, 'broadcast') !== false) { $icon = 'bi-megaphone'; $color = 'info'; }
                            ?>
                                <div class="activity-item">
                                    <div class="activity-icon <?= $color ?>">
                                        <i class="bi <?= $icon ?>"></i>
                                    </div>
                                    <div class="activity-content">
                                        <div class="activity-title">
                                            <?= htmlspecialchars($act['description'] ?? $act['action']) ?>
                                        </div>
                                        <div class="activity-meta">
                                            <i class="bi bi-person-circle"></i>
                                            <span><?= htmlspecialchars($act['username'] ?? 'System') ?></span>
                                        </div>
                                    </div>
                                    <div class="activity-time">
                                        <?= timeAgo($act['created_at']) ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Kolom Kanan: Balance Info -->
        <div>
           

            <!-- MikroTik Status Card -->
            <div class="card-modern">
                <div class="card-header-modern <?= $mtConnected ? 'success' : 'warning' ?>">
                    <div class="title-left">
                        <i class="bi bi-router"></i>
                        <span>Status MikroTik</span>
                    </div>
                </div>
                <div class="card-body-modern">
                    <?php if ($mtConnected): ?>
                        <div style="text-align: center; padding: 10px;">
                            <div style="font-size: 2.5rem; color: #00C853; margin-bottom: 8px;">
                                <i class="bi bi-check-circle-fill"></i>
                            </div>
                            <div style="font-weight: 700; color: #1b5e20; font-size: 1rem; margin-bottom: 4px;">
                                Terhubung
                            </div>
                            <div style="color: #666; font-size: 0.85rem;">
                                <?= $totalOnline ?> dari <?= $totalCustomers ?> pelanggan online
                            </div>
                        </div>
                    <?php else: ?>
                        <div style="text-align: center; padding: 10px;">
                            <div style="font-size: 2.5rem; color: #FF9900; margin-bottom: 8px;">
                                <i class="bi bi-exclamation-triangle-fill"></i>
                            </div>
                            <div style="font-weight: 700; color: #f57c00; font-size: 1rem; margin-bottom: 4px;">
                                Tidak Terhubung
                            </div>
                            <div style="color: #666; font-size: 0.85rem; margin-bottom: 12px;">
                                <?= htmlspecialchars(substr($mtError, 0, 80)) ?>
                            </div>
                            <a href="/branch/mikrotik_settings.php" class="btn-withdraw" style="display: inline-block; width: auto; padding: 8px 16px; font-size: 0.85rem;">
                                <i class="bi bi-gear-fill"></i> Cek Pengaturan
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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

// Live clock
function updateClock() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const el = document.getElementById('liveTime');
    if (el) el.textContent = `${hours}:${minutes}:${seconds} WIB`;
}
setInterval(updateClock, 1000);
updateClock();
</script>

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