<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Footer Partial - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Get execution time if available
$execution_time = defined('SCRIPT_START') ? round(microtime(true) - SCRIPT_START, 4) : 0;

// Safely get constants with fallbacks
$app_version = defined('APP_VERSION') ? APP_VERSION : '1.0';
$app_name = defined('APP_NAME') ? APP_NAME : 'Ruhondo Resort';
$app_company = defined('APP_COMPANY') ? APP_COMPANY : 'JOACHIM\'S INNOTECH';
$db_name = defined('DB_NAME') ? DB_NAME : 'Not connected';
$base_url = defined('BASE_URL') ? BASE_URL : '';
$csrf_token_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
$currency_symbol = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF';
$date_format = defined('DATE_FORMAT') ? DATE_FORMAT : 'Y-m-d';
$datetime_format = defined('DATETIME_FORMAT') ? DATETIME_FORMAT : 'Y-m-d H:i:s';
?>

                </div> <!-- /.main-content -->
            </div> <!-- /.container-fluid -->
        </section> <!-- /.content -->
    </div> <!-- /.content-wrapper -->

    <!-- Footer -->
    <footer class="main-footer">
        <div class="float-right d-none d-sm-block">
             
            <span class="text-muted">Ruhondo</span> | 
            <span class="text-muted"><?php echo $execution_time > 0 ? $execution_time . 's' : ''; ?></span>
        </div>
        <strong>&copy; <?php echo date('Y'); ?> <?php echo $app_name; ?></strong> | 
        Developed by <a href="#" target="_blank"><?php echo $app_company; ?></a>
    </footer>

    <!-- Control Sidebar (right sidebar) -->
    <aside class="control-sidebar control-sidebar-dark">
        <div class="p-3">
            <h5>System Info</h5>
            <hr>
            <ul class="list-unstyled">
                <li><i class="fas fa-database mr-2"></i> Database: <?php echo $db_name; ?></li>
                <li><i class="fas fa-clock mr-2"></i> Time: <?php echo date($datetime_format); ?></li>
                <li><i class="fas fa-globe mr-2"></i> Timezone: <?php echo date_default_timezone_get(); ?></li>
                <li><i class="fas fa-users mr-2"></i> Online Users: <span id="onlineUsers">-</span></li>
            </ul>
            <hr>
            <div class="text-center">
                <button class="btn btn-sm btn-primary" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
                <button class="btn btn-sm btn-info" onclick="clearCache()">
                    <i class="fas fa-trash-alt"></i> Clear Cache
                </button>
            </div>
        </div>
    </aside>
    <!-- /.control-sidebar -->

    <!-- Main Footer (second, visible on mobile) -->
    <div class="mobile-footer d-md-none bg-light text-center py-2 border-top">
        <small class="text-muted">
            <i class="fas fa-copyright"></i> <?php echo date('Y'); ?> <?php echo $app_name; ?>
        </small>
    </div>

</div> <!-- /.wrapper -->

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

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

<!-- AdminLTE JS (for sidebar functionality) -->
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<!-- Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- Datepicker -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>

<!-- Moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

<!-- Toastr -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<!-- jQuery Validation -->
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>

<!-- Print.js for better printing -->
<script src="https://cdn.jsdelivr.net/npm/print-js@1.6.0/dist/print.js"></script>

<!-- Custom App JS - with fallback -->
<?php if (function_exists('assets_url')): ?>
    <script src="<?php echo assets_url('js/app.js'); ?>?v=<?php echo $app_version; ?>"></script>
    <script src="<?php echo assets_url('js/ajax.js'); ?>?v=<?php echo $app_version; ?>"></script>
<?php else: ?>
    <script src="/HMSPOS/assets/js/app.js?v=<?php echo $app_version; ?>"></script>
    <script src="/HMSPOS/assets/js/ajax.js?v=<?php echo $app_version; ?>"></script>
<?php endif; ?>

<!-- Page specific scripts -->
<?php if (isset($extra_js) && is_array($extra_js)): ?>
    <?php foreach ($extra_js as $js): ?>
        <?php if (function_exists('assets_url')): ?>
            <script src="<?php echo assets_url('js/' . $js); ?>?v=<?php echo $app_version; ?>"></script>
        <?php else: ?>
            <script src="/HMSPOS/assets/js/<?php echo $js; ?>?v=<?php echo $app_version; ?>"></script>
        <?php endif; ?>
    <?php endforeach; ?>
<?php endif; ?>

<!-- Inline scripts -->
<?php if (isset($inline_js)): ?>
    <script>
        <?php echo $inline_js; ?>
    </script>
<?php endif; ?>

