<?php
/**
 * sidebar_wisatawan.php - Sidebar untuk role Wisatawan
 * DIPERBAIKI - Ambil saldo langsung dari database dengan koneksi mandiri
 */

// ==============================================
// DEFAULT VALUES
// ==============================================
$activeMenu = $activeMenu ?? 'dashboard';
$unreadCount = $unreadCount ?? 0;
$userName = $_SESSION['nama'] ?? 'Pengguna';
$fotoFile = $_SESSION['foto_profil'] ?? null;
$user_id = $_SESSION['user_id'] ?? 0;

// ==============================================
// 🔥 AMBIL SALDO LANGSUNG DARI DATABASE
// ==============================================
$saldo = 0;

if ($user_id > 0) {
    try {
        // Cek apakah koneksi database sudah ada
        if (!isset($pdo) || !($pdo instanceof PDO)) {
            // Buat koneksi baru
            $host = 'localhost';
            $dbname = 'platform_kapal_samosir';
            $username = 'root';
            $password = '';
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        
        $stmt = $pdo->prepare("SELECT saldo FROM saldo_wisatawan WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $saldo = $result ? (int) $result['saldo'] : 0;
        
        // Simpan ke session
        $_SESSION['saldo'] = $saldo;
        
    } catch (Exception $e) {
        // Jika gagal, ambil dari session
        $saldo = $_SESSION['saldo'] ?? 0;
        error_log("Error getting saldo in sidebar: " . $e->getMessage());
    }
}

// ==============================================
// LOGIKA PATH FOTO
// ==============================================
$fotoUrl = '';
$fotoExists = false;

if (!empty($fotoFile)) {
    $basePath = $_SERVER['DOCUMENT_ROOT'] . '/reservasi-kapal-wisata/';
    
    $pathsToCheck = [
        $basePath . 'uploads/profil/' . $fotoFile,
        $_SERVER['DOCUMENT_ROOT'] . '/uploads/profil/' . $fotoFile,
        __DIR__ . '/../uploads/profil/' . $fotoFile,
    ];
    
    foreach ($pathsToCheck as $path) {
        if (file_exists($path)) {
            $fotoExists = true;
            $fotoUrl = '/reservasi-kapal-wisata/uploads/profil/' . $fotoFile;
            break;
        }
    }
}

$inisial = strtoupper(substr($userName, 0, 2));

// ==============================================
// TENTUKAN ACTIVE MENU
// ==============================================
$isDashboard = ($activeMenu == 'dashboard');
$isBooking = ($activeMenu == 'booking');
$isRiwayat = ($activeMenu == 'riwayat' || $activeMenu == 'riwayatPesanan' || $activeMenu == 'riwayat_pesanan');
$isNotifikasi = ($activeMenu == 'notifications' || $activeMenu == 'notifikasi');
$isSaldo = ($activeMenu == 'saldo');
$isProfil = ($activeMenu == 'profil' || $activeMenu == 'profile');
?>

<aside class="sidebar">
    <!-- ========================================== -->
    <!-- HEADER PROFILE -->
    <!-- ========================================== -->
    <div class="sidebar-header">
        <div class="user-info">
            <div class="user-avatar">
                <?php if($fotoExists && !empty($fotoUrl)): ?>
                    <img src="<?= $fotoUrl ?>" 
                         alt="Foto Profil" 
                         onerror="this.style.display='none'; this.parentElement.textContent='<?= $inisial ?>';">
                <?php else: ?>
                    <?= $inisial ?>
                <?php endif; ?>
            </div>
            <div class="user-detail">
                <div class="user-name"><?= htmlspecialchars($userName) ?></div>
                <div class="user-role">Wisatawan</div>
            </div>
        </div>
    </div>

    <!-- ========================================== -->
    <!-- 🔥 SALDO CARD -->
    <!-- ========================================== -->
    <div class="sidebar-saldo">
        <div class="saldo-icon">
            <i class="fas fa-wallet"></i>
        </div>
        <div class="saldo-info">
            <span class="saldo-label">Saldo Saya</span>
            <span class="saldo-value" id="sidebarSaldo">Rp <?= number_format($saldo, 0, ',', '.') ?></span>
        </div>
        <a href="?page=wisatawan&action=saldo" class="saldo-link" title="Lihat Saldo">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>

    <!-- ========================================== -->
    <!-- NAVIGASI MENU -->
    <!-- ========================================== -->
    <nav class="sidebar-nav">
        <!-- Dashboard -->
        <a href="?page=wisatawan&action=dashboard" class="<?= $isDashboard ? 'active' : '' ?>">
            <span class="icon">📊</span> Dashboard
        </a>
        
        <!-- Booking Kapal -->
        <a href="?page=wisatawan&action=booking" class="<?= $isBooking ? 'active' : '' ?>">
            <span class="icon">🛥️</span> Booking Kapal
        </a>
        
        <!-- Riwayat Pesanan -->
        <a href="?page=wisatawan&action=riwayat" class="<?= $isRiwayat ? 'active' : '' ?>">
            <span class="icon">📋</span> Riwayat Pesanan
        </a>
        
        <!-- Notifikasi -->
        <a href="?page=wisatawan&action=notifications" class="<?= $isNotifikasi ? 'active' : '' ?>">
            <span class="icon">🔔</span> Notifikasi
            <?php if($unreadCount > 0): ?>
                <span class="badge"><?= $unreadCount ?></span>
            <?php endif; ?>
        </a>
        
        <!-- Saldo Saya -->
        <a href="?page=wisatawan&action=saldo" class="<?= $isSaldo ? 'active' : '' ?>">
            <span class="icon">💰</span> Saldo Saya
        </a>
        
        <!-- Profil Saya -->
        <a href="?page=wisatawan&action=profil" class="<?= $isProfil ? 'active' : '' ?>">
            <span class="icon">👤</span> Profil Saya
        </a>
    </nav>
    
    <!-- ========================================== -->
    <!-- FOOTER - LOGOUT -->
    <!-- ========================================== -->
    <div class="sidebar-footer">
        <a href="?page=logout" onclick="return confirm('Yakin ingin logout?')">
            <span class="icon">🚪</span> Logout
        </a>
    </div>
</aside>

<style>
    :root {
        --primary: #2b6cb0;
        --primary-light: #4299e1;
        --primary-dark: #1a4a7a;
        --gray-50: #f7fafc;
        --gray-100: #edf2f7;
        --gray-200: #e2e8f0;
        --gray-400: #a0aec0;
        --gray-600: #4a5568;
        --gray-900: #1a202c;
        --success: #22c55e;
        --danger: #ef4444;
        --transition: all 0.3s ease;
    }
    
    .sidebar {
        width: 260px;
        flex-shrink: 0;
        background: #fff;
        border-radius: 14px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.06);
        padding: 1.5rem 0;
        position: sticky;
        top: 80px;
        border: 1px solid rgba(0,0,0,0.04);
        height: fit-content;
        min-height: 400px;
        display: flex;
        flex-direction: column;
    }
    
    /* ==========================================
       HEADER PROFILE
       ========================================== */
    .sidebar-header {
        padding: 0 1.2rem 1.2rem;
        border-bottom: 1px solid var(--gray-100);
    }
    
    .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, var(--primary), var(--primary-light));
        color: #fff;
        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: var(--gray-900);
        font-size: 0.95rem;
    }
    
    .sidebar-header .user-role {
        font-size: 0.75rem;
        color: var(--gray-400);
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }
    
    /* ==========================================
       SALDO CARD
       ========================================== */
    .sidebar-saldo {
        display: flex;
        align-items: center;
        gap: 0.8rem;
        padding: 0.8rem 1rem;
        margin: 0.8rem 1rem;
        background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        transition: var(--transition);
        text-decoration: none;
        box-shadow: 0 4px 15px rgba(43, 108, 176, 0.2);
    }
    
    .sidebar-saldo:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(43, 108, 176, 0.35);
    }
    
    .sidebar-saldo .saldo-icon {
        font-size: 1.4rem;
        color: rgba(255, 255, 255, 0.7);
        flex-shrink: 0;
        width: 36px;
        text-align: center;
    }
    
    .sidebar-saldo .saldo-info {
        flex: 1;
        min-width: 0;
    }
    
    .sidebar-saldo .saldo-label {
        display: block;
        font-size: 0.6rem;
        color: rgba(255, 255, 255, 0.6);
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .sidebar-saldo .saldo-value {
        display: block;
        font-weight: 700;
        font-size: 1.1rem;
        color: #fff;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .sidebar-saldo .saldo-link {
        color: rgba(255, 255, 255, 0.5);
        font-size: 0.8rem;
        transition: var(--transition);
        text-decoration: none;
        padding: 4px 8px;
        border-radius: 6px;
        flex-shrink: 0;
    }
    
    .sidebar-saldo .saldo-link:hover {
        color: #fff;
        background: rgba(255, 255, 255, 0.15);
        transform: translateX(2px);
    }
    
    /* ==========================================
       NAVIGASI
       ========================================== */
    .sidebar-nav { 
        padding: 0.5rem 0; 
        display: flex;
        flex-direction: column;
        gap: 0.1rem;
        flex: 1;
    }
    
    .sidebar-nav a {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 0.6rem 1.2rem;
        color: var(--gray-600);
        font-weight: 500;
        font-size: 0.9rem;
        transition: var(--transition);
        border-left: 3px solid transparent;
        text-decoration: none;
        position: relative;
        margin: 0 0.3rem;
        border-radius: 8px;
    }
    
    .sidebar-nav a:hover {
        background: var(--gray-50);
        color: var(--gray-900);
        text-decoration: none;
    }
    
    .sidebar-nav a.active {
        background: #ebf8ff;
        color: var(--primary);
        border-left-color: var(--primary);
        font-weight: 600;
    }
    
    .sidebar-nav a .icon {
        font-size: 1.2rem;
        width: 28px;
        text-align: center;
        flex-shrink: 0;
    }
    
    .sidebar-nav a .badge {
        background: var(--danger);
        color: #fff;
        font-size: 0.65rem;
        font-weight: 700;
        padding: 0.1rem 0.5rem;
        border-radius: 12px;
        margin-left: auto;
        min-width: 20px;
        text-align: center;
    }
    
    /* ==========================================
       FOOTER - LOGOUT
       ========================================== */
    .sidebar-footer {
        padding: 0.8rem 1.2rem 0;
        border-top: 1px solid var(--gray-100);
        margin-top: 0.5rem;
    }
    
    .sidebar-footer a {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        color: var(--danger);
        font-weight: 500;
        font-size: 0.85rem;
        padding: 0.4rem 0.6rem;
        transition: var(--transition);
        text-decoration: none;
        border-radius: 8px;
        margin: 0 0.3rem;
    }
    
    .sidebar-footer a:hover {
        background: #fee2e2;
        color: #dc2626;
        text-decoration: none;
    }
    
    .sidebar-footer a .icon {
        font-size: 1.1rem;
        width: 28px;
        text-align: center;
        flex-shrink: 0;
    }
    
    /* ==========================================
       RESPONSIVE
       ========================================== */
    @media (max-width: 768px) {
        .sidebar {
            width: 100%;
            position: static;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.3rem;
            border: none;
            box-shadow: none;
            background: transparent;
            padding: 0;
            min-height: auto;
            border-radius: 0;
        }
        
        .sidebar-header { 
            display: none; 
        }
        
        .sidebar-saldo {
            grid-column: 1 / -1;
            margin: 0 0 0.5rem 0;
            padding: 0.8rem 1rem;
            border-radius: 12px;
        }
        
        .sidebar-nav { 
            display: contents; 
        }
        
        .sidebar-nav a {
            background: #fff;
            border-radius: 10px;
            padding: 0.6rem 0.8rem;
            border-left: none;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            font-size: 0.8rem;
            justify-content: center;
            text-align: center;
            border: 1px solid var(--gray-200);
            margin: 0;
        }
        
        .sidebar-nav a.active {
            border-left: none;
            border-bottom: 3px solid var(--primary);
            background: #fff;
        }
        
        .sidebar-nav a .icon { 
            width: auto; 
            font-size: 1rem; 
        }
        
        .sidebar-nav a .badge { 
            margin-left: 4px; 
        }
        
        .sidebar-footer { 
            display: none; 
        }
    }
    
    @media (max-width: 480px) {
        .sidebar {
            grid-template-columns: 1fr 1fr;
            gap: 0.2rem;
        }
        
        .sidebar-nav a {
            font-size: 0.7rem;
            padding: 0.5rem 0.4rem;
        }
        
        .sidebar-nav a .icon {
            font-size: 0.85rem;
        }
        
        .sidebar-saldo .saldo-value {
            font-size: 0.95rem;
        }
    }
</style>

<!-- ========================================== -->
<!-- 🔥 SCRIPT AUTO-REFRESH SALDO -->
<!-- ========================================== -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Ambil elemen saldo
    const saldoElement = document.querySelector('.saldo-value');
    
    if (!saldoElement) return;
    
    // Fungsi update saldo via AJAX
    function updateSaldo() {
        fetch('?page=ajax&action=getSaldo')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.formatted) {
                    saldoElement.textContent = data.formatted;
                }
            })
            .catch(error => {
                // Silent fail
            });
    }
    
    // Update setiap 30 detik
    setInterval(updateSaldo, 30000);
    
    // Update saat halaman menjadi visible kembali
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            updateSaldo();
        }
    });
});
</script>