<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Flash Messages Partial
 * Developer: JOACHIM'S INNOTECH
 */

// Get flash messages from session
$flash_messages = $_SESSION['flash_messages'] ?? [];

// Clear flash messages after retrieving
$_SESSION['flash_messages'] = [];

// Define message types and their corresponding Bootstrap classes
$message_types = [
    'success' => 'alert-success',
    'info' => 'alert-info',
    'warning' => 'alert-warning',
    'danger' => 'alert-danger',
    'error' => 'alert-danger',
    'primary' => 'alert-primary',
    'secondary' => 'alert-secondary',
    'light' => 'alert-light',
    'dark' => 'alert-dark'
];

// Define icons for each type
$message_icons = [
    'success' => 'fa-check-circle',
    'info' => 'fa-info-circle',
    'warning' => 'fa-exclamation-triangle',
    'danger' => 'fa-times-circle',
    'error' => 'fa-times-circle',
    'primary' => 'fa-bell',
    'secondary' => 'fa-clock',
    'light' => 'fa-sun',
    'dark' => 'fa-moon'
];
?>

<!-- Flash Messages Container -->
<div class="flash-messages-container">
    <?php foreach ($flash_messages as $message): ?>
        <?php
        $type = $message['type'] ?? 'info';
        $text = $message['message'] ?? '';
        $title = $message['title'] ?? '';
        $dismissible = $message['dismissible'] ?? true;
        $icon = $message['icon'] ?? ($message_icons[$type] ?? 'fa-info-circle');
        $class = $message_types[$type] ?? 'alert-info';
        $message_id = 'flash-' . uniqid();
        
        // Handle HTML content
        $allow_html = $message['allow_html'] ?? false;
        ?>
        
        <div id="<?php echo $message_id; ?>" class="alert <?php echo $class; ?> <?php echo $dismissible ? 'alert-dismissible' : ''; ?> fade show" role="alert">
            <?php if (!empty($title)): ?>
                <h5 class="alert-heading">
                    <i class="fas <?php echo $icon; ?> mr-2"></i>
                    <?php echo $allow_html ? $title : escape_html($title); ?>
                </h5>
            <?php endif; ?>
            
            <div class="alert-content">
                <?php if (!empty($title) && empty($icon)): ?>
                    <i class="fas <?php echo $icon; ?> mr-2"></i>
                <?php endif; ?>
                
                <?php if ($allow_html): ?>
                    <?php echo $text; ?>
                <?php else: ?>
                    <?php echo nl2br(escape_html($text)); ?>
                <?php endif; ?>
            </div>
            
            <?php if ($dismissible): ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            <?php endif; ?>
            
            <!-- Auto-progress bar for auto-dismissing messages -->
            <?php if ($message['auto_dismiss'] ?? false): ?>
                <div class="alert-progress">
                    <div class="alert-progress-bar" style="animation-duration: <?php echo $message['duration'] ?? 5; ?>s"></div>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Auto-dismiss script -->
        <?php if ($message['auto_dismiss'] ?? false): ?>
        <script>
            setTimeout(function() {
                var alert = document.getElementById('<?php echo $message_id; ?>');
                if (alert) {
                    alert.classList.remove('show');
                    setTimeout(function() {
                        if (alert.parentNode) {
                            alert.parentNode.removeChild(alert);
                        }
                    }, 150);
                }
            }, <?php echo ($message['duration'] ?? 5) * 1000; ?>);
        </script>
        <?php endif; ?>
        
    <?php endforeach; ?>
</div>

<!-- Toast Container for toast-style notifications -->
<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1050;">
    <!-- Toasts will be added here via JavaScript -->
</div>

