<?php
// Módulo Integraciones - Página principal (Voiso)
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Evitar redeclarar isLoggedIn si ya fue definida por el router principal
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() { return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
}
if (!isLoggedIn()) { header('Location: /index.php?module=auth&action=login'); exit; }

// Helpers de permisos
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}

$db = getDB();
$pdo = $db->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);

// Verificar permiso de acceso al módulo Integraciones
if (!userHasPermissionByName($pdo, 'integrations.view', $current_user_id)) {
    http_response_code(403);
    echo 'No tienes permiso para ver Integraciones.';
    exit;
}

// Configurar layout corporativo
$page_title = 'Integraciones';
$current_module = 'integrations';
$current_action = 'index';
$content_file = BASE_PATH . '/modules/integrations/integrations_content.php';
include BASE_PATH . '/modules/shared/layout.php';
return;
?>