<?php $__env->startSection('title', 'Configuracion | Veltrix v2'); ?>
<?php $__env->startSection('page_title', 'Configuracion'); ?>
<?php $__env->startSection('page_subtitle', 'Centro de control de tu empresa'); ?>
<?php $__env->startSection('page_icon', 'bx bxs-cog'); ?>

<?php $__env->startSection('content'); ?>
<?php
$company = $company ?? [];
$countries = $countries ?? [];
$cities = $cities ?? [];
$currencies = $currencies ?? [];
$timezones = $timezones ?? ['America/Bogota', 'UTC'];
$fiscalSettings = $fiscalSettings ?? [];
$taxes = $taxes ?? [];
$paymentMethods = $paymentMethods ?? [];
$measurementUnits = $measurementUnits ?? [];
$documentNumberings = $documentNumberings ?? [];
$dianResolutions = $dianResolutions ?? [];
$branches = $branches ?? [];
$currentPlan = $currentPlan ?? null;
$planAllowsElectronicInvoicing = (bool) ($planAllowsElectronicInvoicing ?? false);
$feManagedByFactus = (bool) ($feManagedByFactus ?? false);
$factusConfigured = is_array($factusConfigured ?? null) ? $factusConfigured : [];

$selectedCountry = (int) old('pais_id', (string) ($company['pais_id'] ?? 0));
$selectedCity = (int) old('ciudad_id', (string) ($company['ciudad_id'] ?? 0));
$selectedDepartment = trim((string) old('departamento', ''));
$selectedCurrency = (string) old('moneda', (string) ($company['moneda'] ?? 'COP'));
$selectedTimezone = (string) old('zona_horaria', (string) ($company['zona_horaria'] ?? 'America/Bogota'));

$citiesById = [];
$companyCityOptions = [];
foreach ($cities as $city) {
    $cityId = (int) ($city['id'] ?? 0);
    if ($cityId <= 0) {
        continue;
    }

    $countryId = (int) ($city['pais_id'] ?? 0);
    $cityName = trim((string) ($city['nombre'] ?? ''));
    $countryName = trim((string) ($city['pais'] ?? ''));
    $departmentName = trim((string) ($city['departamento'] ?? ''));
    $label = $cityName;
    if ($departmentName !== '') {
        $label .= ' - ' . $departmentName;
    }

    $cityData = [
        'id' => $cityId,
        'country_id' => $countryId,
        'name' => $cityName,
        'country' => $countryName,
        'department' => $departmentName,
        'label' => $label,
    ];
    $citiesById[$cityId] = $cityData;
    $companyCityOptions[] = $cityData;
}
if ($selectedCountry <= 0 && $selectedCity > 0) {
    $selectedCountry = (int) ($citiesById[$selectedCity]['country_id'] ?? 0);
}
if ($selectedDepartment === '' && $selectedCity > 0) {
    $selectedDepartment = trim((string) ($citiesById[$selectedCity]['department'] ?? ''));
}

$regimenFiscal = (string) old('regimen_fiscal', (string) ($fiscalSettings['regimen_fiscal'] ?? 'comun'));
$ambienteFacturacion = (string) old('ambiente_facturacion', (string) ($fiscalSettings['ambiente_facturacion'] ?? 'pruebas'));
$responsableIva = (string) old('responsable_iva', (string) ($fiscalSettings['responsable_iva'] ?? '0')) === '1';
$facturacionElectronica = (string) old('facturacion_electronica', (string) ($fiscalSettings['facturacion_electronica'] ?? '0')) === '1';
$factusApiUrl = (string) old('factus_api_url', (string) ($fiscalSettings['factus_api_url'] ?? ''));
$factusClientId = (string) old('factus_client_id', '');
$factusClientSecret = (string) old('factus_client_secret', '');
$factusUsername = (string) old('factus_username', '');
$factusPassword = (string) old('factus_password', '');
$factusSoftwareId = (string) old('factus_software_id', '');
$factusSoftwarePin = (string) old('factus_software_pin', '');
$factusNumberingRangeId = (string) old('factus_numbering_range_id', (string) ($fiscalSettings['factus_numbering_range_id'] ?? ''));
$factusMunicipalityId = (string) old('factus_municipality_id', (string) ($fiscalSettings['factus_municipality_id'] ?? ''));
$factusLoadRangesUrl = (string) url('configuracion/fiscal/factus/rangos');
$factusLoadMunicipalitiesUrl = (string) url('configuracion/fiscal/factus/municipios');
$ticketSize = (string) old('pos_ticket_size', (string) ($ticketSize ?? '80mm'));
if (! in_array($ticketSize, ['58mm', '80mm'], true)) {
    $ticketSize = '80mm';
}
$openFiscalModal = old('regimen_fiscal', null) !== null
    || old('prefijo_factura', null) !== null
    || old('resolucion_dian', null) !== null
    || old('actividad_economica', null) !== null;
$openElectronicBillingModal = old('facturacion_electronica', null) !== null
    || old('factus_api_url', null) !== null
    || old('factus_numbering_range_id', null) !== null
    || old('factus_municipality_id', null) !== null;
$openNumberingModal = old('n_tipo_documento', null) !== null
    || old('n_consecutivo_actual', null) !== null
    || old('tipo_documento', null) !== null;
$openResolutionModal = old('r_numero_resolucion', null) !== null
    || old('r_rango_desde', null) !== null
    || old('numero_resolucion', null) !== null;
if ($feManagedByFactus) {
    $openNumberingModal = false;
    $openResolutionModal = false;
}

$logoPath = trim((string) ($company['logo'] ?? ''));
$logoUrl = $logoPath !== '' ? url($logoPath) : '';

// Status / completeness checks for the hero summary.
$hasCompanyBasics = trim((string) ($company['nombre'] ?? '')) !== '' && trim((string) ($company['nit'] ?? '')) !== '';
$hasFiscalBasics = trim((string) ($fiscalSettings['regimen_fiscal'] ?? '')) !== '';
$hasTaxes = !empty($taxes);
$hasPaymentMethods = !empty($paymentMethods);
$hasNumbering = !empty($documentNumberings);
$hasResolution = !empty($dianResolutions);
$hasFactusFull = $feManagedByFactus;

$totalChecks = 6;
$doneChecks = (int) $hasCompanyBasics + (int) $hasFiscalBasics + (int) $hasTaxes + (int) $hasPaymentMethods + (int) ($hasNumbering || $hasFactusFull) + (int) ($hasResolution || $hasFactusFull);
$completionPct = $totalChecks > 0 ? (int) round(($doneChecks / $totalChecks) * 100) : 0;

// Default tab from query string (e.g. ?tab=fiscal)
$initialTab = trim((string) request()->query('tab', 'general'));
if (! in_array($initialTab, ['general', 'fiscal', 'impresion', 'catalogos', 'numeracion'], true)) {
    $initialTab = 'general';
}
?>

