<?php

require_once __DIR__.'/error_handler.php';

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

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/tenant.php';

/* =====================================================
   EDM CORE — AUTH & PERMISSION SYSTEM (FIXED)
   - Works from nested folders (/public/operations/...)
   - Uses a dynamic BASE path to prevent wrong redirects
===================================================== */

function app_base_path(): string {
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    $pos = strpos($script, '/public/');
    if ($pos === false) {
        return '/core/public';
    }
    return substr($script, 0, $pos) . '/public';
}

function redirect_to(string $path): void {
    if ($path === '' || $path[0] !== '/') {
        $path = '/' . ltrim($path, '/');
    }
    header("Location: " . $path);
    exit;
}

function requireLogin(): void {
    if (!isset($_SESSION['user_id'])) {
        redirect_to(app_base_path() . "/login.php");
    }

    requireTenant(); // <-- add this line
}

function hasPermission(string $permissionCode): bool {
    requireLogin();

    // SUPER ADMIN bypass (by role name, not id)
    if (isset($_SESSION['role_name']) && $_SESSION['role_name'] === 'SUPER_ADMIN') {
        return true;
    }

    global $pdo;

    if (!isset($_SESSION['role_id'])) {
        return false;
    }

    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM role_permissions rp
        JOIN permissions p ON rp.permission_id = p.id
        WHERE rp.role_id = ?
          AND p.code = ?
    ");

    $stmt->execute([
        (int)$_SESSION['role_id'],
        $permissionCode
    ]);

    return ((int)$stmt->fetchColumn()) > 0;
}

function requirePermission(string $permissionCode): void {
    requireLogin();

    if (!hasPermission($permissionCode)) {
        redirect_to(app_base_path() . "/forbidden.php?perm=" . urlencode($permissionCode));
    }
}

/* ===============================
   TENANT HELPER
================================= */

function tenant_id(): int
{
    return $_SESSION['company_id'] ?? 0;
}