<?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');
$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) : '';
?>

<div class="row g-3 mb-3">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h1 class="h5 mb-3">Configuracion general de empresa</h1>
                <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">Telefono</label>
                            <input class="form-control" name="telefono" value="<?= e((string) old('telefono', (string) ($company['telefono'] ?? ''))) ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Direccion</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">Pais</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 hasta 2MB)</label>
                            <input type="file" class="form-control w-100" 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" for="removeCompanyLogo">Eliminar logo actual</label>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <button class="btn btn-primary mt-3" type="submit">Guardar configuracion general</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h6 mb-3">Resumen actual</h2>
                <?php if ($logoUrl !== ''): ?>
                    <div class="mb-3">
                        <img
                            src="<?= e($logoUrl) ?>"
                            alt="Logo empresa"
                            class="img-fluid rounded border"
                            style="max-height: 120px;"
                        >
                    </div>
                <?php else: ?>
                    <p class="text-muted mb-3">Esta empresa aun no tiene logo cargado.</p>
                <?php endif; ?>

                <p class="mb-2"><strong>Estado:</strong> <?= e((string) ($company['estado'] ?? '')) ?></p>
                <p class="mb-2"><strong>ID Empresa:</strong> <?= e((string) ($company['id'] ?? '')) ?></p>
                <p class="mb-2"><strong>Moneda:</strong> <?= e((string) ($company['moneda'] ?? '')) ?></p>
                <p class="mb-0"><strong>Zona:</strong> <?= e((string) ($company['zona_horaria'] ?? '')) ?></p>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-lg-6">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h6 mb-2">Gestión fiscal y documentos</h2>
                <p class="text-muted mb-3">Abre cada formulario desde estos accesos rápidos.</p>
                <div class="d-flex flex-wrap gap-2">
                    <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#companyFiscalModal">
                        <i class="bx bx-receipt me-1"></i>Configuracion fiscal base
                    </button>
                    <?php if (!$feManagedByFactus): ?>
                        <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#documentNumberingModal">
                            <i class="bx bx-hash me-1"></i>Numeraciones
                        </button>
                        <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#dianResolutionModal">
                            <i class="bx bx-file me-1"></i>Resoluciones DIAN
                        </button>
                    <?php else: ?>
                        <span class="badge text-bg-success px-3 py-2">
                            <i class="bx bx-check-shield me-1"></i>Numeración DIAN gestionada por Factus
                        </span>
                    <?php endif; ?>
                </div>
                <hr class="my-3">
                <div class="small">
                    <div class="mb-1">
                        <strong>Módulo FE:</strong>
                        <?php if ($planAllowsElectronicInvoicing): ?>
                            <span class="badge <?= $facturacionElectronica ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                <?= $facturacionElectronica ? 'Activo' : 'Inactivo' ?>
                            </span>
                        <?php else: ?>
                            <span class="badge text-bg-warning">No incluido en el plan</span>
                        <?php endif; ?>
                    </div>
                    <div class="mb-1">
                        <strong>API Factus:</strong>
                        <?php if (!empty($factusConfigured['api_url']) && !empty($factusConfigured['username']) && !empty($factusConfigured['client_id'])): ?>
                            <span class="badge text-bg-success">Configurada</span>
                        <?php else: ?>
                            <span class="badge text-bg-secondary">Pendiente</span>
                        <?php endif; ?>
                    </div>
                    <div class="mb-0">
                        <strong>Resolución base:</strong> <?= e((string) ($fiscalSettings['resolucion_dian'] ?? 'Sin definir')) ?>
                    </div>
                    <?php if ($feManagedByFactus): ?>
                        <div class="alert alert-info py-2 px-3 mt-3 mb-0">
                            Con FE activa y credenciales completas, la numeración y resolución se toman desde Factus.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h6 mb-3">Impuestos de venta</h2>
                <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">
                        <label class="form-label d-block">Activo</label>
                        <input type="hidden" name="impuesto_activo" value="0">
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" name="impuesto_activo" value="1" <?= (string) old('impuesto_activo', '1') === '1' ? 'checked' : '' ?>>
                        </div>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-primary" type="submit">Agregar impuesto</button>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                        <tr>
                            <th>Nombre</th>
                            <th>Tipo</th>
                            <th>%</th>
                            <th>Estado</th>
                            <th>Accion</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>
                                    <?php if ($taxGlobal): ?>
                                        <span class="text-muted small">No editable</span>
                                    <?php else: ?>
                                        <form action="<?= e(url('configuracion/impuestos/' . $tax['id'] . '/estado')) ?>" method="post">
                                            <?= 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>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h6 mb-3">Metodos de pago por empresa</h2>

        <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">Codigo (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">
                <label class="form-label d-block">Activo</label>
                <input type="hidden" name="metodo_activo" value="0">
                <div class="form-check mt-2">
                    <input class="form-check-input" type="checkbox" name="metodo_activo" value="1" <?= (string) old('metodo_activo', '1') === '1' ? 'checked' : '' ?>>
                </div>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button class="btn btn-primary w-100" type="submit">Agregar</button>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>Nombre</th>
                    <th>Codigo</th>
                    <th>Origen</th>
                    <th>Estado</th>
                    <th>Accion</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($paymentMethods === []): ?>
                    <tr>
                        <td colspan="5" class="text-center text-muted py-3">No hay metodos 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>
                            <?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">
                                    <?= 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>