<!-- Flash Message Helper Functions -->
<script>
    /**
     * Show a flash message via AJAX
     */
    function showFlashMessage(type, message, title = '', options = {}) {
        const defaults = {
            dismissible: true,
            autoDismiss: false,
            duration: 5,
            icon: null,
            allowHtml: false
        };
        
        const settings = {...defaults, ...options};
        
        // Create alert element
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} ${settings.dismissible ? 'alert-dismissible' : ''} fade show`;
        alertDiv.setAttribute('role', 'alert');
        
        // Add title
        if (title) {
            const titleEl = document.createElement('h5');
            titleEl.className = 'alert-heading';
            if (settings.icon) {
                titleEl.innerHTML = `<i class="fas ${settings.icon} mr-2"></i>${title}`;
            } else {
                titleEl.textContent = title;
            }
            alertDiv.appendChild(titleEl);
        }
        
        // Add message
        const contentDiv = document.createElement('div');
        contentDiv.className = 'alert-content';
        if (settings.allowHtml) {
            contentDiv.innerHTML = message;
        } else {
            contentDiv.textContent = message;
        }
        alertDiv.appendChild(contentDiv);
        
        // Add dismiss button
        if (settings.dismissible) {
            const closeBtn = document.createElement('button');
            closeBtn.type = 'button';
            closeBtn.className = 'close';
            closeBtn.setAttribute('data-dismiss', 'alert');
            closeBtn.setAttribute('aria-label', 'Close');
            closeBtn.innerHTML = '<span aria-hidden="true">&times;</span>';
            alertDiv.appendChild(closeBtn);
        }
        
        // Add to container
        document.querySelector('.flash-messages-container').appendChild(alertDiv);
        
        // Auto-dismiss
        if (settings.autoDismiss) {
            setTimeout(function() {
                alertDiv.classList.remove('show');
                setTimeout(function() {
                    if (alertDiv.parentNode) {
                        alertDiv.parentNode.removeChild(alertDiv);
                    }
                }, 150);
            }, settings.duration * 1000);
        }
    }
    
    /**
     * Show a toast notification
     */
    function showToast(type, message, title = '', options = {}) {
        const defaults = {
            duration: 5,
            position: 'bottom-end',
            icon: true
        };
        
        const settings = {...defaults, ...options};
        
        // Use toastr if available
        if (typeof toastr !== 'undefined') {
            toastr[type](message, title, {
                timeOut: settings.duration * 1000,
                closeButton: true,
                progressBar: true,
                positionClass: `toast-${settings.position}`
            });
            return;
        }
        
        // Fallback to Bootstrap toast
        const toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) return;
        
        const toastId = 'toast-' + Date.now();
        const toastHtml = `
            <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-autohide="${settings.duration > 0}" data-delay="${settings.duration * 1000}">
                <div class="toast-header text-${type}">
                    ${settings.icon ? `<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'} mr-2"></i>` : ''}
                    <strong class="mr-auto">${title || (type.charAt(0).toUpperCase() + type.slice(1))}</strong>
                    <small>just now</small>
                    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        `;
        
        toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        
        const toastEl = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastEl, {
            autohide: settings.duration > 0,
            delay: settings.duration * 1000
        });
        
        toast.show();
        
        // Remove after hidden
        toastEl.addEventListener('hidden.bs.toast', function() {
            this.remove();
        });
    }
    
    /**
     * Show a success message
     */
    function showSuccess(message, title = 'Success', options = {}) {
        showFlashMessage('success', message, title, {...options, icon: 'fa-check-circle'});
    }
    
    /**
     * Show an error message
     */
    function showError(message, title = 'Error', options = {}) {
        showFlashMessage('danger', message, title, {...options, icon: 'fa-times-circle'});
    }
    
    /**
     * Show a warning message
     */
    function showWarning(message, title = 'Warning', options = {}) {
        showFlashMessage('warning', message, title, {...options, icon: 'fa-exclamation-triangle'});
    }
    
    /**
     * Show an info message
     */
    function showInfo(message, title = 'Information', options = {}) {
        showFlashMessage('info', message, title, {...options, icon: 'fa-info-circle'});
    }
    
    /**
     * Clear all flash messages
     */
    function clearFlashMessages() {
        document.querySelector('.flash-messages-container').innerHTML = '';
    }
</script>

<!-- Add CSS for flash messages -->
<style>
    .flash-messages-container {
        position: relative;
        z-index: 1050;
        margin-bottom: 1rem;
    }
    
    .flash-messages-container .alert {
        margin-bottom: 0.5rem;
        border-left-width: 4px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        animation: slideInDown 0.3s ease;
    }
    
    .flash-messages-container .alert:last-child {
        margin-bottom: 0;
    }
    
    .flash-messages-container .alert-success {
        border-left-color: #28a745;
    }
    
    .flash-messages-container .alert-info {
        border-left-color: #17a2b8;
    }
    
    .flash-messages-container .alert-warning {
        border-left-color: #ffc107;
    }
    
    .flash-messages-container .alert-danger {
        border-left-color: #dc3545;
    }
    
    .flash-messages-container .alert-primary {
        border-left-color: #007bff;
    }
    
    .flash-messages-container .alert-secondary {
        border-left-color: #6c757d;
    }
    
    .flash-messages-container .alert h5 {
        margin-bottom: 0.5rem;
        font-size: 1rem;
        font-weight: 600;
    }
    
    .flash-messages-container .alert .alert-content {
        display: flex;
        align-items: center;
    }
    
    .flash-messages-container .alert .alert-content i {
        font-size: 1.2rem;
        margin-right: 0.5rem;
    }
    
    /* Progress bar for auto-dismiss */
    .alert-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .alert-progress-bar {
        height: 100%;
        background: rgba(255,255,255,0.5);
        animation: progress linear forwards;
    }
    
    @keyframes progress {
        from { width: 0; }
        to { width: 100%; }
    }
    
    /* Toast container */
    .toast-container {
        position: fixed;
        bottom: 1rem;
        right: 1rem;
        z-index: 1060;
    }
    
    .toast {
        min-width: 250px;
    }
    
    .toast-header.text-success {
        color: #28a745 !important;
    }
    
    .toast-header.text-danger {
        color: #dc3545 !important;
    }
    
    .toast-header.text-warning {
        color: #ffc107 !important;
    }
    
    .toast-header.text-info {
        color: #17a2b8 !important;
    }
    
    /* Animations */
    @keyframes slideInDown {
        from {
            transform: translate3d(0, -100%, 0);
            visibility: visible;
            opacity: 0;
        }
        to {
            transform: translate3d(0, 0, 0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutUp {
        from {
            transform: translate3d(0, 0, 0);
            opacity: 1;
        }
        to {
            visibility: hidden;
            transform: translate3d(0, -100%, 0);
            opacity: 0;
        }
    }
    
    /* Mobile responsiveness */
    @media (max-width: 576px) {
        .flash-messages-container .alert {
            padding: 0.75rem 2rem 0.75rem 0.75rem;
            font-size: 0.9rem;
        }
        
        .flash-messages-container .alert h5 {
            font-size: 0.95rem;
        }
        
        .toast-container {
            left: 0.5rem;
            right: 0.5rem;
            bottom: 0.5rem;
        }
        
        .toast {
            min-width: auto;
            width: 100%;
        }
    }
    
    /* Dark mode support */
    @media (prefers-color-scheme: dark) {
        .flash-messages-container .alert {
            background-color: #343a40;
            color: #fff;
            border-color: #454d55;
        }
        
        .flash-messages-container .alert .close {
            color: #fff;
            text-shadow: 0 1px 0 #000;
        }
        
        .toast {
            background-color: #343a40;
            color: #fff;
        }
        
        .toast-header {
            background-color: #454d55;
            color: #fff;
            border-bottom-color: #5a6268;
        }
        
        .toast-header .close {
            color: #fff;
            text-shadow: 0 1px 0 #000;
        }
    }
</style>