<?php
/**
 * Navbar - FIXED to show correct department
 */

// Get user data from database session
$user = null;
$auth_token = $_COOKIE['rcp_auth'] ?? null;

if ($auth_token) {
    try {
        // Include config and database without redefining constants
        require_once __DIR__ . '/config.php';
        require_once __DIR__ . '/database.php';
        $pdo = Database::getInstance()->getConnection();
        
        // First get session data
        $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
        $stmt->execute([$auth_token]);
        $session_data = $stmt->fetchColumn();
        
        if ($session_data) {
            $user = json_decode($session_data, true);
            
            // Now get fresh user data including department from users table
            if (isset($user['user_id'])) {
                $stmt = $pdo->prepare("SELECT u.*, un.name as unit_name 
                                      FROM users u 
                                      LEFT JOIN units un ON u.unit_id = un.id 
                                      WHERE u.id = ?");
                $stmt->execute([$user['user_id']]);
                $fresh_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($fresh_user_data) {
                    // Update the user array with fresh data including department
                    $user['user_full_name'] = $fresh_user_data['full_name'];
                    $user['user_role'] = $fresh_user_data['role'];
                    $user['department'] = $fresh_user_data['department'];
                    $user['unit_name'] = $fresh_user_data['unit_name'] ?? $fresh_user_data['department'] ?? 'Unknown Unit';
                }
            }
        }
    } catch (Throwable $t) {
        // Silent fail - user will see generic navbar
        error_log("Navbar error: " . $t->getMessage());
    }
}

// Fallback if no user session
if (!$user) {
    $user = [
        'user_full_name' => 'User',
        'user_role' => 'user',
        'unit_name' => 'Unknown Unit',
        'department' => 'Unknown Unit'
    ];
}

// Use existing constants (already defined in config.php)
$base_path = defined('WEB_BASE') ? WEB_BASE : '/rcp/';
?>

<style>
    .navbar-dark.bg-dark {
        background-color: #8B0000 !important; /* Deep red */
        border-bottom: 3px solid #600000;
    }
    .nav-link {
        color: #ffffff !important;
        font-weight: 500;
    }
    .nav-link:hover {
        background-color: #600000;
        border-radius: 4px;
    }
    .dropdown-menu {
        background-color: #8B0000;
        border: 1px solid #600000;
    }
    .dropdown-item {
        color: #ffffff;
    }
    .dropdown-item:hover {
        background-color: #600000;
        color: #ffffff;
    }
    .navbar-brand {
        font-weight: bold;
        font-size: 1.3rem;
    }
    /* Ensure dropdown works properly */
    .dropdown:hover .dropdown-menu {
        display: block;
    }
    .navbar-logo {
        height: 100px;
        margin-right: 10px;
    }
</style>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="<?= $base_path ?>pages/dashboard.php">
      <img src="<?= $base_path ?>assets/images/logo.png" alt="Smart Serve Pro" class="navbar-logo">
      
    </a>
    
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link" href="<?= $base_path ?>pages/dashboard.php">
            <i class="fas fa-tachometer-alt"></i> Dashboard
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?= $base_path ?>pages/ingredients.php">
            <i class="fas fa-carrot"></i> Ingredient Bank
          </a>
        </li>
                <li class="nav-item">
          <a class="nav-link" href="<?= $base_path ?>pages/costing.php">
            <i class="fas fa-calculator"></i> Recipe Costings
          </a>
        </li>
                <li class="nav-item">
          <a class="nav-link" href="<?= $base_path ?>pages/meals.php">
            <i class="fas fa-clipboard-list"></i> Compile Meal
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?= $base_path ?>pages/schedules.php">
            <i class="fas fa-utensils"></i> Production Schedules
          </a>
        </li>
        <li class="nav-item">
    <a class="nav-link" href="issue_sheets.php">
        <i class="fas fa-file-export"></i> Issue Sheets
    </a>
</li>
      </ul>
      
      <ul class="navbar-nav ms-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="fas fa-user-circle"></i> 
            <?= htmlspecialchars($user['user_full_name'] ?? 'User') ?>
            <?php if (($user['user_role'] ?? '') === 'superuser'): ?>
              <span class="badge bg-warning ms-1">Superuser</span>
            <?php endif; ?>
          </a>
          <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
            <li><span class="dropdown-item-text">
              <small class="text-white-50">Logged in to: <?= htmlspecialchars($user['unit_name'] ?? $user['department'] ?? 'Unknown Unit') ?></small>
            </span></li>
            <li><hr class="dropdown-divider"></li>
            <?php if (($user['user_role'] ?? '') === 'superuser'): ?>
            <li><a class="dropdown-item" href="<?= $base_path ?>pages/users.php">
              <i class="fas fa-users"></i> User Management
            </a></li>
            <li><a class="dropdown-item" href="<?= $base_path ?>pages/settings.php">
              <i class="fas fa-cog"></i> System Settings
            </a></li>
            <li><hr class="dropdown-divider"></li>
            <?php endif; ?>
            <li><a class="dropdown-item" href="<?= $base_path ?>pages/logout.php">
              <i class="fas fa-sign-out-alt"></i> Logout
            </a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>