<?php
/**
 * Job Portal Navbar Component
 * GHAMECC Job Portal - Uses job_portal_users session data
 */

// Include notifications library and auth functions
require_once __DIR__ . '/../../includes/notifications-library.php';
require_once __DIR__ . '/../../includes/auth.php';

// Base path for job portal - use relative path from root
$jobPortalBasePath = '/ghameccapp/jobs';

// Get current page for active state
$currentPage = basename($_SERVER['PHP_SELF']);
$currentDir = dirname($_SERVER['PHP_SELF']);

// Check if user is logged in to job portal
function isJobPortalLoggedIn() {
    return isset($_SESSION['user_id']) && isset($_SESSION['user_email']);
}

// Check if user can approve jobs (member with employer privileges or admin)
function canApproveJobs() {
    if (!isJobPortalLoggedIn()) return false;
    
    // Check if user is admin type
    if (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin') {
        return true;
    }
    
    // Check if user is a member with society secretary or choirmaster role
    if (isset($_SESSION['member_id']) && !empty($_SESSION['member_id'])) {
        $memberQuery = "SELECT u.role_id, r.role_key FROM users u 
                       JOIN roles r ON u.role_id = r.id 
                       WHERE u.member_id = ?";
        $memberRole = fetchRow($memberQuery, [$_SESSION['member_id']]);
        
        if ($memberRole) {
            return in_array($memberRole['role_key'], ['admin', 'society_secretary', 'choirmaster']) || $memberRole['role_id'] == 1;
        }
    }
    
    return false;
}
?>

<nav class="navbar navbar-expand-lg navbar-dark sticky-top" style="background-color: #254094;">
    <div class="container">
        <a class="navbar-brand d-flex align-items-center" href="<?php echo $jobPortalBasePath; ?>/index.php">
            <img src="<?php echo $basePath; ?>/includes/uploads/ghamecclogooriginal.png" alt="GHAMECC" height="40" class="d-inline-block align-text-top me-2">
            <span>GHAMECC Job Portal</span>
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'index.php' ? 'active' : ''; ?>" aria-current="page" href="<?php echo $jobPortalBasePath; ?>/index.php">
                        <i class="fas fa-home me-1"></i> Home
                    </a>
                </li>
                
                <li class="nav-item">
                    <?php 
                    // Determine the correct Jobs page based on user role
                    $jobsPage = 'job-listings.php';
                    $jobsActiveCheck = 'job-listings.php';
                    
                    if (canApproveJobs()) {
                        $jobsPage = 'job-approval.php';
                        $jobsActiveCheck = 'job-approval.php';
                    }
                    ?>
                    <a class="nav-link <?php echo $currentPage === $jobsActiveCheck ? 'active' : ''; ?>" href="<?php echo $jobPortalBasePath; ?>/<?php echo $jobsPage; ?>">
                        <i class="fas fa-briefcase me-1"></i> Jobs
                    </a>
                </li>
                
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'talent-showcase.php' ? 'active' : ''; ?>" href="<?php echo $jobPortalBasePath; ?>/talent-showcase.php">
                        <i class="fas fa-user-tie me-1"></i> Talent
                    </a>
                </li>
                
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'categories.php' ? 'active' : ''; ?>" href="<?php echo $jobPortalBasePath; ?>/categories.php">
                        <i class="fas fa-tags me-1"></i> Categories
                    </a>
                </li>
                
                <?php if (isJobPortalLoggedIn()): ?>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle <?php echo strpos($currentPage, 'profile') !== false ? 'active' : ''; ?>" href="#" id="profileDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-id-card me-1"></i> My Profile
                    </a>
                    <ul class="dropdown-menu" aria-labelledby="profileDropdown">
                        <li>
                            <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/create-profile.php">
                                <i class="fas fa-edit me-2"></i> Edit Profile
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/my-applications.php">
                                <i class="fas fa-file-alt me-2"></i> My Applications
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/my-jobs.php">
                                <i class="fas fa-briefcase me-2"></i> My Job Postings
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/my-ratings.php">
                                <i class="fas fa-star me-2"></i> My Ratings & Reviews
                            </a>
                        </li>
                    </ul>
                </li>
                
                <?php if (canApproveJobs()): ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $currentPage === 'job-approval.php' ? 'active' : ''; ?>" href="<?php echo $jobPortalBasePath; ?>/job-approval.php">
                        <i class="fas fa-clipboard-check me-1"></i> Job Approvals
                    </a>
                </li>
                <?php endif; ?>
                <?php endif; ?>
            </ul>
            
            <div class="d-flex align-items-center">
                <?php if (isJobPortalLoggedIn()): ?>
                    <!-- Job Portal Notifications Dropdown -->
                    <div class="dropdown">
                        <a class="nav-link position-relative" href="#" id="notificationsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-bell"></i>
                            <?php echo displayNotificationBadge($_SESSION['user_id']); ?>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end notification-dropdown" style="width: 320px; max-height: 400px; overflow-y: auto;" aria-labelledby="notificationsDropdown">
                            <div class="d-flex justify-content-between align-items-center p-3 border-bottom">
                                <h6 class="mb-0">Notifications</h6>
                                <a href="<?php echo $jobPortalBasePath; ?>/notifications.php" class="text-decoration-none small">View All</a>
                            </div>
                            <?php echo displayNotificationDropdownItems($_SESSION['user_id']); ?>
                            <div class="text-center p-2 border-top">
                                <a href="<?php echo $jobPortalBasePath; ?>/ajax/mark_all_notifications_read.php" 
                                   class="btn btn-sm btn-light mark-all-read"
                                   data-bs-toggle="tooltip"
                                   data-bs-placement="bottom"
                                   title="Mark all as read">
                                    <i class="fas fa-check-double me-1"></i> Mark all as read
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- User Dropdown -->
                    <div class="dropdown ms-3">
                        <a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <?php if (isset($_SESSION['profile_image']) && !empty($_SESSION['profile_image'])): ?>
                                <img src="/uploads/profile/<?php echo $_SESSION['profile_image']; ?>" alt="Profile" class="rounded-circle me-2" width="32" height="32">
                            <?php else: ?>
                                <div class="avatar-circle me-2">
                                    <?php
                                    $initials = "";
                                    if (isset($_SESSION['user_name']) && !empty($_SESSION['user_name'])) {
                                        $nameParts = explode(" ", $_SESSION['user_name']);
                                        if (count($nameParts) >= 2) {
                                            $initials = strtoupper(substr($nameParts[0], 0, 1) . substr($nameParts[count($nameParts) - 1], 0, 1));
                                        } else {
                                            $initials = strtoupper(substr($_SESSION['user_name'], 0, 2));
                                        }
                                    } elseif (isset($_SESSION['user_email']) && !empty($_SESSION['user_email'])) {
                                        $initials = strtoupper(substr($_SESSION['user_email'], 0, 2));
                                    } else {
                                        $initials = "U";
                                    }
                                    echo $initials;
                                    ?>
                                </div>
                            <?php endif; ?>
                            <span class="d-none d-md-inline-block">
                                <?php 
                                if (isset($_SESSION['user_name']) && !empty($_SESSION['user_name'])) {
                                    echo htmlspecialchars($_SESSION['user_name']);
                                } elseif (isset($_SESSION['user_email']) && !empty($_SESSION['user_email'])) {
                                    echo htmlspecialchars($_SESSION['user_email']);
                                } else {
                                    echo 'User';
                                }
                                ?>
                            </span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li>
                                <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/notifications.php">
                                    <i class="fas fa-bell me-2"></i> Notifications
                                    <?php echo displayNotificationBadge($_SESSION['user_id'], true); ?>
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/create-profile.php">
                                    <i class="fas fa-user me-2"></i> Job Portal Profile
                                </a>
                            </li>
                            <?php if (isset($_SESSION['member_id']) && !empty($_SESSION['member_id'])): ?>
                            <li>
                                <a class="dropdown-item" href="/profile.php">
                                    <i class="fas fa-id-badge me-2"></i> Main GHAMECC Profile
                                </a>
                            </li>
                            <?php endif; ?>
                            <li>
                                <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/change-password.php">
                                    <i class="fas fa-key me-2"></i> Change Password
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item" href="<?php echo $jobPortalBasePath; ?>/logout.php">
                                    <i class="fas fa-sign-out-alt me-2"></i> Logout
                                </a>
                            </li>
                        </ul>
                    </div>
                <?php else: ?>
                    <a href="<?php echo $jobPortalBasePath; ?>/login.php" class="btn btn-outline-light me-2">
                        <i class="fas fa-sign-in-alt me-1"></i> Login
                    </a>
                    <a href="<?php echo $jobPortalBasePath; ?>/register.php" class="btn btn-light">
                        <i class="fas fa-user-plus me-1"></i> Register
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</nav>

