<?php
// Módulo Calendario - Entrada principal integrada con el layout del CRM
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }

require_once BASE_PATH . '/modules/shared/helpers.php';
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Verificar permisos del usuario para acceder al Calendario
$db = getDB();
$pdo = $db->getConnection();
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        try {
            $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();
        } catch (Exception $e) {
            return false;
        }
    }
}

if (!userHasPermissionByName($pdo, 'calendar.view', $current_user_id)) {
    http_response_code(403);
    $page_title = 'Acceso denegado';
    $module = 'calendar';
    $action = 'forbidden';
    $content = '<div class="content-area"><div class="alert alert-warning">No tiene permiso para ver el módulo Calendario.</div></div>';
    include BASE_PATH . '/modules/shared/layout.php';
    return;
}

// Variables de layout
$page_title = 'Calendario';
$module = 'calendar';
$action = 'index';
$content_file = __DIR__ . '/calendar_content.php';

// Renderizar mediante layout compartido (incluye header, sidebar y estilos globales)
include BASE_PATH . '/modules/shared/layout.php';
return;
?>