<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!defined('BASE_URL')) {
    require_once __DIR__ . '/config.php';
}

if (!isset($_SESSION['user_id'])) {
    header("Location: " . BASE_URL . "/login.php");
    exit;
}

// Force re-login after 30 minutes of inactivity
$timeout = 1800;
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
    session_unset();
    session_destroy();
    header("Location: " . BASE_URL . "/login.php?timeout=1");
    exit;
}
$_SESSION['last_activity'] = time();

// Ensure DB connection is available (auth.php may be included before db.php in some pages)
if (!isset($conn)) {
    require_once __DIR__ . '/../db.php';
}

require_once __DIR__ . '/permissions.php';

// ── Company access resolution ────────────────────────────────────────────────
global $cid;
$cid = (int)($_SESSION['active_company_id'] ?? 0);

if ($cid === 0) {
    $role = $_SESSION['user_role'] ?? '';
    $uid  = (int)$_SESSION['user_id'];

    if ($role === 'admin') {
        // Admin: auto-assign first company
        $r = $conn->query("SELECT id FROM company_master ORDER BY id ASC LIMIT 1");
        if ($r && $r->num_rows > 0) {
            $cid = (int)$r->fetch_row()[0];
            $_SESSION['active_company_id'] = $cid;
        }
    } else {
        // Staff / master_staff: check user_companies assignments
        $r = $conn->query("SELECT company_id FROM user_companies WHERE user_id = $uid ORDER BY company_id ASC");
        $companies = [];
        if ($r) {
            while ($row = $r->fetch_row()) {
                $companies[] = (int)$row[0];
            }
        }

        if (count($companies) === 0) {
            session_unset();
            session_destroy();
            header("Location: " . BASE_URL . "/login.php?no_company=1");
            exit;
        } elseif (count($companies) === 1 || $role === 'master_staff') {
            // master_staff: always auto-assign first company (dashboard shows all companies anyway)
            $cid = $companies[0];
            $_SESSION['active_company_id'] = $cid;
        } else {
            // Multiple companies — let user pick (avoid redirect loop if already on company_select)
            if (strpos($_SERVER['PHP_SELF'] ?? '', 'company_select') === false) {
                header("Location: " . BASE_URL . "/company_select.php");
                exit;
            }
        }
    }
}

// ── Load permissions into session (once per session, or after company switch) ─
if (!array_key_exists('permissions', $_SESSION) && $cid > 0) {
    loadPermissions($conn);
}
