<?php
/**
 * Layout principal del CRM con sidebar
 */

require_once BASE_PATH . '/modules/shared/helpers.php';
if (!isLoggedIn()) {
    $appBase = get_base_path();
    header('Location: ' . $appBase . '/index.php?module=auth&action=login');
    exit;
}
?>

<?php if (!isset($page_title)) { $page_title = "CRM"; } ?>
<?php if (!isset($active)) { $active = ''; } ?>
<?php if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(__DIR__, 2)); } ?>
<?php require_once BASE_PATH . '/modules/shared/helpers.php'; ?>
<?php require_once BASE_PATH . '/database/config.php'; ?>
<?php require_once BASE_PATH . '/database/connection.php'; ?>
<?php if (!headers_sent()) { header('Content-Type: text/html; charset=UTF-8'); } ?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?> - ProFix CRM</title>
    <base href="<?php echo htmlspecialchars(get_base_path()); ?>/">
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>?v=<?php echo urlencode(date('YmdHis')); ?>">
    <link rel="stylesheet" href="/simple_crm/public/style.css">
    <script>window.APP_BASE_PATH = <?php echo json_encode(get_base_path()); ?>;</script>
    <script src="<?php echo asset('public/basepath.js'); ?>"></script>
    <script>window.__CALENDAR_USER_ID__ = <?php echo json_encode($_SESSION['user_id'] ?? 1); ?>;</script>
</head>
<body class="layout">
    <?php /* Normalizar módulo activo para el header */ $module = $_GET['module'] ?? ($active ?? ''); ?>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>

    <main class="content">
        <?php include __DIR__ . '/sidebar.php'; ?>
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        <section class="main">
            <?php
            if (isset($content)) {
                echo $content;
            } elseif (isset($content_file) && file_exists($content_file)) {
                ob_start();
                include $content_file;
                $content = ob_get_clean();
                echo $content;
            }
            ?>
        </section>
    </main>

    <footer class="footer">
        <p>© <?php echo date('Y'); ?> ProFix CRM</p>
    </footer>

    <script src="<?php echo asset('public/script.js'); ?>"></script>
    <script src="<?php echo asset('public/smooth_submit.js'); ?>"></script>
    <script src="/simple_crm/public/script.js"></script>
</body>
</html>