</div>

<div class="card border-0 shadow-sm mt-3">
    <div class="card-body">
        <h2 class="h6 mb-3">Unidades de medida</h2>

        <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">
                <label class="form-label d-block">Activa</label>
                <input type="hidden" name="unidad_activo" value="0">
                <div class="form-check mt-2">
                    <input class="form-check-input" type="checkbox" name="unidad_activo" value="1" <?= (string) old('unidad_activo', '1') === '1' ? 'checked' : '' ?>>
                </div>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button class="btn btn-primary w-100" type="submit">Agregar</button>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>Nombre</th>
                    <th>Abreviatura</th>
                    <th>Estado</th>
                    <th>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>
                            <div class="d-flex flex-wrap gap-2">
                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#editUnit<?= e((string) $unit['id']) ?>">
                                    Editar
                                </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">Eliminar</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">
                                            <label class="form-label d-block">Activa</label>
                                            <input type="hidden" name="activo" value="0">
                                            <div class="form-check mt-2">
                                                <input class="form-check-input" type="checkbox" name="activo" value="1" <?= $unitActive ? 'checked' : '' ?>>
                                            </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>

<?php if (!$feManagedByFactus): ?>
    <div class="row g-3 mt-1">
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <h2 class="h6 mb-0">Numeraciones de documentos</h2>
                        <button class="btn btn-sm btn-outline-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-striped table-hover">
                            <thead>
                            <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>
        </div>

        <div class="col-lg-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                        <h2 class="h6 mb-0">Resoluciones DIAN</h2>
                        <button class="btn btn-sm btn-outline-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-striped table-hover">
                            <thead>
                            <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>
        </div>
    </div>
<?php endif; ?>

<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">Configuracion fiscal base</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <?php require __DIR__ . '/partials/fiscal_form.php'; ?>
            </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 require __DIR__ . '/partials/electronic_billing_form.php'; ?>
            </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 require __DIR__ . '/partials/numbering_form.php'; ?>
                </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 require __DIR__ . '/partials/resolution_form.php'; ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    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;
        }
        const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
        modal.show();
    };

    if (shouldOpenFiscalModal) {
        openModalById('companyFiscalModal');
    } else if (shouldOpenElectronicBillingModal) {
        openModalById('electronicBillingModal');
    } else if (shouldOpenNumberingModal) {
        openModalById('documentNumberingModal');
    } else if (shouldOpenResolutionModal) {
        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);
    });

    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>