<style>
    .vx-config-hero {
        background: linear-gradient(135deg, #312e81 0%, #4338ca 50%, #6366f1 100%);
        color: #fff;
        border-radius: 18px;
        padding: 28px 32px;
        margin-bottom: 24px;
        box-shadow: 0 18px 40px -22px rgba(67, 56, 202, .55);
        position: relative;
        overflow: hidden;
    }
    .vx-config-hero::after {
        content: "";
        position: absolute;
        right: -60px; top: -60px;
        width: 240px; height: 240px;
        background: radial-gradient(circle, rgba(255,255,255,.18), transparent 70%);
        border-radius: 50%;
    }
    .vx-config-hero h1 {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: .25rem;
        letter-spacing: .2px;
    }
    .vx-config-hero .vx-hero-subtitle { opacity: .85; font-size: .92rem; margin-bottom: 0; }
    .vx-config-hero .vx-progress-track {
        height: 8px;
        background: rgba(255,255,255,.2);
        border-radius: 999px;
        overflow: hidden;
    }
    .vx-config-hero .vx-progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #34d399, #22d3ee);
        border-radius: 999px;
        transition: width .4s ease;
    }
    .vx-config-hero .vx-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: rgba(255,255,255,.16);
        backdrop-filter: blur(4px);
        color: #fff;
        font-size: .78rem;
        font-weight: 500;
        padding: 6px 12px;
        border-radius: 999px;
        margin: 4px 6px 0 0;
    }
    .vx-status-pill .bx { font-size: 1rem; }
    .vx-status-pill.is-on { background: rgba(34, 197, 94, .35); }
    .vx-status-pill.is-off { background: rgba(239, 68, 68, .25); }

    .vx-config-nav {
        background: #fff;
        border-radius: 14px;
        padding: 10px;
        box-shadow: 0 4px 18px -10px rgba(15, 23, 42, .15);
        position: sticky;
        top: 90px;
    }
    .vx-nav-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        width: 100%;
        text-align: left;
        background: transparent;
        border: 0;
        padding: 12px 14px;
        border-radius: 10px;
        color: #1f2937;
        transition: background-color .15s ease, color .15s ease;
        cursor: pointer;
    }
    .vx-nav-item:hover {
        background: #f3f4f6;
    }
    .vx-nav-item.active {
        background: linear-gradient(135deg, #eef2ff, #e0e7ff);
        color: #3730a3;
    }
    .vx-nav-item .vx-nav-icon {
        width: 38px; height: 38px;
        border-radius: 10px;
        background: #eef2ff;
        color: #4338ca;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 1.15rem;
        flex-shrink: 0;
    }
    .vx-nav-item.active .vx-nav-icon {
        background: #4338ca;
        color: #fff;
    }
    .vx-nav-item .vx-nav-title {
        font-weight: 600;
        font-size: .94rem;
        line-height: 1.15;
    }
    .vx-nav-item .vx-nav-sub {
        font-size: .75rem;
        color: #6b7280;
        margin-top: 2px;
    }
    .vx-nav-item.active .vx-nav-sub { color: #6366f1; }

    .vx-section { display: none; animation: vxFade .25s ease; }
    .vx-section.active { display: block; }
    @keyframes vxFade {
        from { opacity: 0; transform: translateY(4px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .vx-card {
        background: #fff;
        border-radius: 14px;
        box-shadow: 0 4px 18px -10px rgba(15, 23, 42, .14);
        border: 1px solid #f1f5f9;
        padding: 22px 24px;
        margin-bottom: 18px;
    }
    .vx-card .vx-card-head {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 18px;
    }
    .vx-card .vx-card-head h2 {
        font-size: 1.05rem;
        font-weight: 600;
        margin-bottom: .15rem;
    }
    .vx-card .vx-card-head .vx-card-sub {
        color: #6b7280;
        font-size: .85rem;
        margin-bottom: 0;
    }

    /* Thermal printer preview */
    .vx-ticket-preview-wrap {
        display: flex;
        gap: 18px;
        align-items: flex-end;
        justify-content: center;
        flex-wrap: wrap;
        padding: 18px;
        background: linear-gradient(180deg, #f8fafc, #eef2ff);
        border-radius: 12px;
    }
    .vx-ticket-mock {
        background: #fff;
        border: 2px dashed #cbd5e1;
        border-radius: 4px;
        padding: 8px;
        font-family: "Courier New", monospace;
        font-size: 8px;
        color: #475569;
        text-align: center;
        transition: all .25s ease;
        cursor: pointer;
        position: relative;
    }
    .vx-ticket-mock.size-58 { width: 70px; min-height: 130px; }
    .vx-ticket-mock.size-80 { width: 96px; min-height: 150px; }
    .vx-ticket-mock.is-active {
        border-color: #4338ca;
        box-shadow: 0 8px 22px -10px rgba(67, 56, 202, .55);
        transform: translateY(-2px);
    }
    .vx-ticket-mock .vx-mock-tag {
        position: absolute;
        bottom: -22px;
        left: 50%;
        transform: translateX(-50%);
        font-family: "Poppins", sans-serif;
        background: #fff;
        color: #1e293b;
        font-weight: 600;
        font-size: .72rem;
        padding: 3px 10px;
        border-radius: 999px;
        box-shadow: 0 4px 10px -4px rgba(15, 23, 42, .25);
        white-space: nowrap;
    }
    .vx-ticket-mock.is-active .vx-mock-tag {
        background: #4338ca;
        color: #fff;
    }
    .vx-ticket-mock .vx-mock-line {
        height: 4px; background: #e2e8f0; margin: 3px auto;
        border-radius: 2px;
    }
    .vx-ticket-mock .vx-mock-line.short { width: 60%; }
    .vx-ticket-mock .vx-mock-line.full { width: 100%; }
    .vx-ticket-mock .vx-mock-total {
        font-weight: 800;
        color: #111827;
        font-size: 9px;
        margin: 6px 0 4px;
    }
</style>

<!-- ====================== HERO SUMMARY ====================== -->
<div class="vx-config-hero">
    <div class="row g-4 align-items-center position-relative" style="z-index: 1;">
        <div class="col-lg-7">
            <h1>
                <i class="bx bxs-cog me-2"></i>
                Configuración de <?php echo e($company['nombre'] ?? 'tu empresa'); ?>

            </h1>
            <p class="vx-hero-subtitle">Centraliza datos fiscales, catálogos, numeraciones e impresión POS desde un solo lugar.</p>
            <div class="mt-3">
                <span class="vx-status-pill <?php echo e($hasCompanyBasics ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e($hasCompanyBasics ? 'bx-check' : 'bx-error'); ?>"></i> Empresa
                </span>
                <span class="vx-status-pill <?php echo e($hasFiscalBasics ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e($hasFiscalBasics ? 'bx-check' : 'bx-error'); ?>"></i> Fiscal
                </span>
                <span class="vx-status-pill <?php echo e($hasTaxes ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e($hasTaxes ? 'bx-check' : 'bx-error'); ?>"></i> Impuestos
                </span>
                <span class="vx-status-pill <?php echo e($hasPaymentMethods ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e($hasPaymentMethods ? 'bx-check' : 'bx-error'); ?>"></i> Pagos
                </span>
                <span class="vx-status-pill <?php echo e(($hasNumbering || $hasFactusFull) ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e(($hasNumbering || $hasFactusFull) ? 'bx-check' : 'bx-error'); ?>"></i> Numeración
                </span>
                <span class="vx-status-pill <?php echo e(($hasResolution || $hasFactusFull) ? 'is-on' : 'is-off'); ?>">
                    <i class="bx <?php echo e(($hasResolution || $hasFactusFull) ? 'bx-check' : 'bx-error'); ?>"></i> Resolución DIAN
                </span>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="d-flex flex-column align-items-lg-end align-items-start">
                <div class="d-flex align-items-baseline gap-2 mb-1">
                    <span style="font-size: 2.2rem; font-weight: 700; line-height: 1;"><?php echo e($completionPct); ?>%</span>
                    <span class="opacity-75">configurado</span>
                </div>
                <div class="vx-progress-track w-100" style="max-width: 320px;">
                    <div class="vx-progress-fill" style="width: <?php echo e($completionPct); ?>%;"></div>
                </div>
                <small class="opacity-75 mt-2"><?php echo e($doneChecks); ?> de <?php echo e($totalChecks); ?> áreas listas</small>
            </div>
        </div>
    </div>
</div>

<!-- ====================== MAIN LAYOUT ====================== -->
<div class="row g-3">
    <!-- Side nav -->
    <div class="col-lg-3">
        <div class="vx-config-nav">
            <button type="button" class="vx-nav-item <?php echo e($initialTab === 'general' ? 'active' : ''); ?>" data-vx-tab="general">
                <span class="vx-nav-icon"><i class="bx bxs-buildings"></i></span>
                <span>
                    <span class="vx-nav-title">Empresa</span>
                    <span class="vx-nav-sub">Datos generales y logo</span>
                </span>
            </button>
            <button type="button" class="vx-nav-item <?php echo e($initialTab === 'fiscal' ? 'active' : ''); ?>" data-vx-tab="fiscal">
                <span class="vx-nav-icon"><i class="bx bx-receipt"></i></span>
                <span>
                    <span class="vx-nav-title">Fiscal & FE</span>
                    <span class="vx-nav-sub">Régimen, DIAN, Factus</span>
                </span>
            </button>
            <button type="button" class="vx-nav-item <?php echo e($initialTab === 'impresion' ? 'active' : ''); ?>" data-vx-tab="impresion">
                <span class="vx-nav-icon"><i class="bx bx-printer"></i></span>
                <span>
                    <span class="vx-nav-title">Impresión POS</span>
                    <span class="vx-nav-sub">Tamaño rollo térmico</span>
                </span>
            </button>
            <button type="button" class="vx-nav-item <?php echo e($initialTab === 'catalogos' ? 'active' : ''); ?>" data-vx-tab="catalogos">
                <span class="vx-nav-icon"><i class="bx bx-collection"></i></span>
                <span>
                    <span class="vx-nav-title">Catálogos</span>
                    <span class="vx-nav-sub">Impuestos, pagos, unidades</span>
                </span>
            </button>
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(! $feManagedByFactus): ?>
            <button type="button" class="vx-nav-item <?php echo e($initialTab === 'numeracion' ? 'active' : ''); ?>" data-vx-tab="numeracion">
                <span class="vx-nav-icon"><i class="bx bx-hash"></i></span>
                <span>
                    <span class="vx-nav-title">Numeración DIAN</span>
                    <span class="vx-nav-sub">Consecutivos y resoluciones</span>
                </span>
            </button>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

            <a href="<?php echo e(route('configuracion.manychat.index')); ?>" class="vx-nav-item" style="text-decoration:none">
                <span class="vx-nav-icon"><i class="bx bxl-whatsapp" style="color:#25d366"></i></span>
                <span>
                    <span class="vx-nav-title">WhatsApp IA</span>
                    <span class="vx-nav-sub">Integración ManyChat</span>
                </span>
            </a>

            <a href="<?php echo e(route('configuracion.envios')); ?>" class="vx-nav-item" style="text-decoration:none">
                <span class="vx-nav-icon"><i class="bx bxs-truck" style="color:#3b82f6"></i></span>
                <span>
                    <span class="vx-nav-title">Envíos</span>
                    <span class="vx-nav-sub">Rótulos y remitente</span>
                </span>
            </a>
        </div>
    </div>

    <!-- Tab panes -->
    <div class="col-lg-9">

        <!-- ============ EMPRESA ============ -->
        <div class="vx-section <?php echo e($initialTab === 'general' ? 'active' : ''); ?>" data-vx-pane="general">
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Información general</h2>
                        <p class="vx-card-sub">Estos datos aparecen en facturas, tickets y en todo el sistema.</p>
                    </div>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($logoUrl !== ''): ?>
                        <img src="<?php echo e($logoUrl); ?>" alt="Logo" style="max-height: 56px; max-width: 120px; object-fit: contain;" class="rounded border p-1">
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
                <form action="<?= e(url('configuracion/empresa')) ?>" method="post" enctype="multipart/form-data">
                    <?= csrf_field() ?>
                    <div class="row g-3">
                        <div class="col-md-8">
                            <label class="form-label">Nombre comercial</label>
                            <input class="form-control" name="nombre" value="<?= e((string) old('nombre', (string) ($company['nombre'] ?? ''))) ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">NIT</label>
                            <input class="form-control" name="nit" value="<?= e((string) old('nit', (string) ($company['nit'] ?? ''))) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" value="<?= e((string) old('email', (string) ($company['email'] ?? ''))) ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Teléfono</label>
                            <input class="form-control" name="telefono" value="<?= e((string) old('telefono', (string) ($company['telefono'] ?? ''))) ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Dirección</label>
                            <input class="form-control" name="direccion" value="<?= e((string) old('direccion', (string) ($company['direccion'] ?? ''))) ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">País</label>
                            <select class="form-select" name="pais_id" id="companyCountrySelect">
                                <option value="0">Sin definir</option>
                                <?php foreach ($countries as $country): ?>
                                    <option value="<?= e((string) $country['id']) ?>" <?= $selectedCountry === (int) $country['id'] ? 'selected' : '' ?>>
                                        <?= e($country['nombre']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Departamento</label>
                            <select class="form-select" name="departamento" id="companyDepartmentSelect">
                                <option value="">Sin definir</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Municipio</label>
                            <select class="form-select" name="ciudad_id" id="companyCitySelect">
                                <option value="0">Sin definir</option>
                            </select>
                            <?php if ($companyCityOptions === []): ?>
                                <small class="text-muted d-block mt-1">No hay ciudades cargadas. Importa el catálogo DANE.</small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Moneda</label>
                            <select class="form-select" name="moneda" required>
                                <?php foreach ($currencies as $currency): ?>
                                    <option value="<?= e($currency['codigo']) ?>" <?= $selectedCurrency === (string) $currency['codigo'] ? 'selected' : '' ?>>
                                        <?= e($currency['codigo']) ?> - <?= e($currency['nombre']) ?> (<?= e($currency['simbolo']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Zona horaria</label>
                            <select class="form-select" name="zona_horaria" required>
                                <?php foreach ($timezones as $timezone): ?>
                                    <option value="<?= e($timezone) ?>" <?= $selectedTimezone === $timezone ? 'selected' : '' ?>>
                                        <?= e($timezone) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Logo (JPG, PNG o WEBP — máx. 2MB)</label>
                            <input type="file" class="form-control" name="logo" accept=".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp">
                            <?php if ($logoUrl !== ''): ?>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="checkbox" value="1" id="removeCompanyLogo" name="eliminar_logo">
                                    <label class="form-check-label small" for="removeCompanyLogo">Eliminar logo actual</label>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="d-flex justify-content-end mt-4">
                        <button class="btn btn-primary px-4" type="submit"><i class="bx bx-save me-1"></i>Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ============ FISCAL & FE ============ -->
        <div class="vx-section <?php echo e($initialTab === 'fiscal' ? 'active' : ''); ?>" data-vx-pane="fiscal">
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Configuración fiscal</h2>
                        <p class="vx-card-sub">Régimen, responsabilidad de IVA y resolución base.</p>
                    </div>
                </div>
                <div class="row g-3">
                    <div class="col-md-4">
                        <div class="border rounded-3 p-3 h-100">
                            <small class="text-muted d-block">Régimen</small>
                            <strong class="d-block fs-6"><?php echo e(ucfirst((string) ($fiscalSettings['regimen_fiscal'] ?? 'sin definir'))); ?></strong>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="border rounded-3 p-3 h-100">
                            <small class="text-muted d-block">Responsable IVA</small>
                            <strong class="d-block fs-6"><?php echo e(trim((string) ($fiscalSettings['responsable_iva'] ?? '0')) === '1' ? 'Sí' : 'No'); ?></strong>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="border rounded-3 p-3 h-100">
                            <small class="text-muted d-block">Resolución base</small>
                            <strong class="d-block fs-6"><?php echo e(trim((string) ($fiscalSettings['resolucion_dian'] ?? '')) !== '' ? $fiscalSettings['resolucion_dian'] : 'Sin definir'); ?></strong>
                        </div>
                    </div>
                </div>
                <div class="d-flex flex-wrap gap-2 mt-3">
                    <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#companyFiscalModal">
                        <i class="bx bx-edit me-1"></i>Editar configuración fiscal
                    </button>
                </div>
            </div>

            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Facturación electrónica (Factus)</h2>
                        <p class="vx-card-sub">Estado de la integración con tu proveedor tecnológico.</p>
                    </div>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($feManagedByFactus): ?>
                        <span class="badge text-bg-success px-3 py-2"><i class="bx bx-check-shield me-1"></i>Activa</span>
                    <?php elseif($facturacionElectronica): ?>
                        <span class="badge text-bg-warning px-3 py-2"><i class="bx bx-time me-1"></i>Pendiente</span>
                    <?php else: ?>
                        <span class="badge text-bg-secondary px-3 py-2">Inactiva</span>
                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                </div>
                <div class="row g-2 small">
                    <div class="col-md-6 d-flex justify-content-between border-bottom py-2">
                        <span>Módulo FE</span>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($planAllowsElectronicInvoicing): ?>
                            <strong><?php echo e($facturacionElectronica ? 'Activado' : 'Desactivado'); ?></strong>
                        <?php else: ?>
                            <strong class="text-warning">No incluido en el plan</strong>
                        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                    <div class="col-md-6 d-flex justify-content-between border-bottom py-2">
                        <span>API Factus</span>
                        <strong><?php echo e((!empty($factusConfigured['api_url']) && !empty($factusConfigured['username']) && !empty($factusConfigured['client_id'])) ? 'Configurada' : 'Pendiente'); ?></strong>
                    </div>
                </div>
                <div class="d-flex flex-wrap gap-2 mt-3">
                    <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#electronicBillingModal">
                        <i class="bx bx-cog me-1"></i>Credenciales y rangos Factus
                    </button>
                </div>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($feManagedByFactus): ?>
                    <div class="alert alert-info py-2 px-3 mt-3 mb-0 small">
                        <i class="bx bx-info-circle me-1"></i>Con FE activa y credenciales completas, la numeración y resolución se gestionan desde Factus.
                    </div>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </div>
        </div>

        <!-- ============ IMPRESIÓN ============ -->
        <div class="vx-section <?php echo e($initialTab === 'impresion' ? 'active' : ''); ?>" data-vx-pane="impresion">
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Tamaño del rollo térmico</h2>
                        <p class="vx-card-sub">El ticket POS se renderiza automáticamente al ancho que selecciones.</p>
                    </div>
                    <span class="badge text-bg-light border align-self-start">Actual: <strong class="ms-1"><?php echo e($ticketSize); ?></strong></span>
                </div>

                <form action="<?= e(url('configuracion/ticket-size')) ?>" method="post" id="ticketSizeForm">
                    <?= csrf_field() ?>
                    <input type="hidden" name="pos_ticket_size" id="ticketSizeInput" value="<?php echo e($ticketSize); ?>">

                    <div class="vx-ticket-preview-wrap mb-3">
                        <div class="vx-ticket-mock size-58 <?php echo e($ticketSize === '58mm' ? 'is-active' : ''); ?>" data-vx-size="58mm">
                            <strong style="font-size: 9px;">VOLTA</strong>
                            <div class="vx-mock-line short"></div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line short"></div>
                            <div class="vx-mock-total">$38.080</div>
                            <div class="vx-mock-line short"></div>
                            <span class="vx-mock-tag">58 mm</span>
                        </div>
                        <div class="vx-ticket-mock size-80 <?php echo e($ticketSize === '80mm' ? 'is-active' : ''); ?>" data-vx-size="80mm">
                            <strong style="font-size: 10px;">VOLTA</strong>
                            <div class="vx-mock-line short"></div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line short"></div>
                            <div class="vx-mock-total">$38.080</div>
                            <div class="vx-mock-line full"></div>
                            <div class="vx-mock-line short"></div>
                            <span class="vx-mock-tag">80 mm</span>
                        </div>
                    </div>

                    <div class="row g-3 align-items-stretch">
                        <div class="col-md-6">
                            <label class="form-label">Selecciona tamaño del rollo</label>
                            <select class="form-select form-select-lg" name="pos_ticket_size_select" id="ticketSizeSelect">
                                <option value="58mm" <?php echo e($ticketSize === '58mm' ? 'selected' : ''); ?>>58 mm — compacto (mini-impresoras)</option>
                                <option value="80mm" <?php echo e($ticketSize === '80mm' ? 'selected' : ''); ?>>80 mm — estándar (recomendado)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <div class="alert alert-info py-2 px-3 mb-0 small h-100 d-flex align-items-center">
                                <span>
                                    <i class="bx bx-bulb me-1"></i>
                                    <strong>58 mm</strong> es ideal para tickets sencillos y rápidos. <strong>80 mm</strong> permite más detalle (impuestos, QR DIAN, resolución completa).
                                </span>
                            </div>
                        </div>
                        <div class="col-12 d-flex justify-content-end">
                            <button class="btn btn-primary px-4" type="submit"><i class="bx bx-save me-1"></i>Guardar tamaño</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- ============ CATÁLOGOS ============ -->
        <div class="vx-section <?php echo e($initialTab === 'catalogos' ? 'active' : ''); ?>" data-vx-pane="catalogos">

            <!-- Impuestos -->
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Impuestos de venta</h2>
                        <p class="vx-card-sub">IVA, INC, ICOH y retenciones que aparecen en POS y facturación.</p>
                    </div>
                </div>
                <form action="<?= e(url('configuracion/impuestos')) ?>" method="post" class="row g-2 mb-3">
                    <?= csrf_field() ?>
                    <div class="col-md-5">
                        <label class="form-label">Nombre</label>
                        <input class="form-control" name="impuesto_nombre" value="<?= e((string) old('impuesto_nombre', '')) ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">% Tasa</label>
                        <input type="number" step="0.01" min="0" max="100" class="form-control" name="impuesto_porcentaje" value="<?= e((string) old('impuesto_porcentaje', '19')) ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Tipo</label>
                        <select class="form-select" name="impuesto_tipo">
                            <?php $selectedTaxType = (string) old('impuesto_tipo', 'IVA'); ?>
                            <option value="IVA" <?= $selectedTaxType === 'IVA' ? 'selected' : '' ?>>IVA</option>
                            <option value="INC" <?= $selectedTaxType === 'INC' ? 'selected' : '' ?>>INC</option>
                            <option value="ICOH" <?= $selectedTaxType === 'ICOH' ? 'selected' : '' ?>>ICOH</option>
                            <option value="RETEFUENTE" <?= $selectedTaxType === 'RETEFUENTE' ? 'selected' : '' ?>>ReteFuente</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <div class="form-check">
                            <input type="hidden" name="impuesto_activo" value="0">
                            <input class="form-check-input" type="checkbox" name="impuesto_activo" value="1" <?= (string) old('impuesto_activo', '1') === '1' ? 'checked' : '' ?>>
                            <label class="form-check-label small">Activo</label>
                        </div>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-primary" type="submit"><i class="bx bx-plus me-1"></i>Agregar impuesto</button>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                        <tr><th>Nombre</th><th>Tipo</th><th>%</th><th>Estado</th><th class="text-end">Acción</th></tr>
                        </thead>
                        <tbody>
                        <?php if ($taxes === []): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3">No hay impuestos configurados.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($taxes as $tax): ?>
                            <?php
                            $taxActive = (int) ($tax['activo'] ?? 0) === 1;
                            $taxGlobal = (int) ($tax['es_global'] ?? 0) === 1;
                            ?>
                            <tr>
                                <td>
                                    <?= e((string) ($tax['nombre'] ?? '')) ?>
                                    <?php if ($taxGlobal): ?><span class="badge text-bg-secondary ms-1">Global</span><?php endif; ?>
                                </td>
                                <td><?= e((string) ($tax['tipo'] ?? '')) ?></td>
                                <td><?= e(number_format((float) ($tax['porcentaje'] ?? 0), 2)) ?></td>
                                <td>
                                    <span class="badge <?= $taxActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $taxActive ? 'Activo' : 'Inactivo' ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <?php if ($taxGlobal): ?>
                                        <span class="text-muted small">No editable</span>
                                    <?php else: ?>
                                        <form action="<?= e(url('configuracion/impuestos/' . $tax['id'] . '/estado')) ?>" method="post" class="d-inline">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="activo" value="<?= $taxActive ? '0' : '1' ?>">
                                            <button class="btn btn-sm <?= $taxActive ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                                <?= $taxActive ? 'Desactivar' : 'Activar' ?>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Métodos de pago -->
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Métodos de pago</h2>
                        <p class="vx-card-sub">Disponibles en el POS para registrar cobros.</p>
                    </div>
                </div>
                <form action="<?= e(url('configuracion/metodos-pago')) ?>" method="post" class="row g-2 mb-3">
                    <?= csrf_field() ?>
                    <div class="col-md-5">
                        <label class="form-label">Nombre</label>
                        <input class="form-control" name="metodo_nombre" value="<?= e((string) old('metodo_nombre', '')) ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Código (opcional)</label>
                        <input class="form-control" name="metodo_codigo" placeholder="se-genera-si-vacio" value="<?= e((string) old('metodo_codigo', '')) ?>">
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <div class="form-check">
                            <input type="hidden" name="metodo_activo" value="0">
                            <input class="form-check-input" type="checkbox" name="metodo_activo" value="1" <?= (string) old('metodo_activo', '1') === '1' ? 'checked' : '' ?>>
                            <label class="form-check-label small">Activo</label>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button class="btn btn-primary w-100" type="submit"><i class="bx bx-plus me-1"></i>Agregar</button>
                    </div>
                </form>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                        <tr><th>Nombre</th><th>Código</th><th>Origen</th><th>Estado</th><th class="text-end">Acción</th></tr>
                        </thead>
                        <tbody>
                        <?php if ($paymentMethods === []): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3">No hay métodos de pago configurados.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($paymentMethods as $method): ?>
                            <?php
                            $methodActive = (int) ($method['activo'] ?? 0) === 1;
                            $methodGlobal = (int) ($method['es_global'] ?? 0) === 1;
                            ?>
                            <tr>
                                <td><?= e((string) ($method['nombre'] ?? '')) ?></td>
                                <td><code><?= e((string) ($method['codigo'] ?? '')) ?></code></td>
                                <td>
                                    <?php if ($methodGlobal): ?>
                                        <span class="badge text-bg-secondary">Global</span>
                                    <?php else: ?>
                                        <span class="badge text-bg-info">Empresa</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge <?= $methodActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $methodActive ? 'Activo' : 'Inactivo' ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <?php if ($methodGlobal): ?>
                                        <span class="text-muted small">No editable</span>
                                    <?php else: ?>
                                        <form action="<?= e(url('configuracion/metodos-pago/' . $method['id'] . '/estado')) ?>" method="post" class="d-inline">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="activo" value="<?= $methodActive ? '0' : '1' ?>">
                                            <button class="btn btn-sm <?= $methodActive ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                                <?= $methodActive ? 'Desactivar' : 'Activar' ?>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Unidades de medida -->
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Unidades de medida</h2>
                        <p class="vx-card-sub">Catálogo usado en productos e inventario.</p>
                    </div>
                </div>
                <form action="<?= e(url('configuracion/unidades-medida')) ?>" method="post" class="row g-2 mb-3">
                    <?= csrf_field() ?>
                    <div class="col-md-5">
                        <label class="form-label">Nombre</label>
                        <input class="form-control" name="unidad_nombre" value="<?= e((string) old('unidad_nombre', '')) ?>" placeholder="Unidad, Kilogramo, Litro..." required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Abreviatura</label>
                        <input class="form-control" name="unidad_abreviatura" maxlength="20" value="<?= e((string) old('unidad_abreviatura', '')) ?>" placeholder="Und, Kg, Lt..." required>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <div class="form-check">
                            <input type="hidden" name="unidad_activo" value="0">
                            <input class="form-check-input" type="checkbox" name="unidad_activo" value="1" <?= (string) old('unidad_activo', '1') === '1' ? 'checked' : '' ?>>
                            <label class="form-check-label small">Activa</label>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button class="btn btn-primary w-100" type="submit"><i class="bx bx-plus me-1"></i>Agregar</button>
                    </div>
                </form>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                        <tr><th>Nombre</th><th>Abreviatura</th><th>Estado</th><th class="text-end">Acciones</th></tr>
                        </thead>
                        <tbody>
                        <?php if ($measurementUnits === []): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">No hay unidades de medida registradas.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($measurementUnits as $unit): ?>
                            <?php $unitActive = (int) ($unit['activo'] ?? 0) === 1; ?>
                            <tr>
                                <td><?= e((string) ($unit['nombre'] ?? '')) ?></td>
                                <td><span class="badge text-bg-light border"><?= e((string) ($unit['abreviatura'] ?? '')) ?></span></td>
                                <td>
                                    <span class="badge <?= $unitActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $unitActive ? 'Activa' : 'Inactiva' ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <div class="d-inline-flex flex-wrap gap-2 justify-content-end">
                                        <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#editUnit<?= e((string) $unit['id']) ?>">
                                            <i class="bx bx-edit-alt"></i>
                                        </button>
                                        <form action="<?= e(url('configuracion/unidades-medida/' . $unit['id'] . '/estado')) ?>" method="post">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="activo" value="<?= $unitActive ? '0' : '1' ?>">
                                            <button class="btn btn-sm <?= $unitActive ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                                <?= $unitActive ? 'Desactivar' : 'Activar' ?>
                                            </button>
                                        </form>
                                        <form action="<?= e(url('configuracion/unidades-medida/' . $unit['id'] . '/eliminar')) ?>" method="post" onsubmit="return confirm('¿Eliminar unidad de medida?');">
                                            <?= csrf_field() ?>
                                            <button class="btn btn-sm btn-outline-danger" type="submit"><i class="bx bx-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4" class="p-0 border-0">
                                    <div class="collapse" id="editUnit<?= e((string) $unit['id']) ?>">
                                        <div class="border rounded bg-light p-3 mb-2">
                                            <form action="<?= e(url('configuracion/unidades-medida/' . $unit['id'] . '/actualizar')) ?>" method="post" class="row g-2">
                                                <?= csrf_field() ?>
                                                <div class="col-md-5">
                                                    <label class="form-label">Nombre</label>
                                                    <input class="form-control" name="nombre" value="<?= e((string) ($unit['nombre'] ?? '')) ?>" required>
                                                </div>
                                                <div class="col-md-3">
                                                    <label class="form-label">Abreviatura</label>
                                                    <input class="form-control" name="abreviatura" maxlength="20" value="<?= e((string) ($unit['abreviatura'] ?? '')) ?>" required>
                                                </div>
                                                <div class="col-md-2 d-flex align-items-end">
                                                    <div class="form-check">
                                                        <input type="hidden" name="activo" value="0">
                                                        <input class="form-check-input" type="checkbox" name="activo" value="1" <?= $unitActive ? 'checked' : '' ?>>
                                                        <label class="form-check-label small">Activa</label>
                                                    </div>
                                                </div>
                                                <div class="col-md-2 d-flex align-items-end">
                                                    <button class="btn btn-sm btn-primary w-100" type="submit">Guardar</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ============ NUMERACIÓN DIAN ============ -->
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(! $feManagedByFactus): ?>
        <div class="vx-section <?php echo e($initialTab === 'numeracion' ? 'active' : ''); ?>" data-vx-pane="numeracion">
            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Numeraciones de documentos</h2>
                        <p class="vx-card-sub">Consecutivos y prefijos para facturas, notas y POS.</p>
                    </div>
                    <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#documentNumberingModal">
                        <i class="bx bx-plus-circle me-1"></i>Nueva numeración
                    </button>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                        <tr><th>Sucursal</th><th>Tipo</th><th>Prefijo</th><th>Actual</th><th>Final</th><th>Estado</th><th></th></tr>
                        </thead>
                        <tbody>
                        <?php if ($documentNumberings === []): ?>
                            <tr><td colspan="7" class="text-center text-muted py-3">No hay numeraciones registradas.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($documentNumberings as $numbering): ?>
                            <?php $isActive = (int) ($numbering['activo'] ?? 0) === 1; ?>
                            <tr>
                                <td><?= e((string) ($numbering['sucursal'] ?? 'General')) ?></td>
                                <td><?= e((string) ($numbering['tipo_documento'] ?? '')) ?></td>
                                <td><?= e((string) (($numbering['prefijo'] ?? '') !== '' ? $numbering['prefijo'] : '-')) ?></td>
                                <td><?= e((string) ($numbering['consecutivo_actual'] ?? '')) ?></td>
                                <td><?= e((string) (($numbering['consecutivo_final'] ?? '') !== '' ? $numbering['consecutivo_final'] : '-')) ?></td>
                                <td>
                                    <span class="badge <?= $isActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $isActive ? 'Activa' : 'Inactiva' ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <form action="<?= e(url('configuracion/numeraciones/' . $numbering['id'] . '/estado')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="activo" value="<?= $isActive ? '0' : '1' ?>">
                                        <button class="btn btn-sm <?= $isActive ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                            <?= $isActive ? 'Desactivar' : 'Activar' ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="vx-card">
                <div class="vx-card-head">
                    <div>
                        <h2>Resoluciones DIAN</h2>
                        <p class="vx-card-sub">Autorizaciones de numeración para facturación.</p>
                    </div>
                    <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#dianResolutionModal">
                        <i class="bx bx-plus-circle me-1"></i>Nueva resolución
                    </button>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                        <tr><th>Sucursal</th><th>Resolución</th><th>Fechas</th><th>Rango</th><th>Estado</th><th></th></tr>
                        </thead>
                        <tbody>
                        <?php if ($dianResolutions === []): ?>
                            <tr><td colspan="6" class="text-center text-muted py-3">No hay resoluciones registradas.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($dianResolutions as $resolution): ?>
                            <?php $isActiveResolution = (int) ($resolution['activo'] ?? 0) === 1; ?>
                            <tr>
                                <td><?= e((string) ($resolution['sucursal'] ?? 'General')) ?></td>
                                <td>
                                    <?= e((string) ($resolution['numero_resolucion'] ?? '')) ?>
                                    <?php if ((string) ($resolution['prefijo'] ?? '') !== ''): ?>
                                        <br><small class="text-muted">Prefijo: <?= e((string) $resolution['prefijo']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?= e((string) ($resolution['fecha_desde'] ?? '')) ?> a <?= e((string) ($resolution['fecha_hasta'] ?? '')) ?></td>
                                <td><?= e((string) ($resolution['rango_desde'] ?? '')) ?> - <?= e((string) ($resolution['rango_hasta'] ?? '')) ?></td>
                                <td>
                                    <span class="badge <?= $isActiveResolution ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $isActiveResolution ? 'Activa' : 'Inactiva' ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <form action="<?= e(url('configuracion/resoluciones/' . $resolution['id'] . '/estado')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="activo" value="<?= $isActiveResolution ? '0' : '1' ?>">
                                        <button class="btn btn-sm <?= $isActiveResolution ? 'btn-outline-secondary' : 'btn-outline-success' ?>" type="submit">
                                            <?= $isActiveResolution ? 'Desactivar' : 'Activar' ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    </div>
</div>

<!-- ====================== MODALES (intactos) ====================== -->
<div class="modal fade" id="companyFiscalModal" tabindex="-1" aria-labelledby="companyFiscalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title h5 mb-0" id="companyFiscalModalLabel">Configuración fiscal base</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php echo $__env->make('modules.configuracion.partials.fiscal_form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="electronicBillingModal" tabindex="-1" aria-labelledby="electronicBillingModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title h5 mb-0" id="electronicBillingModalLabel">Facturación electrónica (módulo)</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php echo $__env->make('modules.configuracion.partials.electronic_billing_form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            </div>
        </div>
    </div>
</div>

<?php if (!$feManagedByFactus): ?>
    <div class="modal fade" id="documentNumberingModal" tabindex="-1" aria-labelledby="documentNumberingModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title h5 mb-0" id="documentNumberingModalLabel">Nueva numeración de documento</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <?php echo $__env->make('modules.configuracion.partials.numbering_form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="dianResolutionModal" tabindex="-1" aria-labelledby="dianResolutionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title h5 mb-0" id="dianResolutionModalLabel">Nueva resolución DIAN</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <?php echo $__env->make('modules.configuracion.partials.resolution_form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    /* ---------------------- VX side-nav tabs ---------------------- */
    const navItems = document.querySelectorAll('[data-vx-tab]');
    const panes = document.querySelectorAll('[data-vx-pane]');
    const activateTab = (key) => {
        navItems.forEach((btn) => btn.classList.toggle('active', btn.getAttribute('data-vx-tab') === key));
        panes.forEach((p) => p.classList.toggle('active', p.getAttribute('data-vx-pane') === key));
        try {
            const url = new URL(window.location.href);
            url.searchParams.set('tab', key);
            window.history.replaceState({}, '', url);
        } catch (e) { /* ignore */ }
    };
    navItems.forEach((btn) => {
        btn.addEventListener('click', () => activateTab(btn.getAttribute('data-vx-tab')));
    });

    /* ---------------------- Thermal preview interactions ---------------------- */
    const sizeSelect = document.getElementById('ticketSizeSelect');
    const sizeInput = document.getElementById('ticketSizeInput');
    const mocks = document.querySelectorAll('.vx-ticket-mock');
    const syncSize = (value) => {
        if (!value) return;
        if (sizeInput) sizeInput.value = value;
        if (sizeSelect && sizeSelect.value !== value) sizeSelect.value = value;
        mocks.forEach((m) => m.classList.toggle('is-active', m.getAttribute('data-vx-size') === value));
    };
    if (sizeSelect) sizeSelect.addEventListener('change', () => syncSize(sizeSelect.value));
    mocks.forEach((m) => m.addEventListener('click', () => syncSize(m.getAttribute('data-vx-size'))));

    /* ---------------------- Country / department / city cascade ---------------------- */
    const countrySelect = document.getElementById('companyCountrySelect');
    const departmentSelect = document.getElementById('companyDepartmentSelect');
    const citySelect = document.getElementById('companyCitySelect');
    const shouldOpenFiscalModal = <?= json_encode($openFiscalModal) ?> === true;
    const shouldOpenElectronicBillingModal = <?= json_encode($openElectronicBillingModal) ?> === true;
    const shouldOpenNumberingModal = <?= json_encode($openNumberingModal) ?> === true;
    const shouldOpenResolutionModal = <?= json_encode($openResolutionModal) ?> === true;
    const cityOptions = <?= json_encode(
        $companyCityOptions,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
    ) ?>;

    const openModalById = (id) => {
        const modalElement = document.getElementById(id);
        if (!(modalElement instanceof HTMLElement) || typeof bootstrap === 'undefined' || typeof bootstrap.Modal === 'undefined') {
            return;
        }
        bootstrap.Modal.getOrCreateInstance(modalElement).show();
    };

    if (shouldOpenFiscalModal) { activateTab('fiscal'); openModalById('companyFiscalModal'); }
    else if (shouldOpenElectronicBillingModal) { activateTab('fiscal'); openModalById('electronicBillingModal'); }
    else if (shouldOpenNumberingModal) { activateTab('numeracion'); openModalById('documentNumberingModal'); }
    else if (shouldOpenResolutionModal) { activateTab('numeracion'); openModalById('dianResolutionModal'); }

    if (
        !(countrySelect instanceof HTMLSelectElement) ||
        !(departmentSelect instanceof HTMLSelectElement) ||
        !(citySelect instanceof HTMLSelectElement)
    ) {
        return;
    }

    const cityById = new Map();
    cityOptions.forEach((city) => { cityById.set(Number(city.id), city); });

    const initialCityId = Number(<?= json_encode($selectedCity) ?>) || 0;
    const initialDepartment = String(<?= json_encode($selectedDepartment) ?> || '').trim();

    const selectedCountryId = () => Number(countrySelect.value || 0);
    const selectedDepartment = () => String(departmentSelect.value || '').trim();
    const selectedCityId = () => Number(citySelect.value || 0);

    const renderDepartmentOptions = (preferredDepartment = '') => {
        const countryId = selectedCountryId();
        departmentSelect.innerHTML = '';
        const emptyOption = document.createElement('option');
        emptyOption.value = ''; emptyOption.textContent = 'Sin definir';
        departmentSelect.appendChild(emptyOption);

        const departments = new Set();
        cityOptions.forEach((city) => {
            const cityCountryId = Number(city.country_id || 0);
            if (countryId > 0 && cityCountryId !== countryId) return;
            const department = String(city.department || '').trim();
            if (department !== '') departments.add(department);
        });

        const sortedDepartments = Array.from(departments).sort((a, b) => a.localeCompare(b, 'es', { sensitivity: 'base' }));
        let hasPreferred = false;
        sortedDepartments.forEach((departmentName) => {
            const option = document.createElement('option');
            option.value = departmentName; option.textContent = departmentName;
            if (departmentName === preferredDepartment) { option.selected = true; hasPreferred = true; }
            departmentSelect.appendChild(option);
        });
        if (!hasPreferred) departmentSelect.value = '';
        departmentSelect.disabled = sortedDepartments.length === 0;
    };

    const cityMatchesFilters = (city) => {
        const countryId = selectedCountryId();
        const cityCountryId = Number(city.country_id || 0);
        if (countryId > 0 && cityCountryId !== countryId) return false;
        const department = selectedDepartment();
        if (department === '') return true;
        return String(city.department || '').trim() === department;
    };

    const renderCityOptions = (preferredCityId = 0) => {
        citySelect.innerHTML = '';
        const emptyOption = document.createElement('option');
        emptyOption.value = '0'; emptyOption.textContent = 'Sin definir';
        citySelect.appendChild(emptyOption);
        let optionsCount = 0; let hasPreferred = false;
        cityOptions.forEach((city) => {
            if (!cityMatchesFilters(city)) return;
            const option = document.createElement('option');
            option.value = String(Number(city.id) || 0);
            option.textContent = String(city.name || '').trim();
            if (Number(city.id) === Number(preferredCityId)) { option.selected = true; hasPreferred = true; }
            citySelect.appendChild(option);
            optionsCount++;
        });
        if (!hasPreferred) citySelect.value = '0';
        citySelect.disabled = optionsCount === 0;
    };

    const syncInitialState = () => {
        const initialCity = cityById.get(initialCityId) || null;
        if (initialCity && selectedCountryId() <= 0) countrySelect.value = String(initialCity.country_id || 0);
        const preferredDepartment = initialDepartment !== ''
            ? initialDepartment
            : String(initialCity ? (initialCity.department || '') : '').trim();
        renderDepartmentOptions(preferredDepartment);
        renderCityOptions(initialCityId);
    };

    countrySelect.addEventListener('change', () => {
        const currentCity = cityById.get(selectedCityId()) || null;
        const preferredDepartment = currentCity && Number(currentCity.country_id || 0) === selectedCountryId()
            ? String(currentCity.department || '').trim() : '';
        renderDepartmentOptions(preferredDepartment);
        const preferred = currentCity && cityMatchesFilters(currentCity) ? selectedCityId() : 0;
        renderCityOptions(preferred);
    });

    departmentSelect.addEventListener('change', () => {
        const currentCity = cityById.get(selectedCityId()) || null;
        const preferred = currentCity && cityMatchesFilters(currentCity) ? selectedCityId() : 0;
        renderCityOptions(preferred);
    });

    /* ---------------------- Factus dynamic credentials block ---------------------- */
    const factusCredentialsBlock = document.getElementById('factusCredentialsBlock');
    const factusActionsBlock = document.getElementById('factusActionsBlock');
    const factusRequiredInputs = Array.from(document.querySelectorAll('[data-factus-required="1"]'));
    if (factusCredentialsBlock instanceof HTMLElement) {
        const syncFactusRequiredInputs = () => {
            factusRequiredInputs.forEach((input) => {
                if (!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement || input instanceof HTMLSelectElement)) return;
                const isConfigured = String(input.dataset.factusConfigured || '0') === '1';
                const hasValue = String(input.value || '').trim() !== '';
                input.required = !isConfigured && !hasValue;
            });
        };
        syncFactusRequiredInputs();
        factusRequiredInputs.forEach((input) => {
            if (!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement || input instanceof HTMLSelectElement)) return;
            input.addEventListener('input', syncFactusRequiredInputs);
            input.addEventListener('change', syncFactusRequiredInputs);
        });
        if (factusActionsBlock instanceof HTMLElement) factusActionsBlock.classList.remove('d-none');
    }

    const factusLoadRangesUrl = <?= json_encode($factusLoadRangesUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const factusLoadMunicipalitiesUrl = <?= json_encode($factusLoadMunicipalitiesUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const factusFiscalForm = document.getElementById('electronicBillingForm');
    const factusLoadRangesBtn = document.getElementById('factusLoadRangesBtn');
    const factusLoadMunicipalitiesBtn = document.getElementById('factusLoadMunicipalitiesBtn');
    const factusNumberingRangeInput = document.getElementById('factusNumberingRangeInput');
    const factusNumberingRangeSelect = document.getElementById('factusNumberingRangeSelect');
    const factusRangesHint = document.getElementById('factusRangesHint');
    const factusMunicipalityInput = document.getElementById('factusMunicipalityInput');
    const factusMunicipalitySearch = document.getElementById('factusMunicipalitySearch');
    const factusMunicipalitySelect = document.getElementById('factusMunicipalitySelect');
    const factusMunicipalitiesHint = document.getElementById('factusMunicipalitiesHint');

    const factusFieldNames = [
        'factus_api_url','factus_username','factus_client_id','factus_client_secret',
        'factus_software_id','factus_software_pin','factus_password',
        'factus_numbering_range_id','factus_municipality_id',
    ];
    const setFactusHint = (element, message, isError = false) => {
        if (!(element instanceof HTMLElement)) return;
        element.textContent = message;
        element.classList.toggle('text-danger', isError);
    };
    const setFactusButtonLoading = (button, loading) => {
        if (!(button instanceof HTMLButtonElement)) return;
        if (loading) {
            button.dataset.originalText = button.textContent || '';
            button.disabled = true; button.textContent = 'Cargando...'; return;
        }
        button.disabled = false; button.textContent = button.dataset.originalText || button.textContent || '';
    };
    const factusReadInput = (name) => {
        if (!(factusFiscalForm instanceof HTMLFormElement)) return '';
        const field = factusFiscalForm.querySelector(`[name="${name}"]`);
        if (field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement || field instanceof HTMLSelectElement) {
            return String(field.value || '').trim();
        }
        return '';
    };
    const factusReadCsrf = () => {
        if (!(factusFiscalForm instanceof HTMLFormElement)) return '';
        const tokenField = factusFiscalForm.querySelector('input[name="_token"]');
        if (tokenField instanceof HTMLInputElement) return String(tokenField.value || '').trim();
        return '';
    };
    const factusPost = async (url, extraPayload = {}) => {
        const csrfToken = factusReadCsrf();
        if (csrfToken === '') throw new Error('Token CSRF inválido. Recarga la página e intenta de nuevo.');
        const payload = new URLSearchParams();
        payload.set('_token', csrfToken);
        factusFieldNames.forEach((name) => payload.set(name, factusReadInput(name)));
        Object.entries(extraPayload).forEach(([key, value]) => payload.set(key, String(value ?? '')));
        const response = await fetch(url, {
            method: 'POST', credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
            body: payload.toString(),
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok || data?.ok !== true) throw new Error(String(data?.message || 'No fue posible consultar Factus.'));
        return data;
    };

    if (factusNumberingRangeSelect instanceof HTMLSelectElement && factusNumberingRangeInput instanceof HTMLInputElement) {
        factusNumberingRangeSelect.addEventListener('change', () => {
            const selectedValue = String(factusNumberingRangeSelect.value || '').trim();
            if (selectedValue !== '') factusNumberingRangeInput.value = selectedValue;
        });
    }
    if (factusMunicipalitySelect instanceof HTMLSelectElement && factusMunicipalityInput instanceof HTMLInputElement) {
        factusMunicipalitySelect.addEventListener('change', () => {
            const selectedValue = String(factusMunicipalitySelect.value || '').trim();
            if (selectedValue !== '') factusMunicipalityInput.value = selectedValue;
        });
    }
    if (factusLoadRangesBtn instanceof HTMLButtonElement && factusNumberingRangeSelect instanceof HTMLSelectElement && factusNumberingRangeInput instanceof HTMLInputElement) {
        factusLoadRangesBtn.addEventListener('click', async () => {
            setFactusButtonLoading(factusLoadRangesBtn, true);
            setFactusHint(factusRangesHint, 'Consultando rangos activos en Factus...');
            try {
                const response = await factusPost(factusLoadRangesUrl, { document: '21', solo_activas: '1' });
                const rows = Array.isArray(response?.data) ? response.data : [];
                factusNumberingRangeSelect.innerHTML = '';
                const emptyOption = document.createElement('option');
                emptyOption.value = '';
                emptyOption.textContent = rows.length > 0 ? 'Selecciona un rango...' : 'Sin rangos disponibles';
                factusNumberingRangeSelect.appendChild(emptyOption);
                const currentValue = String(factusNumberingRangeInput.value || '').trim();
                rows.forEach((row) => {
                    const rangeId = Number(row?.id || 0);
                    if (!Number.isFinite(rangeId) || rangeId <= 0) return;
                    const option = document.createElement('option');
                    option.value = String(rangeId);
                    option.textContent = String(row?.label || `Rango #${rangeId}`);
                    if (currentValue !== '' && currentValue === option.value) option.selected = true;
                    factusNumberingRangeSelect.appendChild(option);
                });
                factusNumberingRangeSelect.classList.toggle('d-none', rows.length === 0);
                setFactusHint(factusRangesHint, rows.length > 0
                    ? `Rangos cargados: ${rows.length}. Selecciona uno para completar el ID.`
                    : String(response?.message || 'No se encontraron rangos activos.'), false);
            } catch (error) {
                setFactusHint(factusRangesHint, error instanceof Error ? error.message : 'No fue posible cargar rangos en Factus.', true);
                factusNumberingRangeSelect.classList.add('d-none');
            } finally { setFactusButtonLoading(factusLoadRangesBtn, false); }
        });
    }
    if (factusLoadMunicipalitiesBtn instanceof HTMLButtonElement && factusMunicipalitySelect instanceof HTMLSelectElement && factusMunicipalityInput instanceof HTMLInputElement) {
        const fetchMunicipalities = async () => {
            setFactusButtonLoading(factusLoadMunicipalitiesBtn, true);
            setFactusHint(factusMunicipalitiesHint, 'Consultando municipios en Factus...');
            try {
                const searchText = factusMunicipalitySearch instanceof HTMLInputElement ? String(factusMunicipalitySearch.value || '').trim() : '';
                const response = await factusPost(factusLoadMunicipalitiesUrl, { query: searchText, limit: '120' });
                const rows = Array.isArray(response?.data) ? response.data : [];
                factusMunicipalitySelect.innerHTML = '';
                const emptyOption = document.createElement('option');
                emptyOption.value = '';
                emptyOption.textContent = rows.length > 0 ? 'Selecciona un municipio...' : 'Sin municipios disponibles';
                factusMunicipalitySelect.appendChild(emptyOption);
                const currentValue = String(factusMunicipalityInput.value || '').trim();
                rows.forEach((row) => {
                    const municipalityId = Number(row?.id || 0);
                    if (!Number.isFinite(municipalityId) || municipalityId <= 0) return;
                    const option = document.createElement('option');
                    option.value = String(municipalityId);
                    option.textContent = String(row?.label || `Municipio #${municipalityId}`);
                    if (currentValue !== '' && currentValue === option.value) option.selected = true;
                    factusMunicipalitySelect.appendChild(option);
                });
                factusMunicipalitySelect.classList.toggle('d-none', rows.length === 0);
                setFactusHint(factusMunicipalitiesHint, rows.length > 0
                    ? `Municipios cargados: ${rows.length}. Selecciona uno para completar el ID.`
                    : String(response?.message || 'No se encontraron municipios con ese criterio.'), false);
            } catch (error) {
                setFactusHint(factusMunicipalitiesHint, error instanceof Error ? error.message : 'No fue posible cargar municipios en Factus.', true);
                factusMunicipalitySelect.classList.add('d-none');
            } finally { setFactusButtonLoading(factusLoadMunicipalitiesBtn, false); }
        };
        factusLoadMunicipalitiesBtn.addEventListener('click', fetchMunicipalities);
        if (factusMunicipalitySearch instanceof HTMLInputElement) {
            factusMunicipalitySearch.addEventListener('keydown', (event) => {
                if (event.key !== 'Enter') return;
                event.preventDefault();
                fetchMunicipalities();
            });
        }
    }

    syncInitialState();
});
</script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Applications/XAMPP/xamppfiles/htdocs/veltrix-v2/resources/views/modules/configuracion/index.blade.php ENDPATH**/ ?>