<?php
use App\Core\Csrf;

$user = auth_user();
$currentPath = '/' . trim(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/', '/');
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
if ($scriptDir !== '/' && str_starts_with($currentPath, $scriptDir)) {
    $currentPath = '/' . trim(substr($currentPath, strlen($scriptDir)), '/');
}
$successToast = flash('success');
$errorToast = flash('error');
$isActive = static function (string $path) use ($currentPath): string {
    return $currentPath === $path || ($path !== '/' && str_starts_with($currentPath, rtrim($path, '/') . '/')) ? ' class="active" aria-current="page"' : '';
};
$pageIcon = bqp_icon_for_path($currentPath);
$pageDescriptions = [
    '/dashboard' => 'Your business performance and priorities at a glance.',
    '/sales' => 'Move opportunities forward and keep every follow-up visible.',
    '/projects' => 'Deliver client work on time and track progress in one place.',
    '/clients' => 'Manage relationships, contacts and customer history.',
    '/products' => 'Maintain the catalogue behind quotes, invoices and orders.',
    '/quotations' => 'Create compelling proposals and turn approvals into revenue.',
    '/invoices' => 'Track billing, collections and payment status.',
    '/marketing' => 'Plan, create and publish campaigns that grow your pipeline.',
    '/reports' => 'Understand performance and make confident decisions.',
    '/support/tickets' => 'Review support requests, reply to customers and keep every case moving.',
];
$pageDescription = 'Manage your business clearly and move work forward.';
foreach ($pageDescriptions as $path => $description) {
    if ($currentPath === $path || str_starts_with($currentPath, $path . '/')) { $pageDescription = $description; break; }
}
?>
<!doctype html>
<html lang="en" data-service-worker="<?= asset('service-worker.js') ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title ?? 'Dashboard') ?> | <?= e(config('app.name')) ?></title>
    <link rel="icon" type="image/svg+xml" href="<?= asset('favicon.svg') ?>">
    <link rel="shortcut icon" href="<?= asset('favicon.svg') ?>">
    <link rel="manifest" href="<?= asset('manifest.webmanifest') ?>">
    <meta name="theme-color" content="#173b65">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <?= vite_assets() ?>
    <script>
        (() => {
            const preference = localStorage.getItem('bq-theme') || 'system';
            const theme = preference === 'system' ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') : preference;
            document.documentElement.dataset.bsTheme = theme;
            document.documentElement.dataset.themePreference = preference;
        })();
    </script>
</head>
<body>
<a class="skip-link" href="#main-content">Skip to main content</a>
<div class="app-shell">
    <aside class="sidebar" id="app-sidebar">
        <div class="d-flex align-items-center gap-2 mb-4">
            <div class="brand-mark fw-bold">BQ</div>
            <div>
                <div class="fw-bold text-white">BizQuote Pro</div>
                <small class="text-secondary">Modern Business SaaS</small>
            </div>
        </div>
        <nav class="sidebar-nav" aria-label="Primary navigation">
            <span class="sidebar-section-label">Overview</span>
            <a<?= $isActive('/dashboard') ?> href="<?= url('/dashboard') ?>"><?= bqp_icon('dashboard') ?><span>Dashboard</span></a>
            <span class="sidebar-section-label">Sales</span>
            <a<?= $isActive('/sales') ?> href="<?= url('/sales') ?>"><?= bqp_icon('reports') ?><span>Sales Pipeline</span></a>
            <a<?= $isActive('/clients') ?> href="<?= url('/clients') ?>"><?= bqp_icon('clients') ?><span>Clients</span></a>
            <a<?= $isActive('/quotations') ?> href="<?= url('/quotations') ?>"><?= bqp_icon('quotations') ?><span>Quotations</span></a>
            <span class="sidebar-section-label">Work</span>
            <a<?= $isActive('/projects') ?> href="<?= url('/projects') ?>"><?= bqp_icon('recurring') ?><span>Projects & Jobs</span></a>
            <a<?= $isActive('/products') ?> href="<?= url('/products') ?>"><?= bqp_icon('products') ?><span>Products & Services</span></a>
            <a<?= $isActive('/commerce') ?> href="<?= url('/commerce') ?>"><?= bqp_icon('products') ?><span>Inventory & Orders</span></a>
            <a<?= $isActive('/vendors') ?> href="<?= url('/vendors') ?>"><?= bqp_icon('vendors') ?><span>Vendors</span></a>
            <span class="sidebar-section-label">Finance</span>
            <a<?= $isActive('/invoices') ?> href="<?= url('/invoices') ?>"><?= bqp_icon('invoices') ?><span>Invoices</span></a>
            <a<?= $isActive('/recurring-invoices') ?> href="<?= url('/recurring-invoices') ?>"><?= bqp_icon('recurring') ?><span>Recurring</span></a>
            <a<?= $isActive('/expenses') ?> href="<?= url('/expenses') ?>"><?= bqp_icon('expenses') ?><span>Expenses</span></a>
            <a<?= $isActive('/accounting') ?> href="<?= url('/accounting') ?>"><?= bqp_icon('reports') ?><span>Accounting & Bank</span></a>
            <a<?= $isActive('/reports') ?> href="<?= url('/reports') ?>"><?= bqp_icon('reports') ?><span>Reports</span></a>
            <span class="sidebar-section-label">Growth</span>
            <a<?= $currentPath === '/marketing' ? ' class="active" aria-current="page"' : '' ?> href="<?= url('/marketing') ?>"><?= bqp_icon('marketing') ?><span>AI Marketing</span></a>
            <a class="sidebar-sub-link<?= $currentPath === '/marketing/activity' ? ' active' : '' ?>" href="<?= url('/marketing/activity') ?>"><?= bqp_icon('marketing') ?><span>Marketing Activity</span></a>
            <span class="sidebar-section-label">Administration</span>
            <a<?= $isActive('/team') ?> href="<?= url('/team') ?>"><?= bqp_icon('clients') ?><span>Team</span></a>
            <a<?= $isActive('/settings/company') ?> href="<?= url('/settings/company') ?>"><?= bqp_icon('settings') ?><span>Company</span></a>
            <a<?= $isActive('/settings/workflows') ?> href="<?= url('/settings/workflows') ?>"><?= bqp_icon('settings') ?><span>Automations</span></a>
            <a<?= $isActive('/settings/proposals') ?> href="<?= url('/settings/proposals') ?>"><?= bqp_icon('quotations') ?><span>Proposal Templates</span></a>
            <a<?= $isActive('/settings/payments') ?> href="<?= url('/settings/payments') ?>"><?= bqp_icon('money') ?><span>Payment Methods</span></a>
            <a<?= $isActive('/settings/integrations') ?> href="<?= url('/settings/integrations') ?>"><?= bqp_icon('settings') ?><span>API & Webhooks</span></a>
            <a<?= $isActive('/settings/subscription-plans') ?> href="<?= url('/settings/subscription-plans') ?>"><?= bqp_icon('money') ?><span>Plan Setup</span></a>
            <a<?= $isActive('/settings/letterhead') ?> href="<?= url('/settings/letterhead') ?>"><?= bqp_icon('settings') ?><span>Letterhead</span></a>
            <a<?= $isActive('/settings/production') ?> href="<?= url('/settings/production') ?>"><?= bqp_icon('settings') ?><span>Production</span></a>
            <span class="sidebar-section-label">Account</span>
            <?php if (in_array((string) ($user['role'] ?? ''), ['super_admin', 'owner', 'admin'], true)): ?>
                <a<?= $isActive('/support/tickets') ?> href="<?= url('/support/tickets') ?>"><?= bqp_icon('assistant') ?><span>Support Tickets</span></a>
            <?php endif; ?>
            <a<?= $currentPath === '/support' ? ' class="active" aria-current="page"' : '' ?> href="<?= url('/support') ?>"><?= bqp_icon('assistant') ?><span>Contact Support</span></a>
            <a<?= $currentPath === '/billing' ? ' class="active" aria-current="page"' : '' ?> href="<?= url('/billing') ?>"><?= bqp_icon('money') ?><span>Billing</span></a>
            <a class="sidebar-sub-link<?= $currentPath === '/billing/plans' ? ' active' : '' ?>" href="<?= url('/billing/plans') ?>"><?= bqp_icon('money') ?><span>Subscription Plans</span></a>
            <a<?= $isActive('/usage/ai') ?> href="<?= url('/usage/ai') ?>"><?= bqp_icon('reports') ?><span>AI Usage</span></a>
        </nav>
    </aside>
    <button class="sidebar-backdrop" type="button" data-sidebar-close aria-label="Close navigation" hidden></button>
    <main class="main" id="main-content" tabindex="-1">
        <div class="topbar d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-3 min-w-0">
                <button class="btn btn-outline-secondary sidebar-toggle" type="button" data-sidebar-toggle aria-controls="app-sidebar" aria-expanded="false" aria-label="Open navigation"><?= bqp_icon('menu') ?></button>
                <div class="d-flex align-items-center gap-3 min-w-0">
                    <span class="page-icon"><?= bqp_icon($pageIcon) ?></span>
                    <div class="min-w-0">
                        <h1 class="h4 mb-0"><?= e($title ?? 'Dashboard') ?></h1>
                        <small class="text-muted page-description"><?= e($pageDescription) ?></small>
                    </div>
                </div>
            </div>
            <div class="topbar-actions d-flex align-items-center gap-2">
                <button class="btn btn-sm btn-outline-secondary topbar-search" type="button" data-command-open aria-label="Search and navigate"><span aria-hidden="true">⌕</span><span>Search</span><kbd>Ctrl K</kbd></button>
                <button class="btn btn-sm btn-primary" type="button" popovertarget="quickCreateMenu">+ Create</button>
                <div class="quick-create-popover" id="quickCreateMenu" popover>
                    <strong>Quick create</strong>
                    <a href="<?= url('/clients#clientName') ?>">New client</a>
                    <a href="<?= url('/quotations/create') ?>">New quotation</a>
                    <a href="<?= url('/invoices') ?>">View invoices</a>
                    <a href="<?= url('/projects#projectName') ?>">New project</a>
                </div>
                <button class="btn btn-sm btn-outline-secondary theme-toggle" type="button" data-theme-toggle aria-label="Change colour theme"><span aria-hidden="true">◐</span><span data-theme-label>System</span></button>
                <span class="small text-muted user-name"><?= e($user['name'] ?? '') ?></span>
                <form method="post" action="<?= url('/logout') ?>">
                    <?= Csrf::input() ?>
                    <button class="btn btn-sm btn-outline-danger" aria-label="Log out"><?= bqp_icon('logout', 'bqp-icon-sm') ?><span class="logout-label">Logout</span></button>
                </form>
            </div>
        </div>
        <?= $content ?>
        <?php $footerTheme = 'light'; require BASE_PATH . '/resources/views/partials/site-footer.php'; ?>
    </main>
</div>
<dialog class="command-dialog" data-command-dialog aria-labelledby="command-title">
    <div class="command-header">
        <div>
            <h2 class="h5 mb-1" id="command-title">Where would you like to go?</h2>
            <p class="small text-muted mb-0">Search pages and common actions.</p>
        </div>
        <button class="btn-close" type="button" data-command-close aria-label="Close search"></button>
    </div>
    <label class="visually-hidden" for="commandSearch">Search navigation</label>
    <input class="form-control form-control-lg" id="commandSearch" type="search" placeholder="Type to search…" autocomplete="off" data-command-search>
    <nav class="command-results" aria-label="Search results" data-command-results>
        <a href="<?= url('/sales') ?>">Sales Pipeline <small>Sales</small></a>
        <a href="<?= url('/clients') ?>">Clients <small>Sales</small></a>
        <a href="<?= url('/quotations') ?>">Quotations <small>Sales</small></a>
        <a href="<?= url('/invoices') ?>">Invoices <small>Finance</small></a>
        <a href="<?= url('/projects') ?>">Projects & Jobs <small>Work</small></a>
        <a href="<?= url('/products') ?>">Products & Services <small>Work</small></a>
        <a href="<?= url('/marketing') ?>">AI Marketing <small>Growth</small></a>
        <a href="<?= url('/reports') ?>">Reports <small>Finance</small></a>
        <a href="<?= url('/settings/company') ?>">Company Settings <small>Administration</small></a>
    </nav>
    <p class="command-empty" data-command-empty hidden>No matching pages found.</p>
</dialog>
<?php require BASE_PATH . '/resources/views/partials/progress-overlay.php'; ?>
<?php if ($successToast || $errorToast): ?>
    <div class="bqp-toast-container toast-container">
        <?php if ($successToast): ?>
            <div class="toast bqp-toast text-bg-success border-0" role="status" aria-live="polite" aria-atomic="true" data-bs-delay="4200">
                <div class="d-flex">
                    <div class="toast-body"><?= e($successToast) ?></div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        <?php endif; ?>
        <?php if ($errorToast): ?>
            <div class="toast bqp-toast text-bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="6500">
                <div class="d-flex">
                    <div class="toast-body"><?= e($errorToast) ?></div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        <?php endif; ?>
    </div>
<?php endif; ?>
<div class="modal fade" id="bqpConfirmModal" tabindex="-1" aria-labelledby="bqpConfirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title h5" id="bqpConfirmModalLabel">Confirm Action</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="mb-0" data-confirm-modal-message>Are you sure?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" data-confirm-modal-submit>Delete</button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php if ($currentPath === '/dashboard'): ?>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<?php endif; ?>
</body>
</html>
