<?php
declare(strict_types=1);

$shell = dirname(__DIR__, 3) . '/includes/console_shell.php';
if (!is_file($shell)) {
    throw new RuntimeException('ABOX console shell is unavailable.');
}
require_once $shell;
require_once __DIR__ . '/bootstrap.php';

function crm_page_start(string $title, string $section, string $eyebrow = 'CRM'): void
{
    $requestPath = ltrim((string)(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: ''), '/');
    $activeLinks = [
        'masters' => 'modules/crm/masters/index.php',
        'operations' => $title === 'Lead Register'
            ? 'modules/crm/operations/leads.php'
            : 'modules/crm/operations/lead-entry.php',
        'reports' => 'modules/crm/reports/index.php',
    ];
    $quotationPages = ['Generate Quotation', 'Quotation Register', 'Quotation Preview'];
    $activeLink = $section === 'reports'
        ? $activeLinks['reports']
        : ($section === 'operations' && in_array($title, $quotationPages, true)
            ? 'modules/crm/operations/leads.php'
            : (strpos($requestPath, 'modules/crm/') === 0
                ? $requestPath
                : ($activeLinks[$section] ?? 'modules/crm/operations/lead-entry.php')));

    require_login();
    require_acl('can_view', $activeLink);
    console_header($title, $activeLink);
    ?>
    <link rel="stylesheet" href="<?= crm_e(crm_url('assets/css/crm.css')) ?>">
    <div class="crm-module page-content">
        <div class="breadcrumbs">
            <a href="/dashboard.php">Dashboard</a>
            <i class="fa-solid fa-chevron-right"></i>
            <span><?= crm_e(ucfirst($section)) ?></span>
            <i class="fa-solid fa-chevron-right"></i>
            <strong><?= crm_e($title) ?></strong>
        </div>
        <div class="page-heading">
            <div>
                <h1><?= crm_e($title) ?></h1>
                <p><?= crm_e($eyebrow) ?></p>
            </div>
            <div class="heading-actions">
                <?php if ($section === 'operations' && $title === 'Lead Register'): ?>
                    <a class="button primary" href="<?= crm_e(crm_url('operations/lead-entry.php')) ?>">
                        <i class="fa-solid fa-plus"></i> New Lead
                    </a>
                <?php endif; ?>
            </div>
        </div>
    <?php
}

function crm_page_end(): void
{
    ?>
    </div>
    <script src="<?= crm_e(crm_url('assets/js/crm.js')) ?>"></script>
    <?php
    console_footer();
}
