<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Top Navigation Bar Partial
 * Developer: JOACHIM'S INNOTECH
 */

// Get current user
$current_user = is_logged_in() ? current_user() : null;

// Get unread notifications count (with fallback)
$unread_notifications = 0;
if (is_logged_in() && $current_user) {
    if (function_exists('get_unread_notification_count')) {
        $unread_notifications = get_unread_notification_count($current_user['user_id'] ?? 0);
    } else {
        // Fallback - try to query directly
        try {
            if (function_exists('db_fetch_value')) {
                $unread_notifications = (int)db_fetch_value(
                    "SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0",
                    [$current_user['user_id'] ?? 0]
                ) ?: 0;
            }
        } catch (Exception $e) {
            error_log("Error getting notification count: " . $e->getMessage());
        }
    }
}
?>

<!-- Navbar -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <!-- Left navbar links -->
    <ul class="navbar-nav">
        <li class="nav-item">
            <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
        </li>
        <li class="nav-item d-none d-sm-inline-block">
            <a href="<?php echo function_exists('base_url') ? base_url('dashboard.php') : '/public/dashboard.php'; ?>" class="nav-link">Home</a>
        </li>
        <li class="nav-item d-none d-sm-inline-block">
            <a href="<?php echo function_exists('base_url') ? base_url('profile.php') : '/public/profile.php'; ?>" class="nav-link">Profile</a>
        </li>
    </ul>

    <!-- Right navbar links -->
    <ul class="navbar-nav ml-auto">
        
        <!-- Notifications Dropdown Menu -->
        <li class="nav-item dropdown">
            <a class="nav-link" data-toggle="dropdown" href="#">
                <i class="far fa-bell"></i>
                <?php if ($unread_notifications > 0): ?>
                    <span class="badge badge-warning navbar-badge"><?php echo $unread_notifications; ?></span>
                <?php endif; ?>
            </a>
            <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
                <span class="dropdown-item dropdown-header"><?php echo $unread_notifications; ?> Notifications</span>
                <div class="dropdown-divider"></div>
                
                <?php
                if (is_logged_in() && $current_user) {
                    $notifications = [];
                    
                    // Try to get notifications using function or direct query
                    if (function_exists('get_user_notifications')) {
                        $notifications = get_user_notifications($current_user['user_id'], 5);
                    } else {
                        // Fallback direct query
                        try {
                            if (function_exists('db_fetch_all')) {
                                $notifications = db_fetch_all(
                                    "SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 5",
                                    [$current_user['user_id']]
                                ) ?: [];
                            }
                        } catch (Exception $e) {
                            error_log("Error getting notifications: " . $e->getMessage());
                        }
                    }
                    
                    if (!empty($notifications)):
                        foreach ($notifications as $note):
                ?>
                    <a href="<?php echo (!empty($note['link']) && function_exists('base_url')) ? base_url($note['link']) : '#'; ?>" class="dropdown-item">
                        <i class="fas fa-<?php 
                            $icon = 'info-circle';
                            $color = 'text-info';
                            
                            if (isset($note['type'])) {
                                switch($note['type']) {
                                    case 'success':
                                        $icon = 'check-circle';
                                        $color = 'text-success';
                                        break;
                                    case 'warning':
                                        $icon = 'exclamation-triangle';
                                        $color = 'text-warning';
                                        break;
                                    case 'danger':
                                    case 'error':
                                        $icon = 'times-circle';
                                        $color = 'text-danger';
                                        break;
                                    case 'info':
                                    default:
                                        $icon = 'info-circle';
                                        $color = 'text-info';
                                }
                            }
                            echo $icon . ' ' . $color;
                        ?> mr-2"></i>
                        <span class="font-weight-bold"><?php echo isset($note['title']) ? htmlspecialchars($note['title']) : 'Notification'; ?></span>
                        <br>
                        <small><?php echo isset($note['message']) ? htmlspecialchars(substr($note['message'], 0, 50)) . (strlen($note['message'] ?? '') > 50 ? '...' : '') : ''; ?></small>
                        <br>
                        <small class="text-muted">
                            <?php 
                            if (isset($note['created_at'])) {
                                if (function_exists('time_ago')) {
                                    echo time_ago($note['created_at']);
                                } else {
                                    echo date('M d, H:i', strtotime($note['created_at']));
                                }
                            }
                            ?>
                        </small>
                    </a>
                    <div class="dropdown-divider"></div>
                <?php 
                        endforeach;
                    else:
                ?>
                    <div class="text-center text-muted py-3">
                        <i class="far fa-bell-slash fa-2x mb-2"></i>
                        <p>No notifications</p>
                    </div>
                <?php
                    endif;
                }
                ?>
                
                <a href="<?php echo function_exists('base_url') ? base_url('notifications.php') : '/public/notifications.php'; ?>" class="dropdown-item dropdown-footer">See All Notifications</a>
            </div>
        </li>
        
        <!-- Fullscreen button -->
        <li class="nav-item">
            <a class="nav-link" href="#" id="fullscreenToggle">
                <i class="fas fa-expand-arrows-alt"></i>
            </a>
        </li>
        
        <!-- User Dropdown Menu -->
        <li class="nav-item dropdown user-menu">
            <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown">
                <?php if ($current_user && !empty($current_user['profile_image'])): ?>
                    <img src="<?php echo function_exists('uploads_url') ? uploads_url($current_user['profile_image']) : '/uploads/' . $current_user['profile_image']; ?>" class="user-image img-circle elevation-2" alt="User Image">
                <?php else: ?>
                    <img src="https://www.gravatar.com/avatar/<?php echo md5(strtolower(trim($current_user['email'] ?? ''))); ?>?s=160&d=mp" class="user-image img-circle elevation-2" alt="User Image">
                <?php endif; ?>
                <span class="d-none d-md-inline"><?php echo htmlspecialchars($current_user['first_name'] ?? ($current_user['username'] ?? 'User')); ?></span>
            </a>
            <ul class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
                <!-- User image -->
                <li class="user-header bg-primary">
                    <?php if ($current_user && !empty($current_user['profile_image'])): ?>
                        <img src="<?php echo function_exists('uploads_url') ? uploads_url($current_user['profile_image']) : '/uploads/' . $current_user['profile_image']; ?>" class="img-circle elevation-2" alt="User Image">
                    <?php else: ?>
                        <img src="https://www.gravatar.com/avatar/<?php echo md5(strtolower(trim($current_user['email'] ?? ''))); ?>?s=160&d=mp" class="img-circle elevation-2" alt="User Image">
                    <?php endif; ?>
                    <p>
                        <?php echo htmlspecialchars(($current_user['first_name'] ?? '') . ' ' . ($current_user['last_name'] ?? '')); ?>
                        <small>
                            Member since 
                            <?php 
                            if (!empty($current_user['created_at'])) {
                                if (function_exists('format_date')) {
                                    echo format_date($current_user['created_at'], 'F Y');
                                } else {
                                    echo date('F Y', strtotime($current_user['created_at']));
                                }
                            }
                            ?>
                        </small>
                    </p>
                </li>
                <!-- Menu Body -->
                <li class="user-body">
                    <div class="row">
                        <div class="col-4 text-center">
                            <a href="<?php echo function_exists('base_url') ? base_url('profile.php') : '/public/profile.php'; ?>"><i class="fas fa-user mr-1"></i> Profile</a>
                        </div>
                        <div class="col-4 text-center">
                            <a href="<?php echo function_exists('base_url') ? base_url('profile.php#settings') : '/public/profile.php#settings'; ?>"><i class="fas fa-cog mr-1"></i> Settings</a>
                        </div>
                        <div class="col-4 text-center">
                            <a href="<?php echo function_exists('base_url') ? base_url('notifications.php') : '/public/notifications.php'; ?>"><i class="fas fa-bell mr-1"></i> Notifications</a>
                        </div>
                    </div>
                </li>
                <!-- Menu Footer -->
                <li class="user-footer">
                    <a href="<?php echo function_exists('base_url') ? base_url('profile.php') : '/public/profile.php'; ?>" class="btn btn-default btn-flat">
                        <i class="fas fa-user-circle"></i> Profile
                    </a>
                    <a href="<?php echo function_exists('base_url') ? base_url('logout.php') : '/public/logout.php'; ?>" class="btn btn-default btn-flat float-right" onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                        <i class="fas fa-sign-out-alt"></i> Sign out
                    </a>
                    <form id="logout-form" action="<?php echo function_exists('base_url') ? base_url('logout.php') : '/public/logout.php'; ?>" method="POST" style="display: none;">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    </form>
                </li>
            </ul>
        </li>
        
        <!-- Control Sidebar Toggle Button -->
        <li class="nav-item">
            <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button">
                <i class="fas fa-th-large"></i>
            </a>
        </li>
    </ul>
