<?php
/**
 * sidebar_supir.php - Sidebar untuk Supir
 * DIPERBAIKI - Notifikasi real-time dengan AJAX
 */
$activeMenu = $activeMenu ?? 'dashboard';
$pendingCount = $pendingCount ?? 0;
$userName = $_SESSION['nama'] ?? 'Pengguna';

// ============================================
// AMBIL FOTO PROFIL DARI SESSION
// ============================================
$userFoto = $_SESSION['foto'] ?? '';
$fotoUrl = '';

if (!empty($userFoto)) {
    $fotoPath = __DIR__ . '/../../uploads/profile/' . $userFoto;
    if (file_exists($fotoPath)) {
        $fotoUrl = BASE_URL . '/uploads/profile/' . $userFoto;
    } else {
        $userFoto = '';
        unset($_SESSION['foto']);
        
        if (isset($_SESSION['user_id'])) {
            try {
                if (isset($this->pdo)) {
                    $stmt = $this->pdo->prepare("UPDATE users SET foto = NULL WHERE id = ?");
                    $stmt->execute([$_SESSION['user_id']]);
                }
            } catch (Exception $e) {
                // Ignore
            }
        }
    }
}

// ============================================
// AMBIL UNREAD COUNT DARI DATABASE
// ============================================
$unreadCount = 0;
$user_id = $_SESSION['user_id'] ?? 0;

