<?php
/**
 * Enterprise HRM ERP System - Authentication Check
 * Include this file to protect pages that require login
 */

// Prevent direct access
if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    $sessionTimeout = getSetting('SESSION_TIMEOUT', SESSION_LIFETIME);
    ini_set('session.gc_maxlifetime', $sessionTimeout);
    session_name(SESSION_NAME);
    session_start();
    
    // Check session timeout
    if (isset($_SESSION['last_activity']) && 
        (time() - $_SESSION['last_activity']) > $sessionTimeout) {
        session_destroy();
        session_start();
    }
    
    $_SESSION['last_activity'] = time();
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header('Location: ' . BASE_URL . '/auth/login.php');
    exit;
}

// Ensure site_id is set (use default if not)
if (!isset($_SESSION['site_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT site_id FROM sites WHERE site_id = 1 LIMIT 1");
        $stmt->execute();
        $site = $stmt->fetch();
        $_SESSION['site_id'] = $site['site_id'] ?? 1;
    } catch (Exception $e) {
        $_SESSION['site_id'] = 1; // Fallback to default
    }
}

// Set timezone from settings
$timezone = getSetting('SYSTEM_TIMEZONE', 'UTC');
date_default_timezone_set($timezone);