</nav>
<!-- /.navbar -->

<!-- Quick Actions Bar (visible on small screens) -->
<div class="quick-actions-bar d-md-none bg-light p-2 border-bottom">
    <div class="d-flex justify-content-around">
        <a href="<?php echo function_exists('base_url') ? base_url('dashboard.php') : '/public/dashboard.php'; ?>" class="text-center" data-toggle="tooltip" title="Dashboard">
            <i class="fas fa-tachometer-alt fa-lg"></i>
            <small class="d-block">Home</small>
        </a>
        <a href="<?php echo function_exists('base_url') ? base_url('reservations/create.php') : '/public/reservations/create.php'; ?>" class="text-center" data-toggle="tooltip" title="New Booking">
            <i class="fas fa-plus-circle fa-lg"></i>
            <small class="d-block">Booking</small>
        </a>
        <a href="<?php echo function_exists('base_url') ? base_url('pos/sales/pos.php') : '/public/pos/sales/pos.php'; ?>" class="text-center" data-toggle="tooltip" title="POS">
            <i class="fas fa-cash-register fa-lg"></i>
            <small class="d-block">POS</small>
        </a>
        <a href="<?php echo function_exists('base_url') ? base_url('search.php') : '/public/search.php'; ?>" class="text-center" data-toggle="tooltip" title="Search">
            <i class="fas fa-search fa-lg"></i>
            <small class="d-block">Search</small>
        </a>
    </div>
