<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once '../../services/costs/CostAccess.php';

require_login();
if (!cost_can('costs.view')) {
    http_response_code(403);
    die('No tienes permisos para acceder al módulo de costos.');
}

$page_title = 'Costos de gestión';
$initialPeriod = isset($_GET['period']) && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', (string)$_GET['period']) ? (string)$_GET['period'] : date('Y-m');

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main" id="costsMain" data-spa-module="costs:management">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section class="content costs-shell">
        <header class="page-header costs-header">
            <div class="page-header-content">
                <span class="label">FINANZAS · FASE 1</span>
                <h1>Costos de gestión</h1>
                <p>Control mensual en neto, recurrencias, costo empresa y asignación por centros.</p>
            </div>
            <div class="costs-header-actions">
                <?php if (cost_can('costs.product.view')): ?><a class="btn btn-outline" href="/modules/costs/products.php"><i data-lucide="package-search"></i><span>Costeo productos</span></a><?php endif; ?>
                <label class="cost-period-control"><span class="badge cost-period-status" id="periodStatusBadge">Cargando</span><input class="input" id="costPeriod" type="month" value="<?php echo safe_text($initialPeriod); ?>" aria-label="Período de costos"></label>
                <details class="cost-actions-menu" id="costActionsMenu" data-close-outside>
                    <summary class="btn btn-outline"><i data-lucide="ellipsis-vertical"></i><span>Acciones</span></summary>
                    <div class="cost-actions-panel">
                        <button type="button" id="syncDteBtn"><i data-lucide="refresh-cw"></i><span>Sincronizar DTE del mes</span></button>
                        <button type="button" id="generateRecurringBtn"><i data-lucide="calendar-sync"></i><span>Generar recurrencias</span></button>
                        <button type="button" id="periodCloseBtn"><i data-lucide="lock"></i><span>Cerrar período</span></button>
                    </div>
                </details>
                <button class="btn btn-primary" type="button" id="newCostBtn"><i data-lucide="plus"></i><span>Nuevo costo</span></button>
            </div>
        </header>

        <div class="cost-notice" id="costNotice" hidden></div>

        <nav class="cost-tabs" aria-label="Secciones de costos">
            <button class="is-active" type="button" data-cost-tab="overview"><i data-lucide="layout-dashboard"></i><span>Resumen</span></button>
            <button type="button" data-cost-tab="entries"><i data-lucide="list-checks"></i><span>Movimientos</span></button>
            <button type="button" data-cost-tab="recurring"><i data-lucide="repeat-2"></i><span>Recurrencias</span></button>
            <button type="button" data-cost-tab="categories"><i data-lucide="tags"></i><span>Categorías</span></button>
            <button type="button" data-cost-tab="payroll" id="payrollTabButton"><i data-lucide="shield-user"></i><span>Remuneraciones</span></button>
        </nav>

        <section class="cost-tab-panel is-active" data-cost-panel="overview">
            <div class="cost-kpis" id="costKpis"></div>
            <div class="cost-analysis-grid">
                <article class="card cost-analysis-card"><header><div><span class="label">COMPOSICIÓN</span><h3>Por categoría</h3></div></header><div id="costByCategory" class="cost-bars"></div></article>
                <article class="card cost-analysis-card"><header><div><span class="label">ESTRUCTURA</span><h3>Fijo, variable y mixto</h3></div></header><div id="costByNature" class="cost-bars"></div></article>
                <article class="card cost-analysis-card"><header><div><span class="label">ASIGNACIÓN</span><h3>Por centro de costo</h3></div></header><div id="costByCenter" class="cost-bars"></div></article>
            </div>
            <article class="card cost-guidance-card">
                <i data-lucide="info"></i>
                <div><strong>Criterio de gestión</strong><p>Los DTE con IVA recuperable aportan su neto al costo. Si el IVA es no recuperable, el costo de gestión corresponde al total bruto. El módulo conserva neto, IVA y bruto para trazabilidad.</p></div>
            </article>
        </section>

        <section class="cost-tab-panel" data-cost-panel="entries">
            <section class="card cost-table-card">
                <header class="cost-card-header">
                    <div><h3>Movimientos del período</h3><p id="entriesSubtitle">Costos manuales y vinculados.</p></div>
                    <div class="cost-table-filters"><input class="input" id="entrySearch" type="search" placeholder="Buscar descripción o proveedor"><select class="select" id="entryStatusFilter"><option value="">Todos los estados</option><option value="draft">Borrador</option><option value="approved">Aprobado</option><option value="paid">Pagado</option><option value="void">Anulado</option></select></div>
                </header>
                <div class="cost-table-scroll"><table class="cost-table"><thead><tr><th>Fecha / fuente</th><th>Descripción</th><th>Categoría</th><th>Centro</th><th>Estado</th><th class="number">Costo gestión</th><th></th></tr></thead><tbody id="entriesBody"></tbody></table></div>
            </section>
        </section>

        <section class="cost-tab-panel" data-cost-panel="recurring">
            <section class="card cost-table-card">
                <header class="cost-card-header"><div><h3>Costos recurrentes</h3><p>Arriendos, consumos, servicios y compromisos periódicos.</p></div><button class="btn btn-primary" type="button" id="newRecurringBtn"><i data-lucide="plus"></i><span>Nueva recurrencia</span></button></header>
                <div class="cost-table-scroll"><table class="cost-table"><thead><tr><th>Regla</th><th>Categoría</th><th>Frecuencia</th><th>Vigencia</th><th class="number">Costo gestión</th><th>Estado</th><th></th></tr></thead><tbody id="recurringBody"></tbody></table></div>
            </section>
        </section>

        <section class="cost-tab-panel" data-cost-panel="categories">
            <section class="card cost-table-card">
                <header class="cost-card-header"><div><h3>Catálogo de costos</h3><p>Naturaleza, tratamiento de IVA y actividad de caja.</p></div><button class="btn btn-primary" type="button" id="newCategoryBtn"><i data-lucide="plus"></i><span>Nueva categoría</span></button></header>
                <div class="cost-table-scroll"><table class="cost-table"><thead><tr><th>Código / categoría</th><th>Naturaleza</th><th>Grupo</th><th>IVA</th><th>Actividad caja</th><th>Centro predeterminado</th><th>Estado</th><th></th></tr></thead><tbody id="categoriesBody"></tbody></table></div>
            </section>
        </section>

        <section class="cost-tab-panel" data-cost-panel="payroll">
            <section class="card payroll-privacy-card"><i data-lucide="shield-check"></i><div><strong>Información protegida</strong><p>Este MVP registra costo empresa para gestión. No reemplaza liquidaciones legales, Previred ni datos bancarios.</p></div></section>
            <section class="card cost-table-card">
                <header class="cost-card-header"><div><h3>Remuneraciones y costo empresa</h3><p id="payrollSubtitle">Acceso restringido por usuario.</p></div><button class="btn btn-primary" type="button" id="newPayrollBtn"><i data-lucide="plus"></i><span>Nuevo registro</span></button></header>
                <div class="cost-table-scroll"><table class="cost-table"><thead><tr><th>Código / persona</th><th>Cargo</th><th>Tipo</th><th>Centro</th><th>Pago</th><th class="number">Costo empresa</th><th></th></tr></thead><tbody id="payrollBody"></tbody></table></div>
            </section>
        </section>
    </section>

    <div class="cost-modal-backdrop" id="entryModal" aria-hidden="true"><div class="cost-modal-box" role="dialog" aria-modal="true" aria-labelledby="entryModalTitle">
        <header><div><span class="label">MOVIMIENTO</span><h2 id="entryModalTitle">Nuevo costo</h2></div><button type="button" class="btn btn-outline cost-modal-close" data-close-modal="entryModal"><i data-lucide="x"></i></button></header>
        <form id="entryForm"><input type="hidden" name="action" value="save_entry"><input type="hidden" name="id" id="entryId"><input type="hidden" name="allocations_json" id="entryAllocationsJson">
            <div class="cost-form-grid">
                <label class="wide"><span>Descripción</span><input class="input" name="description" id="entryDescription" maxlength="255" required></label>
                <label><span>Fecha</span><input class="input" type="date" name="entry_date" id="entryDate" required></label>
                <label><span>Vencimiento</span><input class="input" type="date" name="due_date" id="entryDueDate"></label>
                <label><span>Categoría</span><select class="select" name="category_id" id="entryCategory" required></select></label>
                <label><span>Proveedor</span><select class="select" name="supplier_id" id="entrySupplier"></select></label>
                <label><span>Tratamiento IVA</span><select class="select" name="iva_treatment" id="entryIva"><option value="recoverable">Recuperable · costo neto</option><option value="nonrecoverable">No recuperable · costo bruto</option><option value="no_iva">Sin IVA</option></select></label>
                <label><span>Estado</span><select class="select" name="status" id="entryStatus"><option value="draft">Borrador</option><option value="approved">Aprobado</option><option value="paid">Pagado</option></select></label>
                <label><span>Neto</span><input class="input money-field" type="number" min="0" step="0.01" name="net_amount" id="entryNet" required></label>
                <label><span>IVA</span><input class="input money-field" type="number" min="0" step="0.01" name="tax_amount" id="entryTax" value="0"></label>
                <label><span>Total bruto</span><input class="input money-field" type="number" min="0" step="0.01" name="gross_amount" id="entryGross" required></label>
                <label><span>Fecha de pago</span><input class="input" type="date" name="payment_date" id="entryPaymentDate"></label>
                <label class="wide"><span>Notas</span><textarea class="input" name="notes" id="entryNotes" rows="2"></textarea></label>
            </div>
            <section class="allocation-editor"><div class="allocation-heading"><div><strong>Asignación por centros</strong><small>La suma debe ser 100%. La política central propone un centro cuando no hay asignación manual.</small><small id="entryCenterSuggestion" class="allocation-suggestion"></small></div><button class="btn btn-outline btn-sm" type="button" id="addAllocationBtn"><i data-lucide="plus"></i><span>Agregar</span></button></div><div id="allocationRows"></div><div class="allocation-total">Total asignado <strong id="allocationTotal">0%</strong></div></section>
        </form>
        <footer><button class="btn btn-outline" type="button" data-close-modal="entryModal">Cancelar</button><button class="btn btn-primary" type="submit" form="entryForm"><i data-lucide="save"></i><span>Guardar costo</span></button></footer>
    </div></div>

    <div class="cost-modal-backdrop" id="categoryModal" aria-hidden="true"><div class="cost-modal-box compact" role="dialog" aria-modal="true" aria-labelledby="categoryModalTitle">
        <header><div><span class="label">CATÁLOGO</span><h2 id="categoryModalTitle">Nueva categoría</h2></div><button type="button" class="btn btn-outline cost-modal-close" data-close-modal="categoryModal"><i data-lucide="x"></i></button></header>
        <form id="categoryForm"><input type="hidden" name="action" value="save_category"><input type="hidden" name="id" id="categoryId"><div class="cost-form-grid">
            <label><span>Código</span><input class="input" name="category_code" id="categoryCode" maxlength="30" required></label><label><span>Nombre</span><input class="input" name="category_name" id="categoryName" required></label>
            <label><span>Naturaleza</span><select class="select" name="nature" id="categoryNature"><option value="fixed">Fijo</option><option value="variable">Variable</option><option value="mixed">Mixto</option></select></label><label><span>Grupo</span><select class="select" name="category_group" id="categoryGroup"></select></label>
            <label><span>IVA predeterminado</span><select class="select" name="default_iva_treatment" id="categoryIva"><option value="recoverable">Recuperable</option><option value="nonrecoverable">No recuperable</option><option value="no_iva">Sin IVA</option></select></label><label><span>Actividad de caja</span><select class="select" name="cash_activity" id="categoryCash"><option value="operations">Operación</option><option value="investment">Inversión</option><option value="financing">Financiamiento</option></select></label>
            <label><span>Centro predeterminado</span><select class="select" name="default_finance_center_id" id="categoryCenter"></select></label><label><span>Estado</span><select class="select" name="is_active" id="categoryActive"><option value="1">Activa</option><option value="0">Inactiva</option></select></label>
            <label class="wide"><span>Descripción</span><textarea class="input" name="description" id="categoryDescription" rows="2"></textarea></label>
        </div></form><footer><button class="btn btn-outline" type="button" data-close-modal="categoryModal">Cancelar</button><button class="btn btn-primary" type="submit" form="categoryForm"><i data-lucide="save"></i><span>Guardar categoría</span></button></footer>
    </div></div>

    <div class="cost-modal-backdrop" id="recurringModal" aria-hidden="true"><div class="cost-modal-box" role="dialog" aria-modal="true" aria-labelledby="recurringModalTitle">
        <header><div><span class="label">RECURRENCIA</span><h2 id="recurringModalTitle">Nueva recurrencia</h2></div><button type="button" class="btn btn-outline cost-modal-close" data-close-modal="recurringModal"><i data-lucide="x"></i></button></header>
        <form id="recurringForm"><input type="hidden" name="action" value="save_recurring"><input type="hidden" name="id" id="recurringId"><div class="cost-form-grid">
            <label><span>Nombre de la regla</span><input class="input" name="rule_name" id="recurringName" required></label><label><span>Descripción del costo</span><input class="input" name="description" id="recurringDescription" required></label>
            <label><span>Categoría</span><select class="select" name="category_id" id="recurringCategory" required></select></label><label><span>Proveedor</span><select class="select" name="supplier_id" id="recurringSupplier"></select></label>
            <label><span>Centro</span><select class="select" name="finance_center_id" id="recurringCenter"></select></label><label><span>IVA</span><select class="select" name="iva_treatment" id="recurringIva"><option value="recoverable">Recuperable</option><option value="nonrecoverable">No recuperable</option><option value="no_iva">Sin IVA</option></select></label>
            <label><span>Neto</span><input class="input" type="number" min="0" step="0.01" name="net_amount" id="recurringNet" required></label><label><span>IVA</span><input class="input" type="number" min="0" step="0.01" name="tax_amount" id="recurringTax" value="0"></label>
            <label><span>Total bruto</span><input class="input" type="number" min="0" step="0.01" name="gross_amount" id="recurringGross" required></label><label><span>Frecuencia</span><select class="select" name="frequency" id="recurringFrequency"><option value="monthly">Mensual</option><option value="quarterly">Trimestral</option><option value="semiannual">Semestral</option><option value="annual">Anual</option></select></label>
            <label><span>Día del mes</span><input class="input" type="number" min="1" max="28" name="day_of_month" id="recurringDay" value="1"></label><label><span>Inicio</span><input class="input" type="month" name="start_period" id="recurringStart" required></label>
            <label><span>Fin opcional</span><input class="input" type="month" name="end_period" id="recurringEnd"></label><label><span>Estado</span><select class="select" name="is_active" id="recurringActive"><option value="1">Activa</option><option value="0">Inactiva</option></select></label>
            <label class="wide"><span>Notas</span><textarea class="input" name="notes" id="recurringNotes" rows="2"></textarea></label>
        </div></form><footer><button class="btn btn-outline" type="button" data-close-modal="recurringModal">Cancelar</button><button class="btn btn-primary" type="submit" form="recurringForm"><i data-lucide="save"></i><span>Guardar recurrencia</span></button></footer>
    </div></div>

    <div class="cost-modal-backdrop" id="payrollModal" aria-hidden="true"><div class="cost-modal-box" role="dialog" aria-modal="true" aria-labelledby="payrollModalTitle">
        <header><div><span class="label">INFORMACIÓN PROTEGIDA</span><h2 id="payrollModalTitle">Costo empresa</h2></div><button type="button" class="btn btn-outline cost-modal-close" data-close-modal="payrollModal"><i data-lucide="x"></i></button></header>
        <form id="payrollForm"><input type="hidden" name="action" value="save_payroll"><input type="hidden" name="id" id="payrollId"><input type="hidden" name="period" id="payrollPeriod"><div class="cost-form-grid">
            <label><span>Código interno</span><input class="input" name="person_code" id="payrollCode" maxlength="80" required></label><label><span>Persona o agrupación</span><input class="input" name="person_name" id="payrollName" required></label>
            <label><span>Cargo / área</span><input class="input" name="role_name" id="payrollRole"></label><label><span>Tipo</span><select class="select" name="employment_type" id="payrollType"><option value="employee">Dependiente</option><option value="fees">Honorarios</option><option value="other">Otro</option></select></label>
            <label><span>Sueldo base</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="base_salary" id="payrollBase" value="0"></label><label><span>Asignaciones</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="allowances" id="payrollAllowances" value="0"></label>
            <label><span>Bonos</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="bonuses" id="payrollBonuses" value="0"></label><label><span>Cargas empleador</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="employer_charges" id="payrollCharges" value="0"></label>
            <label><span>Honorarios</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="fees" id="payrollFees" value="0"></label><label><span>Otros costos</span><input class="input payroll-amount" type="number" min="0" step="0.01" name="other_costs" id="payrollOther" value="0"></label>
            <label><span>Centro</span><select class="select" name="finance_center_id" id="payrollCenter"></select></label><label><span>Pago previsto</span><input class="input" type="date" name="expected_payment_date" id="payrollExpected"></label>
            <label><span>Pago efectivo</span><input class="input" type="date" name="effective_payment_date" id="payrollEffective"></label><div class="payroll-total"><span>Costo empresa</span><strong id="payrollTotal">$0</strong></div>
            <label class="wide"><span>Notas</span><textarea class="input" name="notes" id="payrollNotes" rows="2"></textarea></label>
        </div></form><footer><button class="btn btn-outline" type="button" data-close-modal="payrollModal">Cancelar</button><button class="btn btn-primary" type="submit" form="payrollForm"><i data-lucide="save"></i><span>Guardar costo empresa</span></button></footer>
    </div></div>

    <style>
    #costsMain{height:100dvh;max-height:100dvh;overflow:hidden;display:flex;flex-direction:column}
    #costsMain .costs-shell{width:min(100%,1800px);max-width:none!important;margin:0 auto;flex:1 1 0;min-height:0;overflow:auto;padding-bottom:24px}
    .costs-header{display:flex;justify-content:space-between;align-items:flex-end;gap:24px;margin-bottom:16px}.costs-header h1{margin:3px 0 4px}.costs-header p{margin:0;color:var(--text-secondary)}
    .costs-header-actions{display:flex;align-items:flex-end;justify-content:flex-end;gap:10px;flex-wrap:wrap}.cost-period-control{display:grid;gap:4px}.cost-period-control .cost-period-status{justify-self:start;width:max-content;max-width:100%;font-size:.68rem;font-weight:750;text-transform:none;white-space:nowrap}.cost-period-control input{width:155px}
    .cost-actions-menu{position:relative}.cost-actions-menu summary{list-style:none}.cost-actions-menu summary::-webkit-details-marker{display:none}.cost-actions-panel{position:absolute;right:0;top:calc(100% + 7px);z-index:20;display:grid;min-width:240px;padding:7px;background:var(--surface-1);border:1px solid var(--border-default);border-radius:var(--radius-lg);box-shadow:var(--shadow-lg)}.cost-actions-panel button{display:flex;align-items:center;gap:9px;padding:10px;border:0;border-radius:var(--radius-md);background:transparent;color:var(--text-primary);text-align:left;cursor:pointer}.cost-actions-panel button:hover{background:var(--surface-2)}.cost-actions-panel svg{width:17px}
    .cost-notice{margin-bottom:12px;padding:11px 13px;border:1px solid var(--border-default);border-radius:var(--radius-md);background:var(--surface-1)}.cost-notice.is-error{color:var(--color-error);border-color:color-mix(in srgb,var(--color-error) 40%,var(--border-default))}.cost-notice.is-success{color:var(--color-success)}
    .cost-tabs{display:flex;gap:6px;overflow-x:auto;padding:5px;margin-bottom:14px;border:1px solid var(--border-subtle);border-radius:var(--radius-lg);background:var(--surface-1)}.cost-tabs button{display:flex;align-items:center;justify-content:center;gap:7px;min-width:130px;padding:9px 13px;border:0;border-radius:var(--radius-md);background:transparent;color:var(--text-secondary);font:inherit;font-size:.82rem;cursor:pointer}.cost-tabs button svg{width:17px}.cost-tabs button.is-active{background:var(--surface-3);color:var(--text-primary);font-weight:650}
    .cost-tab-panel{display:none}.cost-tab-panel.is-active{display:block}.cost-kpis{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;margin-bottom:12px}.cost-kpi{padding:15px;border:1px solid var(--border-subtle);border-radius:var(--radius-lg);background:var(--surface-1);min-width:0}.cost-kpi span{display:block;color:var(--text-muted);font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em}.cost-kpi strong{display:block;margin-top:7px;font-size:1.2rem;overflow:hidden;text-overflow:ellipsis}.cost-kpi small{display:block;margin-top:4px;color:var(--text-muted);font-size:.68rem}
    .cost-analysis-grid{display:grid;grid-template-columns:1.3fr .8fr 1fr;gap:12px}.cost-analysis-card{padding:0;overflow:hidden}.cost-analysis-card>header{padding:14px 16px;border-bottom:1px solid var(--border-subtle)}.cost-analysis-card h3{margin:2px 0 0;font-size:1rem}.cost-bars{display:grid;gap:12px;padding:15px;max-height:310px;overflow:auto}.cost-bar-row{display:grid;gap:5px}.cost-bar-meta{display:flex;justify-content:space-between;gap:12px;font-size:.77rem}.cost-bar-track{height:7px;border-radius:99px;background:var(--surface-3);overflow:hidden}.cost-bar-fill{height:100%;border-radius:inherit;background:linear-gradient(90deg,var(--color-primary),#65a5ff)}
    .cost-guidance-card,.payroll-privacy-card{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;margin-top:12px}.cost-guidance-card svg,.payroll-privacy-card svg{width:20px;flex:0 0 20px;color:var(--color-primary)}.cost-guidance-card p,.payroll-privacy-card p{margin:3px 0 0;color:var(--text-secondary);font-size:.78rem}
    .cost-table-card{display:flex;flex-direction:column;min-height:420px;max-height:calc(100dvh - 260px);overflow:hidden}.cost-card-header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;border-bottom:1px solid var(--border-subtle)}.cost-card-header h3,.cost-card-header p{margin:0}.cost-card-header p{margin-top:3px;color:var(--text-muted);font-size:.75rem}.cost-table-filters{display:flex;gap:8px}.cost-table-filters input{min-width:260px}.cost-table-scroll{flex:1 1 0;min-height:0;overflow:auto}.cost-table{width:100%;border-collapse:separate;border-spacing:0}.cost-table th{position:sticky;top:0;z-index:2;padding:10px 12px;background:var(--surface-2);border-bottom:1px solid var(--border-default);color:var(--text-muted);font-size:.68rem;text-transform:uppercase;text-align:left;white-space:nowrap}.cost-table td{padding:11px 12px;border-bottom:1px solid var(--border-subtle);vertical-align:middle;font-size:.8rem}.cost-table tr:hover td{background:var(--surface-2)}.cost-table td small{display:block;margin-top:3px;color:var(--text-muted);font-size:.68rem}.cost-table .number{text-align:right}.cost-row-actions{display:flex;justify-content:flex-end;gap:5px}.cost-row-actions .btn{min-width:36px;padding:0 8px}.cost-empty{text-align:center!important;color:var(--text-muted);padding:32px!important}
    .cost-modal-backdrop{position:fixed;inset:0;z-index:1100;display:none;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.7);backdrop-filter:blur(5px)}.cost-modal-backdrop.is-open{display:flex}.cost-modal-box{width:min(920px,calc(100vw - 48px));max-height:calc(100dvh - 48px);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--border-default);border-radius:var(--radius-xl);background:var(--surface-1);box-shadow:var(--shadow-lg)}.cost-modal-box.compact{width:min(760px,calc(100vw - 48px))}.cost-modal-box>header,.cost-modal-box>footer{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 20px;flex:0 0 auto}.cost-modal-box>header{border-bottom:1px solid var(--border-subtle)}.cost-modal-box>header h2{margin:2px 0 0;font-size:1.2rem}.cost-modal-box>footer{justify-content:flex-end;border-top:1px solid var(--border-subtle);background:var(--surface-0)}.cost-modal-close{width:40px;padding:0}.cost-modal-box>form{padding:18px 20px;overflow:auto}.cost-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px}.cost-form-grid label{display:grid;gap:5px}.cost-form-grid label>span{font-size:.72rem;font-weight:650;color:var(--text-secondary)}.cost-form-grid .wide{grid-column:1/-1}.cost-form-grid textarea.input{height:auto;resize:vertical}.allocation-editor{margin-top:16px;padding:14px;border:1px solid var(--border-default);border-radius:var(--radius-lg);background:var(--surface-2)}.allocation-heading{display:flex;justify-content:space-between;gap:12px}.allocation-heading small{display:block;margin-top:3px;color:var(--text-muted)}.allocation-heading .allocation-suggestion{color:var(--color-primary);font-weight:700}#allocationRows{display:grid;gap:8px;margin-top:12px}.allocation-row{display:grid;grid-template-columns:1fr 130px 40px;gap:8px}.allocation-row button{padding:0}.allocation-total{text-align:right;margin-top:10px;color:var(--text-muted);font-size:.75rem}.allocation-total strong{color:var(--text-primary)}.payroll-total{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border:1px solid var(--border-default);border-radius:var(--radius-md);background:var(--surface-2)}.payroll-total span{font-size:.72rem;color:var(--text-muted)}
    @media(max-width:1250px){.cost-kpis{grid-template-columns:repeat(3,minmax(0,1fr))}.cost-analysis-grid{grid-template-columns:1fr 1fr}.cost-analysis-card:last-child{grid-column:1/-1}}
    @media(max-width:760px){#costsMain{height:auto;max-height:none;overflow:visible}#costsMain .costs-shell{overflow:visible;padding:12px}.costs-header{align-items:flex-start;flex-direction:column}.costs-header-actions{width:100%;justify-content:flex-start}.costs-header-actions .btn-primary{flex:1}.cost-period-control{flex:1}.cost-period-control input{width:100%}.cost-tabs button{min-width:116px}.cost-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.cost-analysis-grid{grid-template-columns:1fr}.cost-analysis-card:last-child{grid-column:auto}.cost-table-card{max-height:none}.cost-card-header{align-items:flex-start;flex-direction:column}.cost-table-filters{width:100%;flex-direction:column}.cost-table-filters input{min-width:0}.cost-table{min-width:850px}.cost-modal-backdrop{padding:0}.cost-modal-box,.cost-modal-box.compact{width:100vw;max-width:100vw;height:100dvh;max-height:100dvh;border-radius:0}.cost-form-grid{grid-template-columns:1fr}.cost-form-grid .wide{grid-column:auto}.allocation-row{grid-template-columns:1fr 90px 40px}}
    </style>

    <script>window.ICY_COSTS_INITIAL_PERIOD=<?php echo json_encode($initialPeriod); ?>;</script>
    <script src="/modules/costs/costs.js?v=9.1.1"></script>
</main>

<?php require_once '../../layouts/footer.php'; ?>