<script>
    $(document).ready(function() {
        // Global configuration for JavaScript
        window.appConfig = {
            baseUrl: '<?php echo $base_url; ?>',
            assetsUrl: '<?php echo (function_exists('assets_url') ? assets_url('') : '/HMSPOS/assets/'); ?>',
            csrfToken: '<?php echo (function_exists('csrf_token') ? csrf_token() : (isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : '')); ?>',
            csrfParam: '<?php echo $csrf_token_name; ?>',
            userId: <?php echo (function_exists('current_user_id') ? (current_user_id() ?? 'null') : 'null'); ?>,
            userName: '<?php echo isset($_SESSION['username']) ? addslashes($_SESSION['username']) : ''; ?>',
            currencySymbol: '<?php echo $currency_symbol; ?>',
            dateFormat: '<?php echo $date_format; ?>',
            datetimeFormat: '<?php echo $datetime_format; ?>'
        };

        // Toastr configuration
        if (typeof toastr !== 'undefined') {
            toastr.options = {
                closeButton: true,
                progressBar: true,
                positionClass: 'toast-top-right',
                showDuration: 300,
                hideDuration: 1000,
                timeOut: 5000,
                extendedTimeOut: 1000,
                showEasing: 'swing',
                hideEasing: 'linear',
                showMethod: 'fadeIn',
                hideMethod: 'fadeOut'
            };
        }

        // Global AJAX setup
        if (typeof $ !== 'undefined') {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-Token': window.appConfig.csrfToken,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            // Handle AJAX errors globally
            $(document).ajaxError(function(event, jqxhr, settings, error) {
                if (jqxhr.status === 401) {
                    // Unauthorized - redirect to login
                    window.location.href = (window.appConfig.baseUrl || '') + '/public/login.php?redirect=' + encodeURIComponent(window.location.href);
                } else if (jqxhr.status === 403) {
                    // Forbidden
                    if (typeof toastr !== 'undefined') toastr.error('You do not have permission to perform this action');
                } else if (jqxhr.status === 404) {
                    // Not found
                    if (typeof toastr !== 'undefined') toastr.error('The requested resource was not found');
                } else if (jqxhr.status === 422) {
                    // Validation error
                    const response = jqxhr.responseJSON;
                    if (response && response.errors) {
                        $.each(response.errors, function(field, messages) {
                            if (Array.isArray(messages)) {
                                messages.forEach(function(message) {
                                    if (typeof toastr !== 'undefined') toastr.error(message);
                                });
                            } else {
                                if (typeof toastr !== 'undefined') toastr.error(messages);
                            }
                        });
                    } else {
                        if (typeof toastr !== 'undefined') toastr.error('Validation error occurred');
                    }
                } else if (jqxhr.status === 500) {
                    // Server error
                    if (typeof toastr !== 'undefined') toastr.error('An internal server error occurred');
                } else {
                    // Other errors
                    if (typeof toastr !== 'undefined') toastr.error('An error occurred: ' + (jqxhr.responseJSON?.message || error || 'Unknown error'));
                }
                
                // Hide loading overlay
                $('#loadingOverlay').hide();
            });

            // Show loading on AJAX start
            $(document).ajaxStart(function() {
                $('#loadingOverlay').show();
            });

            // Hide loading on AJAX complete
            $(document).ajaxStop(function() {
                $('#loadingOverlay').hide();
            });
        }

        // Get online users count periodically
        function updateOnlineUsers() {
            if (typeof $ === 'undefined') return;
            
            $.get((window.appConfig.baseUrl || '') + '/api/online-users.php', function(data) {
                $('#onlineUsers').text(data.count || '0');
            }).fail(function() {
                $('#onlineUsers').text('-');
            });
        }
        
        // Update every 30 seconds
        setInterval(updateOnlineUsers, 30000);
        setTimeout(updateOnlineUsers, 1000);

        // Handle push menu (sidebar toggle)
        $('[data-widget="pushmenu"]').on('click', function(e) {
            e.preventDefault();
            $('body').toggleClass('sidebar-collapse');
            
            // Save preference
            try {
                localStorage.setItem('sidebarCollapsed', $('body').hasClass('sidebar-collapse'));
            } catch (e) {}
        });

        // Load sidebar state
        try {
            if (localStorage.getItem('sidebarCollapsed') === 'true') {
                $('body').addClass('sidebar-collapse');
            }
        } catch (e) {}

        // Handle dropdown menus on mobile
        if ($(window).width() < 768) {
            $('.nav-sidebar .nav-item').on('click', function(e) {
                if ($(e.target).is('a') && $(this).hasClass('has-treeview')) {
                    e.preventDefault();
                    $(this).toggleClass('menu-open');
                }
            });
        }

        // Initialize tooltips
        if (typeof bootstrap !== 'undefined') {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-toggle="tooltip"]'));
            tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });

            // Initialize popovers
            var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-toggle="popover"]'));
            popoverTriggerList.map(function(popoverTriggerEl) {
                return new bootstrap.Popover(popoverTriggerEl);
            });
        }

        // Handle escape key to close modals
        $(document).keyup(function(e) {
            if (e.key === 'Escape') {
                $('.modal.show').modal('hide');
            }
        });

        // Confirm actions
        $(document).on('click', '[data-confirm]', function(e) {
            e.preventDefault();
            const message = $(this).data('confirm') || 'Are you sure?';
            const href = $(this).attr('href');
            
            if (confirm(message)) {
                window.location.href = href;
            }
        });

        // Form validation defaults
        if ($.validator) {
            $.validator.setDefaults({
                errorElement: 'span',
                errorClass: 'invalid-feedback',
                highlight: function(element) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function(element) {
                    $(element).removeClass('is-invalid');
                },
                errorPlacement: function(error, element) {
                    if (element.parent('.input-group').length) {
                        error.insertAfter(element.parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });
        }
    });

    // Clear system cache
    function clearCache() {
        if (confirm('Are you sure you want to clear the system cache?')) {
            $.post((window.appConfig?.baseUrl || '') + '/api/clear-cache.php', function(response) {
                if (response.status === 'success') {
                    if (typeof toastr !== 'undefined') toastr.success('Cache cleared successfully');
                } else {
                    if (typeof toastr !== 'undefined') toastr.error('Failed to clear cache');
                }
            }).fail(function() {
                if (typeof toastr !== 'undefined') toastr.error('Failed to clear cache');
            });
        }
    }
</script>

</body>
</html>