<!-- JavaScript for notification interactions -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Mark notification as read when clicked
    document.querySelectorAll('.notification-item').forEach(function(item) {
        item.addEventListener('click', function(e) {
            const notificationId = this.dataset.id;
            if (notificationId) {
                fetch('<?php echo $jobPortalBasePath; ?>/ajax/mark_notification_read.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'notification_id=' + notificationId
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.classList.remove('unread');
                    }
                })
                .catch(error => console.error('Error:', error));
            }
        });
    });
    
    // Mark all notifications as read
    document.querySelector('.mark-all-read')?.addEventListener('click', function(e) {
        e.preventDefault();
        
        fetch(this.getAttribute('href'), {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.querySelectorAll('.notification-item.unread').forEach(function(item) {
                    item.classList.remove('unread');
                });
                
                // Update badge counts
                document.querySelectorAll('.notification-badge').forEach(function(badge) {
                    badge.textContent = '0';
                    badge.classList.add('d-none');
                });
            }
        })
        .catch(error => console.error('Error:', error));
    });
    
    // Initialize tooltips
    if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

<!-- Custom CSS for notifications -->
<style>
.notification-dropdown {
    padding: 0;
}

.notification-item {
    padding: 0.75rem 1rem;
    display: flex;
    align-items: flex-start;
    border-bottom: 1px solid rgba(0,0,0,.05);
    cursor: pointer;
    transition: background-color 0.2s;
}

.notification-item:hover {
    background-color: rgba(0,0,0,.03);
}

.notification-item.unread {
    background-color: rgba(13, 110, 253, 0.05);
    border-left: 3px solid #0d6efd;
}

.notification-icon {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    margin-right: 12px;
    flex-shrink: 0;
}

.notification-content {
    flex-grow: 1;
}

.notification-title {
    font-weight: 600;
    font-size: 0.9rem;
    margin-bottom: 2px;
}

.notification-text {
    font-size: 0.85rem;
    color: #6c757d;
    margin-bottom: 2px;
}

.notification-time {
    font-size: 0.75rem;
    color: #adb5bd;
}

.avatar-circle {
    width: 32px;
    height: 32px;
    background-color: #007bff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 14px;
    font-weight: 600;
}

.notification-badge {
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(25%, -25%);
    font-size: 0.65rem;
    padding: 0.25rem 0.4rem;
}

.empty-notifications {
    padding: 1.5rem;
    text-align: center;
    color: #6c757d;
}

.empty-notifications i {
    font-size: 2rem;
    color: #dee2e6;
    margin-bottom: 0.5rem;
}
</style>