if ($user_id > 0) {
    try {
        if (isset($this->pdo)) {
            $stmt = $this->pdo->prepare("SELECT COUNT(*) as total FROM notifications WHERE user_id = ? AND is_read = 0");
            $stmt->execute([$user_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $unreadCount = $result['total'] ?? 0;
        }
    } catch (Exception $e) {
        $unreadCount = 0;
    }
}

// Update session agar konsisten
$_SESSION['unreadCount'] = $unreadCount;
?>

<aside class="sidebar">
    <div class="sidebar-header">
        <div class="user-info">
            <div class="user-avatar">
                <?php if (!empty($fotoUrl)): ?>
                    <img src="<?= $fotoUrl ?>" alt="Profile Photo">
                <?php else: ?>
                    <?= strtoupper(substr($userName, 0, 2)) ?>
                <?php endif; ?>
            </div>
            <div class="user-detail">
                <div class="user-name"><?= htmlspecialchars($userName) ?></div>
                <div class="user-role"><i class="fas fa-user-tie"></i> Supir Kapal</div>
            </div>
        </div>
    </div>
    
    <nav class="sidebar-nav">
        <a href="?page=supir&action=dashboard" class="<?= ($activeMenu == 'dashboard') ? 'active' : '' ?>">
            <i class="fas fa-chart-pie icon"></i> 
            <span>Dashboard</span>
        </a>
        <a href="?page=supir&action=kelolaKapal" class="<?= ($activeMenu == 'kelolaKapal') ? 'active' : '' ?>">
            <i class="fas fa-ship icon"></i> 
            <span>Kapal Saya</span>
        </a>
        <a href="?page=supir&action=kelolaRute" class="<?= ($activeMenu == 'kelolaRute') ? 'active' : '' ?>">
            <i class="fas fa-route icon"></i> 
            <span>Kelola Rute</span>
        </a>
        <a href="?page=supir&action=kelolaPesanan" class="<?= ($activeMenu == 'kelolaPesanan') ? 'active' : '' ?>">
            <i class="fas fa-inbox icon"></i> 
            <span>Pesanan Masuk</span>
            <?php if($pendingCount > 0): ?>
                <span class="badge badge-danger"><?= $pendingCount ?></span>
            <?php endif; ?>
        </a>
        <a href="?page=supir&action=pencairanDana" class="<?= ($activeMenu == 'riwayatPencairan') ? 'active' : '' ?>">
            <i class="fas fa-money-bill-wave icon"></i> 
            <span>Riwayat Pencairan</span>
        </a>
        <a href="?page=supir&action=notifikasi" class="<?= ($activeMenu == 'notifikasi') ? 'active' : '' ?>">
            <i class="fas fa-bell icon"></i> 
            <span>Notifikasi</span>
            <span class="badge badge-danger" id="notifBadge">
                <?= $unreadCount > 0 ? $unreadCount : '' ?>
            </span>
        </a>
        
        <div class="nav-divider"></div>
        
        <a href="?page=supir&action=editProfile" class="<?= ($activeMenu == 'editProfile') ? 'active' : '' ?>">
            <i class="fas fa-user-edit icon"></i> 
            <span>Edit Profil</span>
        </a>
    </nav>
    
    <div class="sidebar-footer">
        <a href="?page=logout" onclick="return confirm('Yakin ingin logout?')">
            <i class="fas fa-sign-out-alt icon"></i> 
            <span>Logout</span>
        </a>
    </div>
</aside>

<!-- Tambahkan Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

<style>
/* ============================================
   CSS VARIABLES
   ============================================ */
:root {
    --primary: #2b6cb0;
    --primary-light: #3182ce;
    --primary-dark: #1a4a7a;
    --gray-50: #f7fafc;
    --gray-100: #edf2f7;
    --gray-200: #e2e8f0;
    --gray-300: #cbd5e0;
    --gray-400: #a0aec0;
    --gray-500: #718096;
    --gray-600: #4a5568;
    --gray-700: #2d3748;
    --gray-800: #1a202c;
    --gray-900: #171923;
    --danger: #ef4444;
    --success: #22c55e;
    --warning: #f59e0b;
    --transition: all 0.3s ease;
    --radius: 12px;
    --shadow: 0 4px 20px rgba(0,0,0,0.06);
}

/* ============================================
   SIDEBAR
   ============================================ */
.sidebar {
    width: 250px;
    flex-shrink: 0;
    background: #ffffff;
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    padding: 1.5rem 0;
    position: sticky;
    top: 80px;
    border: 1px solid #e2e8f0;
    transition: var(--transition);
    display: flex;
    flex-direction: column;
    height: fit-content;
    max-height: calc(100vh - 100px);
    overflow-y: auto;
}

/* ============================================
   SIDEBAR HEADER
   ============================================ */
.sidebar-header {
    padding: 0 1.2rem 1.2rem;
    border-bottom: 1px solid #edf2f7;
    margin-bottom: 0.5rem;
}

.sidebar-header .user-info {
    display: flex;
    align-items: center;
    gap: 0.8rem;
}

.sidebar-header .user-avatar {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: linear-gradient(135deg, #2b6cb0, #3182ce);
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 1rem;
    flex-shrink: 0;
    overflow: hidden;
}

.sidebar-header .user-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.sidebar-header .user-name {
    font-weight: 600;
    color: #1a202c;
    font-size: 0.95rem;
}

.sidebar-header .user-role {
    font-size: 0.7rem;
    color: #a0aec0;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.sidebar-header .user-role i {
    font-size: 0.6rem;
}

/* ============================================
   SIDEBAR NAVIGATION
   ============================================ */
.sidebar-nav {
    flex: 1;
    padding: 0.3rem 0.8rem;
}

.sidebar-nav a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.6rem 1rem;
    color: #4a5568;
    font-weight: 500;
    font-size: 0.85rem;
    transition: var(--transition);
    border-radius: 8px;
    text-decoration: none;
    position: relative;
    margin-bottom: 0.15rem;
}

.sidebar-nav a:hover {
    background: #f7fafc;
    color: #1a202c;
    text-decoration: none;
}

.sidebar-nav a.active {
    background: #ebf4ff;
    color: #2b6cb0;
    font-weight: 600;
}

.sidebar-nav a.active .icon {
    color: #2b6cb0;
}

.sidebar-nav a .icon {
    font-size: 0.95rem;
    width: 22px;
    text-align: center;
    flex-shrink: 0;
    color: #718096;
}

.sidebar-nav a.active .icon {
    color: #2b6cb0;
}

.sidebar-nav a span {
    flex: 1;
}

.sidebar-nav a .badge {
    margin-left: auto;
    font-size: 0.6rem;
    font-weight: 700;
    padding: 0.1rem 0.5rem;
    border-radius: 12px;
    min-width: 18px;
    text-align: center;
    line-height: 1.4;
    color: #ffffff;
    animation: pulse-badge 2s infinite;
}

.sidebar-nav a .badge-danger {
    background: #ef4444;
}

.sidebar-nav .nav-divider {
    height: 1px;
    background: #edf2f7;
    margin: 0.5rem 1rem;
}

@keyframes pulse-badge {
    0%, 100% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.1);
    }
}

/* ============================================
   SIDEBAR FOOTER
   ============================================ */
.sidebar-footer {
    padding: 0.8rem 1.2rem 0;
    border-top: 1px solid #edf2f7;
    margin-top: 0.5rem;
}

.sidebar-footer a {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    color: #ef4444;
    font-weight: 500;
    font-size: 0.85rem;
    padding: 0.5rem 1rem;
    transition: var(--transition);
    text-decoration: none;
    border-radius: 8px;
}

.sidebar-footer a:hover {
    background: #fef2f2;
    color: #dc2626;
    text-decoration: none;
}

.sidebar-footer a .icon {
    font-size: 0.95rem;
    width: 22px;
    text-align: center;
    flex-shrink: 0;
}

/* ============================================
   SCROLLBAR STYLING
   ============================================ */
.sidebar::-webkit-scrollbar {
    width: 4px;
}

.sidebar::-webkit-scrollbar-track {
    background: #f7fafc;
}

.sidebar::-webkit-scrollbar-thumb {
    background: #cbd5e0;
    border-radius: 10px;
}

.sidebar::-webkit-scrollbar-thumb:hover {
    background: #a0aec0;
}

/* ============================================
   RESPONSIVE - DESKTOP
   ============================================ */
