</div>

<!-- Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- SweetAlert2 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Main JavaScript -->
<script src="<?= base_url(); ?>assets/js/main.js"></script>

<!-- Global SweetAlert2 Helper Functions -->
<script>
// Global SweetAlert helper functions available on all pages
window.showSuccess = function(title, text, timer = 3000) {
    return Swal.fire({
        icon: 'success',
        title: title,
        text: text,
        timer: timer,
        timerProgressBar: true,
        showConfirmButton: false,
        toast: false
    });
};

window.showError = function(title, text) {
    return Swal.fire({
        icon: 'error',
        title: title,
        text: text,
        confirmButtonColor: '#dc3545'
    });
};

window.showWarning = function(title, text) {
    return Swal.fire({
        icon: 'warning',
        title: title,
        text: text,
        confirmButtonColor: '#ffc107'
    });
};

window.showInfo = function(title, text) {
    return Swal.fire({
        icon: 'info',
        title: title,
        text: text,
        confirmButtonColor: '#007bff'
    });
};

window.showConfirm = function(title, text, confirmText = 'Yes', cancelText = 'No') {
    return Swal.fire({
        title: title,
        text: text,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: confirmText,
        cancelButtonText: cancelText
    });
};

window.showLoading = function(title = 'Loading...', text = 'Please wait...') {
    return Swal.fire({
        title: title,
        text: text,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
};

window.showToast = function(message, type = 'success', position = 'top-end') {
    return Swal.fire({
        toast: true,
        position: position,
        icon: type,
        title: message,
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true
    });
};

window.showCustomLoader = function(title, html) {
    return Swal.fire({
        title: title,
        html: html,
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false
    });
};

// Global AJAX error handler
window.handleAjaxError = function(xhr, status, error) {
    console.error('AJAX Error:', error);
    
    let errorMessage = 'An unexpected error occurred. Please try again.';
    
    if (xhr.status === 0) {
        errorMessage = 'Network connection error. Please check your internet connection.';
    } else if (xhr.status === 404) {
        errorMessage = 'The requested resource was not found.';
    } else if (xhr.status === 500) {
        errorMessage = 'Internal server error. Please try again later.';
    } else if (xhr.status === 403) {
        errorMessage = 'Access denied. Please log in again.';
    }
    
    showError('Request Failed', errorMessage);
};

// Global form validation helper
window.validateForm = function(formId, rules = {}) {
    const form = document.getElementById(formId);
    if (!form) return false;
    
    let isValid = true;
    const errors = [];
    
    // Check required fields
    const requiredFields = form.querySelectorAll('[required]');
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('is-invalid');
            errors.push(`${field.name || field.id} is required`);
        } else {
            field.classList.remove('is-invalid');
        }
    });
    
    // Custom validation rules
    for (const fieldName in rules) {
        const field = form.querySelector(`[name="${fieldName}"]`);
        if (field && rules[fieldName]) {
            const rule = rules[fieldName];
            const value = field.value.trim();
            
            if (rule.pattern && !rule.pattern.test(value)) {
                isValid = false;
                field.classList.add('is-invalid');
                errors.push(rule.message || `${fieldName} is invalid`);
            }
        }
    }
    
    if (!isValid && errors.length > 0) {
        showWarning('Validation Error', errors[0]);
    }
    
    return isValid;
};

// Global copy to clipboard function
window.copyToClipboard = function(text, successMessage = 'Copied to clipboard!') {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(function() {
            showToast(successMessage, 'success');
        }).catch(function(err) {
            console.error('Could not copy text: ', err);
            showToast('Failed to copy', 'error');
        });
    } else {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast(successMessage, 'success');
        } catch (err) {
            showToast('Failed to copy', 'error');
        }
        document.body.removeChild(textArea);
    }
};
</script>

<!-- Toggle Sidebar (for mobile) -->
<script>
    function toggleSidebar() {
        const sidebar = document.getElementById("sidebar");
        sidebar.classList.toggle("closed")
    }
</script>

<!-- Global Notification System CSS & JS -->
<style>
/* Notification Bell Styling */
.notification-bell {
    position: relative;
    display: inline-block;
}

.notification-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #dc3545;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    font-size: 10px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    animation: notificationPulse 2s infinite;
}

