<?php
// includes/header.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// طرد المستخدم إذا لم يكن مسجلاً للدخول
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    // تعديل المسار ليكون ديناميكياً في حال كنا في مجلد فرعي
    $redirect_path = (strpos($_SERVER['SCRIPT_NAME'], '/hr/') !== false) ? '../../login.php' : '../login.php';
    header("location: $redirect_path");
    exit;
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/modules/audit_logger.php';

// =========================================================
// تعديل جوهري: تحديد مسار الملفات (CSS, Images, Links)
// =========================================================
// إذا كنا داخل مجلد "hr"، يجب أن نعود خطوتين للخلف (../../)
// وإذا كنا في مجلد "pages" العادي، نعود خطوة واحدة (../)
$path_prefix = "../";
if (strpos($_SERVER['SCRIPT_NAME'], '/hr/') !== false) {
    $path_prefix = "../../";
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>نادي الإمارات - الخدمات الإلكترونية</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    
    <link href="<?php echo $path_prefix; ?>assets/css/style.css" rel="stylesheet">
    
    <style>
        .navbar-custom { background-color: var(--ec-green); }
        .navbar-brand img { height: 40px; margin-left: 10px; }
        .nav-link { color: white !important; font-weight: 500; }
        .nav-link:hover { color: var(--ec-gold) !important; }
        .user-badge { background: rgba(255,255,255,0.2); padding: 5px 15px; border-radius: 20px; color: white; }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-custom shadow-sm no-print">
  <div class="container-fluid">
    <a class="navbar-brand text-white fw-bold" href="<?php echo $path_prefix; ?>pages/dashboard.php">
      <img src="<?php echo $path_prefix; ?>assets/images/emirates_club_logo.png" alt="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 mb-2 mb-lg-0">
        
        <li class="nav-item">
            <?php 
                // توجيه الصفحة الرئيسية حسب الدور
                $home_link = $path_prefix . 'pages/my_requests.php'; // الافتراضي
                
                if(in_array($_SESSION['role'], ['super_admin', 'ceo', 'hr_manager'])) {
                    $home_link = $path_prefix . 'pages/dashboard.php';
                } elseif($_SESSION['role'] == 'purchasing') {
                    $home_link = $path_prefix . 'pages/purchasing_panel.php';
                } elseif($_SESSION['role'] == 'supervisor') {
                    $home_link = $path_prefix . 'pages/supervisor_panel.php';
                } elseif($_SESSION['role'] == 'accountant') { // <--- إضافة المحاسب هنا
                    $home_link = $path_prefix . 'pages/finance_panel.php'; 
                }
            ?>
          <a class="nav-link" href="<?php echo $home_link; ?>"><i class="bi bi-house-door"></i> الرئيسية</a>
        </li>
        
        <?php if(in_array($_SESSION['role'], ['super_admin', 'ceo'])): ?>
            <li class="nav-item">
            <a class="nav-link" href="<?php echo $path_prefix; ?>pages/manage_requests.php"><i class="bi bi-check-circle"></i> اعتماد الطلبات</a>
            </li>
        <?php endif; ?>

        <?php if(in_array($_SESSION['role'], ['super_admin', 'purchasing'])): ?>
            <li class="nav-item">
            <a class="nav-link" href="<?php echo $path_prefix; ?>pages/purchasing_panel.php"><i class="bi bi-currency-dollar"></i> لوحة المشتريات</a>
            </li>
        <?php endif; ?>
        
        <?php if(in_array($_SESSION['role'], ['super_admin', 'accountant'])): ?>
            <li class="nav-item">
            <a class="nav-link" href="<?php echo $path_prefix; ?>pages/finance_panel.php"><i class="bi bi-cash-stack"></i> الإدارة المالية</a>
            </li>
        <?php endif; ?>

        <?php if(in_array($_SESSION['role'], ['super_admin', 'supervisor'])): ?>
            <li class="nav-item">
            <a class="nav-link" href="<?php echo $path_prefix; ?>pages/supervisor_panel.php"><i class="bi bi-clipboard-check"></i> لوحة المشرف العام</a>
            </li>
        <?php endif; ?>

        <?php if($_SESSION['role'] == 'super_admin'): ?>
            <li class="nav-item">
                <a class="nav-link text-warning fw-bold" href="<?php echo $path_prefix; ?>pages/manage_users.php">
                    <i class="bi bi-people-fill"></i> المستخدمين
                </a>
            </li>
        <?php endif; ?>

        <li class="nav-item">
          <a class="nav-link" href="<?php echo $path_prefix; ?>pages/new_request.php"><i class="bi bi-plus-circle"></i> طلب جديد</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?php echo $path_prefix; ?>pages/my_requests.php"><i class="bi bi-list-ul"></i> طلباتي</a>
        </li>

        <li class="nav-item">
            <a class="nav-link text-warning fw-bold" href="<?php echo $path_prefix; ?>pages/my_leaves.php">
                <i class="bi bi-calendar2-check"></i> إجازاتي
            </a>
        </li>
        
        <?php if(in_array($_SESSION['role'], ['super_admin', 'ceo', 'hr_manager', 'manager_first', 'manager_youth', 'maintenance_head', 'accountant'])): // أضفت المحاسب هنا للرزنامة ?>
        <li class="nav-item">
            <a class="nav-link fw-bold" style="color: #fff;" href="<?php echo $path_prefix; ?>pages/calendar.php">
                <i class="bi bi-calendar3"></i> رزنامة الموظفين
            </a>
        </li>
        <?php endif; ?>

       <?php if(in_array($_SESSION['role'], ['super_admin', 'ceo', 'purchasing', 'hr_manager', 'accountant'])): ?>
            <li class="nav-item">
                <a class="nav-link text-info fw-bold" href="<?php echo $path_prefix; ?>pages/reports.php">
                    <i class="bi bi-graph-up-arrow"></i> التقارير
                </a>
            </li>
        <?php endif; ?>
      </ul>
      
       </div>
       <div class="d-flex align-items-center">
        
        <?php
        // جلب عدد الإشعارات غير المقروءة
        $uid = $_SESSION['id'];
        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt_count->execute([$uid]);
        $notif_count = $stmt_count->fetchColumn();

        // جلب آخر 5 إشعارات
        $stmt_list = $pdo->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
        $stmt_list->execute([$uid]);
        $notifications = $stmt_list->fetchAll();
        ?>
        
        <div class="dropdown me-3 no-print">
            <a class="text-white text-decoration-none position-relative" href="#" role="button" data-bs-toggle="dropdown">
                <i class="bi bi-bell-fill fs-5"></i>
                <?php if ($notif_count > 0): ?>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.6rem;">
                        <?php echo $notif_count; ?>
                    </span>
                <?php endif; ?>
            </a>
            <ul class="dropdown-menu dropdown-menu-end shadow" style="width: 300px; max-height: 400px; overflow-y: auto;">
                <li><h6 class="dropdown-header fw-bold">الإشعارات</h6></li>
                <li><hr class="dropdown-divider"></li>
                
                <?php if (count($notifications) > 0): ?>
                    <?php foreach ($notifications as $notif): ?>
                        <li>
                            <a class="dropdown-item d-flex align-items-start p-2 <?php echo ($notif['is_read'] == 0) ? 'bg-light fw-bold' : ''; ?>" 
                               href="<?php echo $path_prefix; ?>pages/mark_read.php?id=<?php echo $notif['id']; ?>">
                                <div class="ms-2 me-auto">
                                    <div class="small"><?php echo $notif['message']; ?></div>
                                    <small class="text-muted" style="font-size: 0.7em;"><?php echo date('Y-m-d H:i', strtotime($notif['created_at'])); ?></small>
                                </div>
                                <?php if ($notif['is_read'] == 0): ?><span class="badge bg-danger rounded-circle p-1"> </span><?php endif; ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <li class="p-3 text-center text-muted small">لا توجد إشعارات جديدة</li>
                <?php endif; ?>
            </ul>
        </div>
        <div class="ms-3 dropdown">
            <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="profileDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                <?php 
                    // التحقق من وجود صورة، وإلا استخدام صورة افتراضية
                    // استخدام المسار الذكي للصورة
                    $user_pic = !empty($_SESSION['profile_pic']) ? $path_prefix . $_SESSION['profile_pic'] : $path_prefix . "assets/images/default_user.png";
                    
                    // تحديث السيشن في حال تم تغيير الصورة للتو (اختياري للتحسين)
                    if(isset($current_user['profile_pic'])) $user_pic = $path_prefix . $current_user['profile_pic'];
                ?>
                <img src="<?php echo $user_pic; ?>" alt="User" class="rounded-circle border border-white" width="32" height="32" style="object-fit: cover;">
                <div class="ms-2 d-none d-sm-block text-start">
                    <span class="d-block fw-bold" style="font-size: 0.9rem;"><?php echo $_SESSION['fullname']; ?></span>
                    <span class="d-block text-white-50" style="font-size: 0.7rem;"><?php echo ucfirst($_SESSION['role']); ?></span>
                </div>
            </a>
            <ul class="dropdown-menu dropdown-menu-end shadow small" aria-labelledby="profileDropdown">
                <li><a class="dropdown-item" href="<?php echo $path_prefix; ?>pages/profile.php"><i class="bi bi-person me-2"></i> الملف الشخصي</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item text-danger" href="<?php echo $path_prefix; ?>logout.php"><i class="bi bi-box-arrow-left me-2"></i> خروج</a></li>
            </ul>
        </div>
</nav>

<div class="container mt-4">