<?php
/**
 * includes/sidebar_admin.php - Sidebar untuk Admin
 * DIPERBAIKI - Dengan sistem notifikasi yang akurat
 */
$activeMenu = $activeMenu ?? 'dashboard';
$userName = $_SESSION['nama'] ?? 'Admin';

// ============================================
// KONEKSI DATABASE
// ============================================
if (!isset($db) || !$db instanceof mysqli) {
    $possiblePaths = [
        __DIR__ . '/../../config/database.php',
        __DIR__ . '/../config/database.php',
        dirname(__DIR__, 2) . '/config/database.php',
    ];
    foreach ($possiblePaths as $path) {
        if (file_exists($path)) {
            require_once $path;
            if (isset($db) && $db instanceof mysqli) {
                break;
            }
        }
    }
}

if (!isset($db) || !$db instanceof mysqli) {
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $possibleDatabases = ['platform_kapal_samosir', 'reservasi_kapal_wisata', 'reservasi_kapal', 'kapal_wisata'];
    foreach ($possibleDatabases as $dbName) {
        try {
            $db = new mysqli($host, $username, $password, $dbName);
            if (!$db->connect_error) {
                $db->set_charset("utf8mb4");
                break;
            }
        } catch (Exception $e) {
            continue;
        }
    }
}

// ============================================
// FUNGSI GET NOTIFICATIONS DENGAN CACHE
// ============================================
function getNotificationCounts($db) {
    // Gunakan cache untuk mengurangi query
    $cacheKey = 'admin_notifications_' . session_id();
    $cacheFile = sys_get_temp_dir() . '/' . $cacheKey . '.cache';
    $cacheTime = 30; // Cache 30 detik
    
    // Cek cache
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
        $data = file_get_contents($cacheFile);
        if ($data !== false) {
            $cached = json_decode($data, true);
            if ($cached !== null && isset($cached['valid']) && $cached['valid']) {
                return $cached;
            }
        }
    }
    
    // Query database
    $counts = [
        'kapal' => 0,
        'pesanan' => 0,
        'hapus' => 0,
        'pembayaran' => 0,
        'claim' => 0,
        'pencairan' => 0,
        'total' => 0
    ];
    
    if ($db && $db instanceof mysqli) {
        // 1. Kapal menunggu verifikasi
        $result = $db->query("SELECT COUNT(*) as total FROM kapal WHERE status_verifikasi = 'pending'");
        if ($result && $row = $result->fetch_assoc()) {
            $counts['kapal'] = (int)$row['total'];
        }
        
        // 2. Pesanan pending
        $result = $db->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pesanan = 'pending'");
        if ($result && $row = $result->fetch_assoc()) {
            $counts['pesanan'] = (int)$row['total'];
        }
        
        // 3. Request hapus pending
        $checkTable = $db->query("SHOW TABLES LIKE 'request_hapus_kapal'");
        if ($checkTable && $checkTable->num_rows > 0) {
            $result = $db->query("SELECT COUNT(*) as total FROM request_hapus_kapal WHERE hapus_request = 'pending'");
            if ($result && $row = $result->fetch_assoc()) {
                $counts['hapus'] = (int)$row['total'];
            }
        }
        
        // 4. Pembayaran menunggu konfirmasi
        $result = $db->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pembayaran = 'menunggu_konfirmasi'");
        if ($result && $row = $result->fetch_assoc()) {
            $counts['pembayaran'] = (int)$row['total'];
        }
        
        // 5. Claim pending
        $checkClaim = $db->query("SHOW TABLES LIKE 'claim_pengembalian'");
        if ($checkClaim && $checkClaim->num_rows > 0) {
            $result = $db->query("SELECT COUNT(*) as total FROM claim_pengembalian WHERE status_claim = 'menunggu'");
            if ($result && $row = $result->fetch_assoc()) {
                $counts['claim'] = (int)$row['total'];
            }
        }
        
        // 6. Pencairan dana tertahan
        $result = $db->query("SELECT COUNT(*) as total FROM pesanan WHERE status_pencairan = 'belum' AND status_pembayaran = 'lunas'");
        if ($result && $row = $result->fetch_assoc()) {
            $counts['pencairan'] = (int)$row['total'];
        }
        
        $counts['total'] = array_sum($counts);
        $counts['valid'] = true;
        $counts['timestamp'] = time();
        
        // Simpan cache
        file_put_contents($cacheFile, json_encode($counts));
    }
    
    return $counts;
}

// Ambil data notifikasi
$notifications = getNotificationCounts($db);

