<?php

if(session_status() == PHP_SESSION_NONE)
{
    session_start();
}

if(!isset($_SESSION['user_id']))
{
    require_once __DIR__.'/../config/app.php';

header(
"Location: ".BASE_URL."login.php"
);
    exit();
}

require_once __DIR__ . '/../config/db.php';

$authUserId = (int)$_SESSION['user_id'];
$authStatement = mysqli_prepare($conn, 'SELECT id, email, fullname, role, zone_name, status FROM users WHERE id=? LIMIT 1');
mysqli_stmt_bind_param($authStatement, 'i', $authUserId);
mysqli_stmt_execute($authStatement);
$authUser = mysqli_fetch_assoc(mysqli_stmt_get_result($authStatement));
mysqli_stmt_close($authStatement);

if (!$authUser || ($authUser['status'] ?? 'Active') !== 'Active' || !in_array($authUser['role'], ['admin', 'zonal_director', 'user'], true))
{
    //session_unset();
    //session_destroy();
    session_regenerate_id(true);
    require_once __DIR__.'/../config/app.php';
    header('Location: ' . BASE_URL . 'login.php');
    exit();
}

$_SESSION['email'] = $authUser['email'];
$_SESSION['fullname'] = $authUser['fullname'];
$_SESSION['role'] = $authUser['role'];
$_SESSION['zone_name'] = $authUser['zone_name'];
