<?php
// Mula sesi jika belum
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Sambung ke DB
include('conn.php');

// Redirect ke login jika belum login
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Ambil info pengguna dari session
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? 'Pengguna';
$user_role = $_SESSION['user_role'] ?? null;

// Optional: Refresh nama pengguna dari DB (jika perlu)
if ($conn && $user_id) {
    $stmt = $conn->prepare("SELECT NamaStaff, role, jabatan, bahagian FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($user = $result->fetch_assoc()) {
        $user_name = $user['NamaStaff'];
        $user_role = $user['role'];
        $_SESSION['user_name'] = $user_name;
        $_SESSION['user_role'] = $user_role;
        $_SESSION['jabatan'] = $user['jabatan'];
        $_SESSION['bahagian'] = $user['bahagian'];
    }
    $stmt->close();
}

// Fungsi: semak jika role sekarang sesuai
function checkRole($required_role) {
    return isset($_SESSION['user_role']) && $_SESSION['user_role'] === $required_role;
}

// Fungsi: semak jika user ada dalam senarai role
function checkRoles(array $allowed_roles) {
    return isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], $allowed_roles);
}
?>