<?php
$user = current_user();
$branchSwitchOptions = [];
if ($user) {
    try {
        $pdoLayout = \App\Core\Database::pdo();
        $stmtLayout = $pdoLayout->prepare(
            'SELECT b.id, b.code, b.name
             FROM user_branches ub
             INNER JOIN branches b ON b.id = ub.branch_id
             WHERE ub.user_id = ? AND b.company_id = ? AND b.is_active = 1
             ORDER BY ub.is_default DESC, b.name ASC'
        );
        $stmtLayout->execute([(int)$user['id'], (int)$user['company_id']]);
        $branchSwitchOptions = $stmtLayout->fetchAll(PDO::FETCH_ASSOC);
        if (!$branchSwitchOptions && (($user['role_code'] ?? '') === 'ADMIN')) {
            $stmtLayout = $pdoLayout->prepare('SELECT id, code, name FROM branches WHERE company_id = ? AND is_active = 1 ORDER BY name ASC');
            $stmtLayout->execute([(int)$user['company_id']]);
            $branchSwitchOptions = $stmtLayout->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable) {
        $branchSwitchOptions = [];
    }
}

$topbarRates = [
    'MANUAL_VENTA' => null,
    'BNA_BILLETE_COMPRADOR' => null,
];
if ($user) {
    try {
        $rateServiceLayout = new \App\Services\ExchangeRateService();
        foreach (array_keys($topbarRates) as $rateCodeLayout) {
            $topbarRates[$rateCodeLayout] = $rateServiceLayout->latest((int)$user['company_id'], $rateCodeLayout);
        }
    } catch (Throwable) {
        $topbarRates = [
            'MANUAL_VENTA' => null,
            'BNA_BILLETE_COMPRADOR' => null,
        ];
    }
}

$currentUri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$basePath = rtrim((string)\App\Core\Env::get('APP_BASE_PATH', ''), '/');
$currentPath = $currentUri;
if ($basePath !== '' && str_starts_with($currentPath, $basePath)) {
    $currentPath = substr($currentPath, strlen($basePath)) ?: '/';
}
$currentPath = '/' . ltrim($currentPath, '/');
$currentPath = $currentPath === '/' ? '/' : rtrim($currentPath, '/');

$isActive = static function (string|array $paths) use ($currentPath): bool {
    foreach ((array)$paths as $path) {
        $path = '/' . ltrim($path, '/');
        $path = $path === '/' ? '/' : rtrim($path, '/');
        if ($path === '/') {
            if ($currentPath === '/') {
                return true;
            }
            continue;
        }
        if ($currentPath === $path || str_starts_with($currentPath . '/', $path . '/')) {
            return true;
        }
    }
    return false;
};

$menuGroups = [
    [
        'title' => 'Ventas',
        'icon' => 'VT',
        'paths' => ['/customers', '/sales-documents', '/customer-delivery-notes', '/customer-returns'],
        'items' => [
            ['label' => 'Clientes / Cliente 360', 'url' => '/customers', 'permission' => 'clientes.ver', 'paths' => ['/customers']],
            ['label' => 'POS / documentos de venta', 'url' => '/sales-documents', 'permission' => null, 'paths' => ['/sales-documents']],
            ['label' => 'Remitos a clientes', 'url' => '/customer-delivery-notes', 'permission' => 'ventas.remitos.ver', 'paths' => ['/customer-delivery-notes']],
            ['label' => 'Devoluciones / cambios', 'url' => '/customer-returns', 'permission' => 'ventas.devoluciones.ver', 'paths' => ['/customer-returns']],
        ],
    ],
    [
        'title' => 'Compras',
        'icon' => 'CO',
        'paths' => ['/suppliers', '/purchases'],
        'items' => [
            ['label' => 'Proveedores / Proveedor 360', 'url' => '/suppliers', 'permission' => 'proveedores.ver', 'paths' => ['/suppliers']],
            ['label' => 'Panel de compras', 'url' => '/purchases', 'permission' => null, 'paths' => ['/purchases']],
            ['label' => 'Órdenes de compra', 'url' => '/purchases/orders', 'permission' => 'compras.ordenes.ver', 'paths' => ['/purchases/orders']],
            ['label' => 'Facturas y notas proveedor', 'url' => '/purchases/invoices', 'permission' => 'compras.facturas.ver', 'paths' => ['/purchases/invoices']],
            ['label' => 'Recepción / remitos proveedor', 'url' => '/purchases/delivery-notes', 'permission' => 'compras.remitos.ver', 'paths' => ['/purchases/delivery-notes']],
        ],
    ],
    [
        'title' => 'Productos',
        'icon' => 'PR',
        'paths' => ['/products', '/product-categories', '/stock', '/imports/products', '/stock/import-initial'],
        'items' => [
            ['label' => 'Productos y servicios', 'url' => '/products', 'permission' => 'productos.ver', 'paths' => ['/products']],
            ['label' => 'Categorías de productos', 'url' => '/product-categories', 'permission' => 'productos.ver', 'paths' => ['/product-categories']],
            ['label' => 'Importar categorías', 'url' => '/product-categories/import', 'permission' => 'productos.crear', 'paths' => ['/product-categories/import']],
            ['label' => 'Stock por sucursal', 'url' => '/stock', 'permission' => 'stock.saldos.ver', 'paths' => ['/stock']],
            ['label' => 'Movimientos de stock', 'url' => '/stock/movements', 'permission' => 'stock.saldos.ver', 'paths' => ['/stock/movements']],
            ['label' => 'Ajustes de stock', 'url' => '/stock/adjustments', 'permission' => 'stock.ajustes.ver', 'paths' => ['/stock/adjustments']],
            ['label' => 'Importar productos', 'url' => '/imports/products', 'permission' => 'productos.crear', 'paths' => ['/imports/products']],
            ['label' => 'Importar stock inicial', 'url' => '/stock/import-initial', 'permission' => 'stock.ajustes.crear', 'paths' => ['/stock/import-initial']],
        ],
    ],
    [
        'title' => 'Finanzas',
        'icon' => 'FN',
        'paths' => ['/finance', '/receipts', '/supplier-payments', '/cashboxes', '/finance/renditions', '/finance/treasury', '/bank-accounts', '/bank-movements', '/checks'],
        'items' => [
            ['label' => 'Panel financiero', 'url' => '/finance', 'permission' => null, 'paths' => ['/finance']],
            ['label' => 'Nuevo recibo / cobranzas', 'url' => '/receipts', 'permission' => 'clientes.recibos.ver', 'paths' => ['/receipts']],
            ['label' => 'Pagos a proveedores', 'url' => '/supplier-payments', 'permission' => 'proveedores.pagos.ver', 'paths' => ['/supplier-payments']],
            ['label' => 'Caja / movimientos', 'url' => '/cashboxes/movements', 'permission' => 'caja.ver', 'paths' => ['/cashboxes']],
            ['label' => 'Rendición y cierre del día', 'url' => '/finance/cash-closing', 'permission' => 'caja.ver', 'paths' => ['/finance/cash-closing']],
            ['label' => 'Caja Gerente / Tesorería', 'url' => '/finance/treasury', 'permission' => 'caja.gerente.ver', 'paths' => ['/finance/treasury']],
            ['label' => 'Rendiciones a Caja Gerente', 'url' => '/finance/renditions', 'permission' => 'caja.rendiciones.ver', 'paths' => ['/finance/renditions']],
            ['label' => 'Bancos', 'url' => '/bank-accounts', 'permission' => 'bancos.ver', 'paths' => ['/bank-accounts', '/bank-movements']],
            ['label' => 'Cheques / Echeqs', 'url' => '/checks', 'permission' => 'cheques.ver', 'paths' => ['/checks', '/finance/checks']],
        ],
    ],
    [
        'title' => 'Reportes',
        'icon' => 'RP',
        'paths' => ['/reports'],
        'items' => [
            ['label' => 'Panel de reportes', 'url' => '/reports', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports']],
            ['label' => 'Ventas', 'url' => '/reports/sales', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/sales']],
            ['label' => 'Cobranzas', 'url' => '/reports/collections', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/collections']],
            ['label' => 'Deuda de clientes', 'url' => '/reports/receivables', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/receivables']],
            ['label' => 'Deuda proveedores', 'url' => '/reports/supplier-debt', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/supplier-debt']],
            ['label' => 'Stock valorizado', 'url' => '/reports/stock-valuation', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/stock-valuation']],
            ['label' => 'Caja diaria', 'url' => '/reports/cash-daily', 'permission' => 'reportes.operativos.ver', 'paths' => ['/reports/cash-daily']],
        ],
    ],
    [
        'title' => 'ARCA',
        'icon' => 'AF',
        'paths' => ['/arca'],
        'items' => [
            ['label' => 'Panel ARCA', 'url' => '/arca', 'permission' => 'arca.configuracion.ver', 'paths' => ['/arca']],
            ['label' => 'Configuración ARCA', 'url' => '/arca/settings', 'permission' => 'arca.configuracion.ver', 'paths' => ['/arca/settings']],
            ['label' => 'Libro IVA ventas', 'url' => '/arca/iva-sales', 'permission' => 'arca.facturacion.ver', 'paths' => ['/arca/iva-sales']],
            ['label' => 'Libro IVA compras', 'url' => '/arca/iva-purchases', 'permission' => 'arca.facturacion.ver', 'paths' => ['/arca/iva-purchases']],
        ],
    ],
    [
        'title' => 'Configuración CRM',
        'icon' => 'CF',
        'paths' => ['/config', '/exchange-rates', '/imports'],
        'items' => [
            ['label' => 'Panel configuración', 'url' => '/config', 'permission' => 'configuracion.empresa.ver', 'paths' => ['/config']],
            ['label' => 'Empresa', 'url' => '/config/company', 'permission' => 'configuracion.empresa.ver', 'paths' => ['/config/company']],
            ['label' => 'Plantilla comprobantes', 'url' => '/config/document-template', 'permission' => 'configuracion.empresa.ver', 'paths' => ['/config/document-template', '/config/document-templates']],
            ['label' => 'Sucursales y depósitos', 'url' => '/config/branches', 'permission' => 'configuracion.sucursales.ver', 'paths' => ['/config/branches']],
            ['label' => 'Tipos de cambio', 'url' => '/exchange-rates', 'permission' => 'configuracion.tipos_cambio.ver', 'paths' => ['/exchange-rates']],
            ['label' => 'Importaciones masivas', 'url' => '/imports', 'permission' => null, 'paths' => ['/imports']],
            ['label' => 'Backups', 'url' => '/config/backup', 'permission' => 'configuracion.backup.ver', 'paths' => ['/config/backup']],
            ['label' => 'Parámetros críticos', 'url' => '/config/system', 'permission' => 'configuracion.empresa.ver', 'paths' => ['/config/system']],
            ['label' => 'Reset controlado', 'url' => '/config/reset', 'permission' => 'configuracion.reset.ver', 'paths' => ['/config/reset']],
        ],
    ],
    [
        'title' => 'Usuarios',
        'icon' => 'US',
        'paths' => ['/users'],
        'items' => [
            ['label' => 'Usuarios', 'url' => '/users', 'permission' => 'configuracion.usuarios.ver', 'paths' => ['/users']],
            ['label' => 'Roles y permisos', 'url' => '/users/roles', 'permission' => 'configuracion.roles.ver', 'paths' => ['/users/roles']],
        ],
    ],
];
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title ?? 'CRM Agro') ?></title>
    <link rel="stylesheet" href="<?= asset('css/app.css') ?>">
</head>
<body class="ui-v26 ui-compact" style="<?= e(document_template_style()) ?>">
<div class="app-shell">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-brand">
            <div class="brand-logo small">AG</div>
            <div>
                <strong>CRM Agro</strong>
                <span><?= e($user['branch_name'] ?? 'Sucursal') ?></span>
            </div>
        </div>

        <nav class="menu" aria-label="Navegación principal">
            <a href="<?= url('/') ?>" class="menu-item menu-dashboard <?= $isActive('/') ? 'active' : '' ?>">
                <span class="menu-icon">IN</span>
                <span>Inicio / Dashboard</span>
            </a>

            <?php foreach ($menuGroups as $group): ?>
                <?php
                $visibleItems = array_filter($group['items'], static function (array $item): bool {
                    return $item['permission'] === null || can((string)$item['permission']);
                });
                if (!$visibleItems) {
                    continue;
                }
                $groupOpen = $isActive($group['paths']);
                ?>
                <details class="menu-group" <?= $groupOpen ? 'open' : '' ?>>
                    <summary>
                        <span class="menu-icon"><?= e($group['icon']) ?></span>
                        <span><?= e($group['title']) ?></span>
                    </summary>
                    <div class="menu-group-items">
                        <?php foreach ($visibleItems as $item): ?>
                            <a href="<?= url($item['url']) ?>" class="menu-item <?= $isActive($item['paths']) ? 'active' : '' ?>">
                                <?= e($item['label']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </details>
            <?php endforeach; ?>
        </nav>
    </aside>

    <div class="main">
        <header class="topbar">
            <button class="hamburger" type="button" data-toggle-sidebar>☰</button>
            <div class="topbar-title">
                <strong><?= e($title ?? '') ?></strong>
                <span><?= e($user['role_name'] ?? '') ?></span>
            </div>
            <div class="userbox topbar-tools">
                <div class="top-quick-nav" aria-label="Accesos rápidos">
                    <a class="top-quick-link pos" href="<?= url('/sales-documents/create') ?>" title="Nuevo POS / documento de venta">
                        <span class="top-quick-icon">🛒</span><span>POS</span>
                    </a>
                    <a class="top-quick-link customers" href="<?= url('/customers') ?>" title="Clientes">
                        <span class="top-quick-icon">👥</span><span>Clientes</span>
                    </a>
                    <a class="top-quick-link products" href="<?= url('/products') ?>" title="Productos">
                        <span class="top-quick-icon">📦</span><span>Productos</span>
                    </a>
                </div>
                <div class="top-rates" title="Cotizaciones vigentes">
                    <a class="top-rate-pill internal" href="<?= url('/exchange-rates') ?>">
                        <span>Venta</span>
                        <strong><?= $topbarRates['MANUAL_VENTA'] ? money_ars($topbarRates['MANUAL_VENTA']['rate']) : 'Sin TC' ?></strong>
                    </a>
                    <a class="top-rate-pill bna" href="<?= url('/exchange-rates') ?>">
                        <span>BNA comp.</span>
                        <strong><?= $topbarRates['BNA_BILLETE_COMPRADOR'] ? money_ars($topbarRates['BNA_BILLETE_COMPRADOR']['rate']) : 'Sin TC' ?></strong>
                    </a>
                </div>
                <?php if (count($branchSwitchOptions) > 1): ?>
                    <form class="branch-switch-form" action="<?= url('/config/switch-branch') ?>" method="post">
                        <?= csrf_field() ?>
                        <input type="hidden" name="redirect_to" value="<?= e($currentPath) ?>">
                        <label class="sr-only" for="topbar_branch_id">Sucursal activa</label>
                        <select id="topbar_branch_id" name="branch_id" onchange="this.form.submit()">
                            <?php foreach ($branchSwitchOptions as $branchOption): ?>
                                <option value="<?= (int)$branchOption['id'] ?>" <?= ((int)($user['branch_id'] ?? 0) === (int)$branchOption['id']) ? 'selected' : '' ?>>
                                    <?= e(($branchOption['code'] ?? '') . ' - ' . $branchOption['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                <?php endif; ?>
                <span><?= e($user['full_name'] ?? '') ?></span>
                <form action="<?= url('/logout') ?>" method="post">
                    <?= csrf_field() ?>
                    <button class="link-button" type="submit">Salir</button>
                </form>
            </div>
        </header>

        <main class="content">
            <?php if ($msg = flash('success')): ?>
                <div class="alert success"><?= e($msg) ?></div>
            <?php endif; ?>
            <?php if ($msg = flash('error')): ?>
                <div class="alert error"><?= e($msg) ?></div>
            <?php endif; ?>

            <?= $content ?>
        </main>
    </div>
</div>
<script src="<?= asset('js/app.js') ?>"></script>
</body>
</html>