// Assign ke variabel untuk digunakan di HTML
$pendingKapalCount = $notifications['kapal'];
$pendingPesananCount = $notifications['pesanan'];
$pendingHapusCount = $notifications['hapus'];
$pendingPembayaranCount = $notifications['pembayaran'];
$pendingClaimCount = $notifications['claim'];
$pendingPencairanCount = $notifications['pencairan'];
$totalNotifications = $notifications['total'];

// Debug (hapus di production)
// error_log("Notifikasi: Kapal=$pendingKapalCount, Pesanan=$pendingPesananCount, Hapus=$pendingHapusCount");
?>

<aside class="sidebar">
    <div class="sidebar-header">
        <div class="user-info">
            <div class="user-avatar">
                <?= strtoupper(substr($userName, 0, 2)) ?>
            </div>
            <div class="user-detail">
                <div class="user-name"><?= htmlspecialchars($userName) ?></div>
                <div class="user-role"><i class="fas fa-user-shield"></i> Administrator</div>
            </div>
        </div>
    </div>
    
    <nav class="sidebar-nav">
        <!-- Dashboard -->
        <a href="?page=admin&action=dashboard" class="<?= ($activeMenu == 'dashboard') ? 'active' : '' ?>">
            <i class="fas fa-chart-pie icon"></i> 
            <span>Dashboard</span>
        </a>
        
        <!-- Kelola Kapal -->
        <a href="?page=admin&action=kelolaKapal" class="<?= ($activeMenu == 'kelolaKapal') ? 'active' : '' ?>" id="kelolaKapalLink">
            <i class="fas fa-ship icon"></i> 
            <span>Kelola Kapal</span>
            <?php if($pendingKapalCount > 0): ?>
                <span class="badge badge-danger" id="kapalBadge"><?= $pendingKapalCount > 99 ? '99+' : $pendingKapalCount ?></span>
            <?php else: ?>
                <span class="badge badge-danger" id="kapalBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Kelola Pesanan -->
        <a href="?page=admin&action=kelolaPesanan" class="<?= ($activeMenu == 'kelolaPesanan') ? 'active' : '' ?>" id="kelolaPesananLink">
            <i class="fas fa-clipboard-list icon"></i> 
            <span>Kelola Pesanan</span>
            <?php if($pendingPesananCount > 0): ?>
                <span class="badge badge-warning" id="pesananBadge"><?= $pendingPesananCount > 99 ? '99+' : $pendingPesananCount ?></span>
            <?php else: ?>
                <span class="badge badge-warning" id="pesananBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Kelola Supir -->
        <a href="?page=admin&action=kelolaSupir" class="<?= ($activeMenu == 'kelolaSupir') ? 'active' : '' ?>">
            <i class="fas fa-users icon"></i> 
            <span>Kelola Supir</span>
        </a>
        
        <!-- Request Hapus Kapal -->
        <a href="?page=admin&action=requestHapusKapal" class="<?= ($activeMenu == 'request_hapus_kapal') ? 'active' : '' ?>" id="requestHapusLink">
            <i class="fas fa-trash-alt icon"></i> 
            <span>Request Hapus Kapal</span>
            <?php if($pendingHapusCount > 0): ?>
                <span class="badge badge-danger" id="requestHapusBadge"><?= $pendingHapusCount > 99 ? '99+' : $pendingHapusCount ?></span>
            <?php else: ?>
                <span class="badge badge-danger" id="requestHapusBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Konfirmasi Pembayaran -->
        <a href="?page=admin&action=konfirmasiPembayaran" class="<?= ($activeMenu == 'konfirmasiPembayaran') ? 'active' : '' ?>" id="konfirmasiPembayaranLink">
            <i class="fas fa-credit-card icon"></i> 
            <span>Konfirmasi Pembayaran</span>
            <?php if($pendingPembayaranCount > 0): ?>
                <span class="badge badge-warning" id="pembayaranBadge"><?= $pendingPembayaranCount > 99 ? '99+' : $pendingPembayaranCount ?></span>
            <?php else: ?>
                <span class="badge badge-warning" id="pembayaranBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Pencairan Dana -->
        <a href="?page=admin&action=pencairanDana" class="<?= ($activeMenu == 'pencairanDana') ? 'active' : '' ?>" id="pencairanDanaLink">
            <i class="fas fa-money-bill-wave icon"></i> 
            <span>Pencairan Dana</span>
            <?php if($pendingPencairanCount > 0): ?>
                <span class="badge badge-info" id="pencairanBadge"><?= $pendingPencairanCount > 99 ? '99+' : $pendingPencairanCount ?></span>
            <?php else: ?>
                <span class="badge badge-info" id="pencairanBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Claim Pengembalian -->
        <a href="?page=admin&action=claimPengembalian" class="<?= ($activeMenu == 'claimPengembalian') ? 'active' : '' ?>" id="claimPengembalianLink">
            <i class="fas fa-hand-holding-usd icon"></i> 
            <span>Claim Pengembalian</span>
            <?php if($pendingClaimCount > 0): ?>
                <span class="badge badge-danger" id="claimBadge"><?= $pendingClaimCount > 99 ? '99+' : $pendingClaimCount ?></span>
            <?php else: ?>
                <span class="badge badge-danger" id="claimBadge" style="display:none;">0</span>
            <?php endif; ?>
        </a>
        
        <!-- Laporan -->
        <a href="?page=admin&action=laporan" class="<?= ($activeMenu == 'laporan') ? 'active' : '' ?>">
            <i class="fas fa-file-invoice-dollar icon"></i> 
            <span>Laporan</span>
        </a>
        
        <div class="nav-divider"></div>
        
        <!-- Logout -->
        <a href="?page=logout" onclick="return confirm('Yakin ingin logout?')">
            <i class="fas fa-sign-out-alt icon"></i> 
            <span>Logout</span>
        </a>
    </nav>
