<?php
// auth_guard.php
require_once __DIR__ . '/session_boot.php';
require_once __DIR__ . '/config.php'; // must define $conn (PDO)

if (empty($_SESSION['alogin']) && empty($_SESSION['cname']) && empty($_SESSION['admin_id'])) {
  header('Location: login.php');
  exit;
}

// Fetch current user once and cache minimal fields in session
if (empty($_SESSION['me']) || empty($_SESSION['me']['email']) || $_SESSION['me']['email'] !== $_SESSION['alogin']) {
  $st = $conn->prepare("SELECT id, empId, username, email, userRole, userDepartment, profile_pic
                        FROM emplist WHERE email = :e LIMIT 1");
  $st->execute([':e' => $_SESSION['alogin']]);
  $me = $st->fetch(PDO::FETCH_ASSOC);
  if (!$me) {
    // (edge case) If your login stores empId in alogin, try that fallback:
    $st = $conn->prepare("SELECT id, empId, username, email, userRole, userDepartment, profile_pic
                          FROM emplist WHERE empId = :x LIMIT 1");
    $st->execute([':x' => $_SESSION['alogin']]);
    $me = $st->fetch(PDO::FETCH_ASSOC);
    if (!$me) {
      // invalid session → force logout
      header('Location: logout.php'); exit;
    }
  }
  $_SESSION['me'] = $me;
}
$me = $_SESSION['me'];  // $me is available to the page