@media (max-width: 1024px) {
    .sidebar {
        width: 220px;
        padding: 1rem 0;
    }

    .sidebar-nav a {
        padding: 0.5rem 0.8rem;
        font-size: 0.8rem;
    }

    .sidebar-nav a .icon {
        font-size: 0.85rem;
        width: 18px;
    }

    .sidebar-header .user-name {
        font-size: 0.85rem;
    }

    .sidebar-header .user-avatar {
        width: 38px;
        height: 38px;
        font-size: 0.85rem;
    }
}

/* ============================================
   RESPONSIVE - TABLET & MOBILE
   ============================================ */
@media (max-width: 768px) {
    .sidebar {
        width: 100%;
        position: static;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
        gap: 0.4rem;
        border: none;
        box-shadow: none;
        background: transparent;
        padding: 0;
        max-height: none;
        overflow-y: visible;
        border-radius: 0;
        top: 0;
    }

    .sidebar-header {
        display: none;
    }

    .sidebar-nav {
        display: contents;
        padding: 0;
    }

    .sidebar-nav a {
        background: #ffffff;
        border-radius: 10px;
        padding: 0.6rem 0.5rem;
        border: 1px solid #e2e8f0;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        font-size: 0.75rem;
        justify-content: center;
        text-align: center;
        flex-direction: column;
        gap: 0.2rem;
        margin-bottom: 0;
    }

    .sidebar-nav a .icon {
        width: auto;
        font-size: 1.1rem;
    }

    .sidebar-nav a span {
        font-size: 0.7rem;
    }

    .sidebar-nav a .badge {
        margin-left: 0;
        font-size: 0.55rem;
        padding: 0.05rem 0.4rem;
    }

    .sidebar-nav a.active {
        border-bottom: 3px solid #2b6cb0;
        border-left: 1px solid #e2e8f0;
    }

    .sidebar-nav .nav-divider {
        display: none;
    }

    .sidebar-footer {
        display: none;
    }
}

@media (max-width: 480px) {
    .sidebar {
        grid-template-columns: 1fr 1fr;
        gap: 0.3rem;
    }

    .sidebar-nav a {
        padding: 0.4rem 0.3rem;
        font-size: 0.65rem;
        border-radius: 8px;
    }

    .sidebar-nav a .icon {
        font-size: 0.9rem;
    }

    .sidebar-nav a span {
        font-size: 0.6rem;
    }
}

/* ============================================
   STYLE KHUSUS UNTUK BADGE NOTIFIKASI
   ============================================ */
#notifBadge {
    display: <?= $unreadCount > 0 ? 'inline-block' : 'none' ?>;
    min-width: 18px;
    text-align: center;
    background: #ef4444;
    color: #ffffff;
    font-size: 0.6rem;
    font-weight: 700;
    padding: 0.1rem 0.5rem;
    border-radius: 12px;
    line-height: 1.4;
    animation: pulse-badge 2s infinite;
    margin-left: auto;
}
</style>

<!-- ============================================ -->
<!-- JAVASCRIPT UNTUK REAL-TIME NOTIFIKASI -->
<!-- ============================================ -->
<script>
// ============================================
// REAL-TIME UPDATE NOTIFIKASI BADGE
// ============================================
function updateNotifBadge() {
    const userId = <?= json_encode($_SESSION['user_id'] ?? 0) ?>;
    
    if (userId == 0) {
        console.log('User tidak login, skip update badge');
        return;
    }
    
    // Gunakan BASE_URL jika didefinisikan, atau gunakan relative path
    const url = '<?= defined('BASE_URL') ? BASE_URL : '' ?>/index.php?page=supir&action=getUnreadCount';
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            const badge = document.getElementById('notifBadge');
            
            if (!badge) {
                console.log('Badge element not found');
                return;
            }
            
            if (data.count > 0) {
                badge.textContent = data.count;
                badge.style.display = 'inline-block';
                badge.style.animation = 'pulse-badge 2s infinite';
            } else {
                badge.textContent = '';
                badge.style.display = 'none';
                badge.style.animation = 'none';
            }
        })
        .catch(error => {
            console.error('Error updating notification badge:', error);
            // Jika error, coba lagi nanti
        });
}

// ============================================
// UPDATE BADGE SECARA PERIODIK
// ============================================
// Update setiap 5 detik (lebih responsif)
const updateInterval = setInterval(updateNotifBadge, 5000);

// ============================================
// UPDATE SAAT HALAMAN DIMUAT DAN VISIBILITY CHANGE
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    // Delay awal agar halaman selesai load
    setTimeout(updateNotifBadge, 500);
});

// Update saat tab menjadi aktif
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        updateNotifBadge();
    }
});

// ============================================
// CLEANUP INTERVAL SAAT HALAMAN DI TUTUP
// ============================================
window.addEventListener('beforeunload', function() {
    clearInterval(updateInterval);
});

console.log('✅ Notifikasi real-time aktif, update setiap 5 detik');
</script>