.notification-dot {
    position: absolute;
    top: -2px;
    right: -2px;
    background: #dc3545;
    border-radius: 50%;
    width: 12px;
    height: 12px;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    animation: notificationPulse 2s infinite;
}

.notification-bell.has-unread #bellIcon {
    filter: brightness(0) saturate(100%) invert(16%) sepia(99%) saturate(7404%) hue-rotate(359deg) brightness(95%) contrast(118%);
}

@keyframes notificationPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Notification bell shake animation */
@keyframes bellShake {
    0%, 100% { transform: rotate(0deg); }
    10%, 30%, 50%, 70%, 90% { transform: rotate(-10deg); }
    20%, 40%, 60%, 80% { transform: rotate(10deg); }
}

.notification-bell.shake {
    animation: bellShake 0.5s ease-in-out;
}

/* Mobile responsive */
@media (max-width: 768px) {
    .notification-badge {
        width: 18px;
        height: 18px;
        font-size: 9px;
    }
    
    .notification-dot {
        width: 10px;
        height: 10px;
    }
}
</style>

<script>
// Global Notification System
let notificationPollingInterval;
let lastNotificationCount = 0;

// Initialize notification checking when page loads
document.addEventListener('DOMContentLoaded', function() {
    // Check notifications immediately
    checkNotificationStatus();
    
    // Start polling for notifications every 10 seconds
    startNotificationPolling();
    
    // Check when page becomes visible (user switches back to tab)
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            checkNotificationStatus();
        }
    });
});

// Start polling for notifications
function startNotificationPolling() {
    if (notificationPollingInterval) {
        clearInterval(notificationPollingInterval);
    }
    
    notificationPollingInterval = setInterval(() => {
        if (!document.hidden) {
            checkNotificationStatus();
        }
    }, 10000); // Check every 10 seconds
}

// Check notification status
function checkNotificationStatus() {
    fetch('<?php echo base_url("dashboard/get_notification_status"); ?>')
    .then(response => response.json())
    .then(data => {
        updateNotificationIndicator(data.hasUnread, data.unreadCount);
        
        // Show animation if new notifications arrived
        if (data.unreadCount > lastNotificationCount && lastNotificationCount > 0) {
            animateNotificationBell();
        }
        
        lastNotificationCount = data.unreadCount;
    })
    .catch(error => {
        console.error('Error checking notifications:', error);
    });
}

// Update notification indicator in topbar
function updateNotificationIndicator(hasUnread, unreadCount) {
    const bellElement = document.getElementById('notificationBell');
    const badgeElement = document.getElementById('notificationBadge');
    const dotElement = document.getElementById('notificationDot');
    const countElement = document.getElementById('notificationCount');
    
    if (!bellElement) return; // Element not found on this page
    
    if (hasUnread && unreadCount > 0) {
        // Show red indicator
        bellElement.classList.add('has-unread');
        
        if (unreadCount > 9) {
            // Show badge with count for 10+ notifications
            badgeElement.style.display = 'flex';
            dotElement.style.display = 'none';
            countElement.textContent = '9+';
        } else if (unreadCount > 1) {
            // Show badge with count for 2-9 notifications
            badgeElement.style.display = 'flex';
            dotElement.style.display = 'none';
            countElement.textContent = unreadCount;
        } else {
            // Show dot for 1 notification
            badgeElement.style.display = 'none';
            dotElement.style.display = 'block';
        }
    } else {
        // No unread notifications
        bellElement.classList.remove('has-unread');
        badgeElement.style.display = 'none';
        dotElement.style.display = 'none';
    }
}

// Animate notification bell when new notifications arrive
function animateNotificationBell() {
    const bellElement = document.getElementById('notificationBell');
    if (bellElement) {
        bellElement.classList.add('shake');
        setTimeout(() => {
            bellElement.classList.remove('shake');
        }, 500);
        
        // Show toast notification if available
        if (typeof showToast === 'function') {
            showToast('You have new notifications!', 'info');
        }
    }
}

// Force check notifications (can be called from other pages)
window.forceCheckNotifications = function() {
    checkNotificationStatus();
};

// Clean up on page unload
window.addEventListener('beforeunload', function() {
    if (notificationPollingInterval) {
        clearInterval(notificationPollingInterval);
    }
});
</script>

</body>