<?php
// includes/header.php

// Check if a session is already active before starting one
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Branding.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/dashboard_helper.php'; // Include our new helper

// Create a database connection
$database = new Database();
$conn = $database->getConnection();

// Initialize the Auth class
$auth = new Auth($conn);

// Check if user is logged in
$auth->requireLogin();

// Get user's branch name using our new helper function
$branchName = getUserBranchName($_SESSION['user_id'], $conn);
$companyName = Branding::companyName();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/2.3.4/css/dataTables.bootstrap5.css">
    <!-- Using absolute path for CSS for better reliability -->
    <link href="/IMS/assets/css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <!-- DataTables CSS and JS -->
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    <script src="https://cdn.datatables.net/2.3.4/js/dataTables.js"></script>
    <script src="https://cdn.datatables.net/2.3.4/js/dataTables.bootstrap5.js"></script>

    <!-- Add Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .navbar {
            padding: 1rem 0;
        }
        .app-navbar-inner {
            position: relative;
            min-height: 44px;
        }

        .app-navbar-inner .navbar-brand {
            position: absolute;
            left: 50%;
            max-width: min(70vw, 760px);
            margin: 0;
            overflow: hidden;
            text-align: center;
            text-overflow: ellipsis;
            white-space: nowrap;
            transform: translateX(-50%);
        }

        .app-navbar-actions {
            margin-left: auto;
        }

        .navbar-nav.ms-auto {
            margin-left: auto !important;
        }
        @media (max-width: 575.98px) {
            .app-navbar-inner .navbar-brand {
                max-width: calc(100vw - 110px);
                font-size: 1rem;
                letter-spacing: 1px;
            }
        }
        
        /* Profile dropdown styles */
        .dropdown-menu {
            min-width: 280px; /* Increased width to fit content */
            padding: 0; /* Remove padding to use our own structure */
            border-radius: 5px;
            border: 1px solid rgba(0,0,0,0.1);
        }
        
        .user-info-header {
            background-color: #f8f9fa;
            padding: 15px;
            border-bottom: 1px solid #dee2e6;
        }

        .user-info-body {
             padding: 15px;
        }

        .user-info-item {
            display: flex;
            justify-content: space-between;
            font-size: 0.9rem;
            margin-bottom: 8px;
        }

        .user-info-label {
            font-weight: bold;
            color: #495057;
            margin-right: 10px;
        }

        .user-info-value {
             color: #6c757d;
             text-align: right;
        }
        
        .profile-icon {
            margin-right: 10px;
        }

        .dropdown-item {
            padding: 10px 15px;
        }
    </style>
    <link href="/IMS/assets/css/responsive.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid app-navbar-inner">
<!-- Center company name on all pages -->
            <a class="navbar-brand" href="<?php echo getDashboardLink(); ?>"><?php echo htmlspecialchars(Branding::companyNameUpper()); ?></a>
            
            <ul class="navbar-nav app-navbar-actions">
                <!-- Chat -->
                <li class="nav-item">
                    <a class="nav-link position-relative" href="/IMS/views/messages/inbox.php" title="Messages">
                        <i class="fas fa-comments"></i>
                        <span id="chatUnreadBadge" class="badge bg-danger rounded-pill position-absolute d-none" style="top: 2px; left: 20px; font-size: 0.6rem;">0</span>
                    </a>
                </li>
                <!-- Profile Dropdown -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="profileDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle profile-icon"></i><span class="profile-label">Profile</span>
                    </a>
                    <div class="dropdown-menu dropdown-menu-end" aria-labelledby="profileDropdown">
                        <div class="user-info-header">
                            <h6 class="mb-0 text-center"><?php echo htmlspecialchars($_SESSION['username']); ?></h6>
                        </div>
                        <div class="user-info-body">
                            <div class="user-info-item">
                                <span class="user-info-label">Role:</span>
                                <span class="user-info-value"><?php echo ucfirst(htmlspecialchars($_SESSION['role'])); ?></span>
                            </div>
                            <div class="user-info-item">
                                <span class="user-info-label">Branch:</span>
                                <span class="user-info-value"><?php echo htmlspecialchars($branchName); ?></span>
                            </div>
                        </div>
                        <div class="dropdown-divider m-0"></div>
                        <a class="dropdown-item" href="/IMS/views/users/change_password.php">
                            <i class="fas fa-key me-2 text-muted"></i>Change Password
                        </a>
                        <div class="dropdown-divider m-0"></div>
                        <!-- Point to the new logout script -->
                        <a class="dropdown-item" href="/IMS/logout.php" >
                            <i class="fas fa-sign-out-alt me-2 text-muted"></i>Logout
                        </a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>
    
    <script>
        (function () {
            function refreshChatBadge() {
                fetch('/IMS/ajax/messages_unread_count.php')
                    .then(r => r.json())
                    .then(data => {
                        if (!data.success) return;
                        const badge = document.getElementById('chatUnreadBadge');
                        if (!badge) return;
                        if (data.unread_count > 0) {
                            badge.textContent = data.unread_count > 99 ? '99+' : data.unread_count;
                            badge.classList.remove('d-none');
                        } else {
                            badge.classList.add('d-none');
                        }
                    })
                    .catch(() => {});
            }
            refreshChatBadge();
            setInterval(refreshChatBadge, 15000);
        })();
    </script>
    <?php
    // Detect if this is a dashboard page based on the current script path
    $currentScript = $_SERVER['SCRIPT_NAME'];
    $isDashboard = (strpos($currentScript, '/dashboard/') !== false || 
                   strpos($currentScript, 'dashboard') !== false ||
                   strpos($currentScript, '/admin/') !== false ||
                   strpos($currentScript, '/warehouse/') !== false ||
                   strpos($currentScript, '/branch/') !== false ||
                   strpos($currentScript, '/stocktaking/') !== false ||
                   strpos($currentScript, 'stocktaking') !== false ||
                   strpos($currentScript, '/reports/') !== false ||
                   strpos($currentScript, '/inventory/') !== false ||
                   strpos($currentScript, '/sales/') !== false ||
                   strpos($currentScript, '/shipments/') !== false ||
                   strpos($currentScript, '/tracking/') !== false ||
                   strpos($currentScript, '/disposals/') !== false ||
                   strpos($currentScript, '/customer_service/') !== false ||
                   strpos($currentScript, '/services/') !== false ||
                   strpos($currentScript, '/reminders/') !== false ||
                   strpos($currentScript, '/expenses/') !== false ||
                   strpos($currentScript, '/orders/') !== false ||
                   strpos($currentScript, '/users/') !== false ||
                   strpos($currentScript, '/branches/') !== false ||
                   strpos($currentScript, '/logs/') !== false ||
                   strpos($currentScript, '/laybuy_&_loans/') !== false);
    
    // Use appropriate container class based on page type
    if ($isDashboard): ?>
        <!-- Dashboard pages: use wider container for better readability -->
        <main class="app-page-container app-page-container--wide mt-4">
    <?php else: ?>
        <!-- Regular pages: use standard container -->
        <main class="app-page-container mt-4">
    <?php endif; ?>
