<?php
/**
 * notifikasi.php - Halaman Notifikasi Supir
 */
$activeMenu = 'notifikasi';
$pageTitle = 'Notifikasi - Supir';
include __DIR__ . '/../layouts/header.php';

// Data dari controller
$notifikasi = $notifikasi ?? [];
$user = $user ?? null;
$unreadCount = $unreadCount ?? 0;
$user_id = $user_id ?? $_SESSION['user_id'] ?? 0;
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifikasi - Supir</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2b6cb0;
            --primary-light: #4299e1;
            --primary-dark: #1a4a7a;
            --primary-bg: #ebf4ff;
            --success: #22c55e;
            --success-bg: #d1fae5;
            --warning: #f59e0b;
            --warning-bg: #fef3c7;
            --danger: #ef4444;
            --danger-bg: #fee2e2;
            --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;
            --shadow: 0 4px 20px rgba(0,0,0,0.06);
            --shadow-lg: 0 10px 40px rgba(0,0,0,0.1);
            --radius: 16px;
            --radius-sm: 10px;
            --transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #f7fafc;
            color: var(--gray-800);
            line-height: 1.6;
        }

        .dashboard-wrapper {
            display: flex;
            gap: 24px;
            max-width: 1200px;
            margin: 1.5rem auto 0;
            padding: 0 20px;
            width: 100%;
            flex: 1;
            align-items: flex-start;
        }

        .main-content {
            flex: 1;
            min-width: 0;
            background: #ffffff;
            border-radius: var(--radius);
            padding: 1.8rem;
            box-shadow: var(--shadow);
            border: 1px solid var(--gray-200);
            animation: fadeInUp 0.5s ease;
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--gray-100);
        }

        .content-header-left h2 {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--gray-900);
            display: flex;
            align-items: center;
            gap: 0.6rem;
        }

        .content-header-left h2 i {
            color: var(--primary);
            background: var(--primary-bg);
            padding: 0.4rem;
            border-radius: var(--radius-sm);
        }

        .content-header-left p {
            color: var(--gray-500);
            font-size: 0.9rem;
            margin-top: 0.2rem;
        }

        .header-actions {
            display: flex;
            gap: 0.6rem;
            flex-wrap: wrap;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1.2rem;
            border: none;
            border-radius: var(--radius-sm);
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            font-family: inherit;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: #fff;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-dark), #0d2b4f);
            color: #fff;
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success), #16a34a);
            color: #fff;
        }

        .btn-success:hover {
            background: linear-gradient(135deg, #16a34a, #0d7a3a);
            color: #fff;
        }

        .btn-outline {
            background: transparent;
            color: var(--gray-600);
            border: 2px solid var(--gray-200);
        }

        .btn-outline:hover {
            background: var(--gray-50);
            border-color: var(--gray-400);
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #dc2626);
            color: #fff;
        }

        .btn-danger:hover {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
            color: #fff;
        }

        .btn-sm {
            padding: 0.25rem 0.8rem;
            font-size: 0.7rem;
        }

        .notification-list {
            display: grid;
            grid-template-columns: 1fr;
            gap: 0.8rem;
        }

        .notification-item {
            background: #fff;
            border-radius: var(--radius-sm);
            border: 1px solid var(--gray-200);
            padding: 1rem 1.2rem;
            transition: var(--transition);
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            position: relative;
        }

        .notification-item:hover {
            box-shadow: var(--shadow);
            border-color: var(--primary-light);
        }

        .notification-item.unread {
            background: var(--primary-bg);
            border-left: 4px solid var(--primary);
        }

        .notification-item .notif-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            flex-shrink: 0;
        }

        .notification-item .notif-icon.success {
            background: var(--success-bg);
            color: #065f46;
        }

        .notification-item .notif-icon.warning {
            background: var(--warning-bg);
            color: #92400e;
        }

        .notification-item .notif-icon.danger {
            background: var(--danger-bg);
            color: #991b1b;
        }

        .notification-item .notif-icon.info {
            background: var(--primary-bg);
            color: var(--primary);
        }

        .notification-item .notif-content {
            flex: 1;
            min-width: 0;
        }

        .notification-item .notif-content .notif-title {
            font-weight: 700;
            color: var(--gray-900);
            font-size: 0.95rem;
            margin-bottom: 0.2rem;
        }

        .notification-item .notif-content .notif-message {
            color: var(--gray-600);
            font-size: 0.85rem;
            line-height: 1.5;
        }

        .notification-item .notif-content .notif-time {
            font-size: 0.7rem;
            color: var(--gray-400);
            margin-top: 0.3rem;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }

        .notification-item .notif-actions {
            display: flex;
            gap: 0.3rem;
            flex-shrink: 0;
            align-items: center;
        }

        .notification-item .notif-actions .btn {
            font-size: 0.65rem;
            padding: 0.2rem 0.6rem;
        }

        .notification-item .notif-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--danger);
            animation: pulse 2s infinite;
        }

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

        .notification-item .notif-link {
            color: var(--primary);
            font-weight: 600;
            text-decoration: none;
            transition: var(--transition);
        }

        .notification-item .notif-link:hover {
            color: var(--primary-dark);
            text-decoration: underline;
        }

        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
            background: var(--gray-50);
            border-radius: var(--radius);
            border: 2px dashed var(--gray-200);
        }

        .empty-state .empty-icon {
            font-size: 4rem;
            display: block;
            margin-bottom: 0.5rem;
        }

        .empty-state h3 {
            font-size: 1.3rem;
            font-weight: 700;
            color: var(--gray-800);
            margin-bottom: 0.3rem;
        }

        .empty-state p {
            color: var(--gray-500);
            font-size: 0.95rem;
            max-width: 400px;
            margin: 0 auto;
        }

        #toastContainer {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 99999;
            max-width: 400px;
        }

        .toast-item {
            background: white;
            padding: 12px 16px;
            margin-bottom: 10px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            animation: slideInRight 0.4s ease;
            font-family: 'Inter', sans-serif;
            font-size: 14px;
            color: #1a202c;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid #3b82f6;
        }

        .toast-item.success { border-left-color: #22c55e; }
        .toast-item.error { border-left-color: #ef4444; }
        .toast-item.warning { border-left-color: #f59e0b; }

        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOutRight {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }

        @media (max-width: 768px) {
            .dashboard-wrapper {
                flex-direction: column;
                padding: 0 12px;
                margin-top: 1rem;
            }

            .main-content {
                padding: 1rem;
            }

            .content-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
                justify-content: center;
            }

            .notification-item {
                flex-direction: column;
                align-items: flex-start;
            }

            .notification-item .notif-actions {
                width: 100%;
                justify-content: flex-start;
                margin-top: 0.3rem;
            }

            .notification-item .notif-actions .btn {
                flex: 1;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .main-content {
                padding: 0.8rem;
            }

            .notification-item {
                padding: 0.8rem;
            }

            .notification-item .notif-icon {
                width: 32px;
                height: 32px;
                font-size: 0.8rem;
            }

            .notification-item .notif-content .notif-title {
                font-size: 0.85rem;
            }

            .notification-item .notif-content .notif-message {
                font-size: 0.75rem;
            }
        }
    </style>
</head>
<body>

<div class="dashboard-wrapper">
    <?php include __DIR__ . '/../layouts/sidebar_supir.php'; ?>

    <main class="main-content">
        <div class="content-header">
            <div class="content-header-left">
                <h2>
                    <i class="fas fa-bell" style="color:var(--primary);"></i>
                    Notifikasi
                    <?php if($unreadCount > 0): ?>
                        <span style="background:var(--danger);color:#fff;font-size:0.7rem;padding:0.1rem 0.6rem;border-radius:20px;margin-left:0.3rem;">
                            <?= $unreadCount ?>
                        </span>
                    <?php endif; ?>
                </h2>
                <p>
                    <i class="fas fa-info-circle"></i> 
                    Semua notifikasi untuk Anda. Notifikasi baru akan ditandai dengan badge.
                </p>
            </div>
            <div class="header-actions">
                <?php if(!empty($notifikasi)): ?>
                    <button onclick="markAllAsRead()" class="btn btn-primary btn-sm">
                        <i class="fas fa-check-double"></i> Tandai Semua Dibaca
                    </button>
                <?php endif; ?>
                <button onclick="refreshData()" class="btn btn-outline btn-sm">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
        </div>

        <?php if(empty($notifikasi)): ?>
            <div class="empty-state">
                <span class="empty-icon">🔔</span>
                <h3>Tidak Ada Notifikasi</h3>
                <p>Semua notifikasi akan muncul di sini</p>
            </div>
        <?php else: ?>
            <div class="notification-list" id="notificationList">
                <?php foreach($notifikasi as $notif): 
                    $isRead = ($notif['is_read'] ?? 0) == 1;
                    $iconType = 'info';
                    $title = $notif['title'] ?? 'Notifikasi';
                    $message = $notif['message'] ?? '';
                    
                    if(stripos($title, 'LUNAS') !== false || stripos($title, 'Pembayaran') !== false) {
                        $iconType = 'success';
                    } elseif(stripos($title, 'Dibatalkan') !== false || stripos($title, 'Batal') !== false) {
                        $iconType = 'danger';
                    } elseif(stripos($title, 'Menunggu') !== false || stripos($title, 'Pending') !== false) {
                        $iconType = 'warning';
                    }
                    
                    $bookingId = $notif['booking_id'] ?? $notif['pesanan_id'] ?? 0;
                ?>
                    <div class="notification-item <?= !$isRead ? 'unread' : '' ?>" 
                         data-id="<?= $notif['id'] ?>"
                         data-read="<?= $isRead ? '1' : '0' ?>">
                        
                        <?php if(!$isRead): ?>
                            <div class="notif-badge"></div>
                        <?php endif; ?>
                        
                        <div class="notif-icon <?= $iconType ?>">
                            <i class="fas <?= $iconType == 'success' ? 'fa-check-circle' : ($iconType == 'danger' ? 'fa-times-circle' : ($iconType == 'warning' ? 'fa-exclamation-triangle' : 'fa-bell')) ?>"></i>
                        </div>
                        
                        <div class="notif-content">
                            <div class="notif-title">
                                <?= htmlspecialchars($title) ?>
                                <?php if(!$isRead): ?>
                                    <span style="background:var(--danger);color:#fff;font-size:0.5rem;padding:0.1rem 0.4rem;border-radius:10px;margin-left:0.3rem;">Baru</span>
                                <?php endif; ?>
                            </div>
                            <div class="notif-message">
                                <?= htmlspecialchars($message) ?>
                                <?php if($bookingId > 0): ?>
                                    <br>
                                    <a href="?page=supir&action=detailPesanan&id=<?= $bookingId ?>" class="notif-link">
                                        <i class="fas fa-arrow-right"></i> Lihat Detail Pesanan
                                    </a>
                                <?php endif; ?>
                            </div>
                            <div class="notif-time">
                                <i class="fas fa-clock"></i>
                                <?= isset($notif['created_at']) ? date('d/m/Y H:i', strtotime($notif['created_at'])) : 'Baru saja' ?>
                            </div>
                        </div>
                        
                        <div class="notif-actions">
                            <?php if(!$isRead): ?>
                                <button onclick="markAsRead(<?= $notif['id'] ?>)" class="btn btn-success btn-sm">
                                    <i class="fas fa-check"></i> Tandai Dibaca
                                </button>
                            <?php else: ?>
                                <button onclick="deleteNotification(<?= $notif['id'] ?>)" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </main>
</div>

<!-- Toast Container -->
<div id="toastContainer"></div>

<script>
    // ==============================================
    // TOAST NOTIFICATION
    // ==============================================
    function showToast(message, type = 'info') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast-item ${type}`;
        toast.innerHTML = `
            <span style="flex:1;">${message}</span>
            <button onclick="this.parentElement.remove()" 
                    style="background:none;border:none;font-size:18px;cursor:pointer;color:#a0aec0;">
                ×
            </button>
        `;
        container.appendChild(toast);
        setTimeout(() => {
            if (toast.parentElement) {
                toast.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => toast.remove(), 300);
            }
        }, 4000);
    }

    // ==============================================
    // MARK AS READ - SATU NOTIFIKASI
    // ==============================================
    function markAsRead(id) {
        if (!id) {
            showToast('ID notifikasi tidak valid', 'error');
            return;
        }

        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;

        fetch('?page=ajax&action=markAsRead', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('✅ Notifikasi ditandai sebagai dibaca', 'success');
                
                // Update UI
                const item = document.querySelector(`.notification-item[data-id="${id}"]`);
                if (item) {
                    item.classList.remove('unread');
                    item.dataset.read = '1';
                    
                    const badge = item.querySelector('.notif-badge');
                    if (badge) badge.remove();
                    
                    const actions = item.querySelector('.notif-actions');
                    const oldBtn = actions.querySelector('.btn-success');
                    if (oldBtn) {
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'btn btn-danger btn-sm';
                        deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Hapus';
                        deleteBtn.onclick = function() { deleteNotification(id); };
                        oldBtn.replaceWith(deleteBtn);
                    }
                }
                
                // Update unread count
                updateUnreadCount();
            } else {
                showToast('❌ ' + (data.message || 'Gagal menandai sebagai dibaca'), 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ Error: ' + error.message, 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    }

    // ==============================================
    // MARK ALL AS READ
    // ==============================================
    function markAllAsRead() {
        if (!confirm('Tandai semua notifikasi sebagai dibaca?')) return;

        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses...';
        btn.disabled = true;

        fetch('?page=ajax&action=markAllAsRead', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('✅ Semua notifikasi ditandai sebagai dibaca', 'success');
                
                document.querySelectorAll('.notification-item.unread').forEach(item => {
                    item.classList.remove('unread');
                    item.dataset.read = '1';
                    
                    const badge = item.querySelector('.notif-badge');
                    if (badge) badge.remove();
                    
                    const actions = item.querySelector('.notif-actions');
                    const oldBtn = actions.querySelector('.btn-success');
                    if (oldBtn) {
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'btn btn-danger btn-sm';
                        deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Hapus';
                        const id = item.dataset.id;
                        deleteBtn.onclick = function() { deleteNotification(id); };
                        oldBtn.replaceWith(deleteBtn);
                    }
                });
                
                updateUnreadCount();
                
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            } else {
                showToast('❌ ' + (data.message || 'Gagal menandai semua'), 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ Error: ' + error.message, 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    }

    // ==============================================
    // DELETE NOTIFICATION
    // ==============================================
    function deleteNotification(id) {
        if (!confirm('Hapus notifikasi ini?')) return;

        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;

        fetch('?page=ajax&action=deleteNotification', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('🗑️ Notifikasi dihapus', 'success');
                
                const item = document.querySelector(`.notification-item[data-id="${id}"]`);
                if (item) {
                    item.style.transition = 'all 0.3s ease';
                    item.style.opacity = '0';
                    item.style.transform = 'translateX(100%)';
                    setTimeout(() => {
                        item.remove();
                        const remaining = document.querySelectorAll('.notification-item');
                        if (remaining.length === 0) {
                            location.reload();
                        }
                    }, 300);
                }
                
                updateUnreadCount();
            } else {
                showToast('❌ ' + (data.message || 'Gagal menghapus notifikasi'), 'error');
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('❌ Error: ' + error.message, 'error');
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        });
    }

    // ==============================================
    // UPDATE UNREAD COUNT
    // ==============================================
    function updateUnreadCount() {
        fetch('?page=ajax&action=getUnreadCount', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const count = data.count || 0;
                
                const headerBadge = document.querySelector('.content-header-left h2 span');
                if (headerBadge) {
                    if (count > 0) {
                        headerBadge.textContent = count;
                        headerBadge.style.display = 'inline-block';
                    } else {
                        headerBadge.style.display = 'none';
                    }
                }
                
                const sidebarBadge = document.querySelector('.sidebar-nav .notification-badge');
                if (sidebarBadge) {
                    if (count > 0) {
                        sidebarBadge.textContent = count > 99 ? '99+' : count;
                        sidebarBadge.style.display = 'inline-block';
                    } else {
                        sidebarBadge.style.display = 'none';
                    }
                }
            }
        })
        .catch(error => console.error('Error updating unread count:', error));
    }

    // ==============================================
    // REFRESH DATA
    // ==============================================
    function refreshData() {
        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
        location.reload();
    }

    console.log('✅ Notifikasi Supir loaded');
    console.log('📊 Total notifikasi: <?= count($notifikasi) ?>');
</script>

<?php include __DIR__ . '/../layouts/footer.php'; ?>
</body>
</html>