</div>

<!-- Add CSS for topbar -->
<style>
    .user-menu .user-image {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        margin-right: 5px;
    }
    
    .user-header .img-circle {
        width: 90px;
        height: 90px;
        border: 3px solid rgba(255, 255, 255, 0.3);
    }
    
    .quick-actions-bar {
        position: sticky;
        top: 0;
        z-index: 1030;
    }
    
    .quick-actions-bar a {
        color: #495057;
        text-decoration: none;
        font-size: 0.8rem;
    }
    
    .quick-actions-bar a:hover {
        color: #007bff;
    }
    
    .navbar-badge {
        font-size: .6rem;
        font-weight: 300;
        padding: 2px 4px;
        position: absolute;
        right: 5px;
        top: 5px;
    }
    
    @media (max-width: 576px) {
        .user-menu span {
            display: none !important;
        }
        
        .user-menu .user-image {
            width: 25px;
            height: 25px;
        }
    }
</style>

<script>
    // Toggle fullscreen
    document.getElementById('fullscreenToggle')?.addEventListener('click', function(e) {
        e.preventDefault();
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen();
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
        }
    });
    
    // Update fullscreen icon
    document.addEventListener('fullscreenchange', function() {
        const icon = document.querySelector('#fullscreenToggle i');
        if (icon) {
            if (document.fullscreenElement) {
                icon.className = 'fas fa-compress-arrows-alt';
            } else {
                icon.className = 'fas fa-expand-arrows-alt';
            }
        }
    });
</script>