</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 & STYLING (SAME AS BEFORE)
   ============================================ */
: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;
    --info: #3b82f6;
    --secondary: #6b7280;
    --transition: all 0.3s ease;
    --radius: 12px;
    --shadow: 0 4px 20px rgba(0,0,0,0.06);
}

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

.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-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;
    display: flex;
    align-items: center;
    gap: 0.3rem;
}

.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 .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 a .badge-warning {
    background: #f59e0b;
}

.sidebar-nav a .badge-success {
    background: #22c55e;
}

.sidebar-nav a .badge-info {
    background: #3b82f6;
}

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

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

/* ============================================
   RESPONSIVE
   ============================================ */
@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;
    }
}

@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 .nav-divider { 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>

<!-- ============================================
     JAVASCRIPT NOTIFIKASI REAL-TIME
     ============================================ -->
<script>
// ============================================
// CONFIGURASI
// ============================================
const NOTIFICATION_CONFIG = {
    updateInterval: 10000, // Update setiap 10 detik
    apiEndpoint: '?page=admin&action=getAdminNotifications',
    debug: false // Set true untuk logging
};

// ============================================
// FUNGSI UPDATE BADGE
// ============================================
function updateAdminBadges() {
    fetch(NOTIFICATION_CONFIG.apiEndpoint)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (NOTIFICATION_CONFIG.debug) {
                console.log('📊 Notifications:', data);
            }
            
            // Update badge
            const badgeMapping = {
                'kapalBadge': data.kapal_pending || 0,
                'pesananBadge': data.pesanan_pending || 0,
                'requestHapusBadge': data.request_hapus || 0,
                'pembayaranBadge': data.pembayaran_pending || 0,
                'pencairanBadge': data.pencairan_pending || 0,
                'claimBadge': data.claim_pending || 0
            };
            
            let totalNotifications = 0;
            
            Object.keys(badgeMapping).forEach(id => {
                const badge = document.getElementById(id);
                const count = badgeMapping[id];
                
                if (badge) {
                    if (count > 0) {
                        badge.textContent = count > 99 ? '99+' : count;
                        badge.style.display = 'inline-block';
                        totalNotifications += count;
                    } else {
                        badge.style.display = 'none';
                    }
                }
            });
            
            // Update title jika ada notifikasi
            const title = document.querySelector('title');
            if (title) {
                const baseTitle = 'Admin Panel - Platform Kapal Samosir';
                if (totalNotifications > 0) {
                    title.textContent = `(${totalNotifications}) ${baseTitle}`;
                } else {
                    title.textContent = baseTitle;
                }
            }
        })
        .catch(error => {
            console.error('❌ Error updating badges:', error);
        });
}

// ============================================
// INISIALISASI
// ============================================
document.addEventListener('DOMContentLoaded', function() {
    // Update pertama
    setTimeout(updateAdminBadges, 1000);
    
    // Update berkala
    setInterval(updateAdminBadges, NOTIFICATION_CONFIG.updateInterval);
    
    // Update saat tab aktif
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            updateAdminBadges();
        }
    });
    
    console.log('✅ Sistem Notifikasi Aktif');
});

// Expose untuk debugging
window.updateAdminBadges = updateAdminBadges;
</script>