<div class="row">

    <div class="col-xl-12">
        <div class="nav-align-top mb-4">
            <ul class="nav nav-pills mb-3" role="tablist">
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link active"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#informacion-cliente"
                            aria-controls="informacion-cliente"
                            aria-selected="true">
                        Ficha de Cliente
                    </button>
                </li>
                <?php if ($formAction !== route_to('clienteAdd')){ ?>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#tarifascliente"
                            aria-controls="tarifascliente"
                            aria-selected="false">
                        Tarifas
                    </button>
                </li>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#contactos"
                            aria-controls="contactos"
                            aria-selected="false">
                        Contactos
                    </button>
                </li>

                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#domicilio-entrega"
                            aria-controls="domicilio-entrega"
                            aria-selected="false">
                        Domicilio de Entrega
                    </button>
                </li>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link presupuestos-btn"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#presupuestos"
                            aria-controls="presupuestos"
                            aria-selected="false">
                        Presupuestos
                    </button>
                </li>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link pedidos-btn"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#pedidos"
                            aria-controls="pedidos"
                            aria-selected="false">
                        Pedidos
                    </button>
                </li>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link facturacion-btn"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#facturacion"
                            aria-controls="facturacion"
                            aria-selected="false">
                        Facturación
                    </button>
                </li>
                <li class="nav-item">
                    <button
                            type="button"
                            class="nav-link"
                            role="tab"
                            data-bs-toggle="tab"
                            data-bs-target="#usuarios"
                            aria-controls="usuarios"
                            aria-selected="false">
                        Usuarios
                    </button>
                </li>
                <?php } ?>
            </ul>
            <div class="tab-content">
                <div class="tab-pane fade show active" id="informacion-cliente" role="tabpanel">
                    <div class="accordion" id="collapsibleSection">
                        <div class="card accordion-item">
                            <h2 class="accordion-header" id="headingDeliveryAddress">
                                <button
                                        type="button"
                                        class="accordion-button"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#datos-cliente"
                                        aria-expanded="true"
                                        aria-controls="datos-cliente">
                                    Datos del Cliente
                                </button>
                            </h2>
                            <div
                                    id="datos-cliente"
                                    class="accordion-collapse collapse show"
                                    data-bs-parent="#collapsibleSection"
                            >
                                <div class="accordion-body">
                                    <div class="row g-3 mb-3">
                                        <div class="col-md-12">
                                            <label for="cif" class="form-label">
                                                <?= lang('Clientes.cif') ?>*
                                            </label>
                                            <input type="text" id="cif" name="cif" required
                                                   maxLength="50" class="form-control"
                                                   value="<?= old('cif', $clienteEntity->cif) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="nombre" class="form-label">
                                                <?= lang('Clientes.nombre') ?>*
                                            </label>
                                            <input
                                                    type="text" id="nombre" name="nombre" required
                                                    maxLength="255" class="form-control"
                                                    value="<?= old('nombre', $clienteEntity->nombre) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="alias" class="form-label">
                                                <?= lang('Clientes.alias') ?>*
                                            </label>
                                            <input type="text" id="alias" name="alias" required
                                                   maxLength="255" class="form-control"
                                                   value="<?= old('alias', $clienteEntity->alias) ?>"
                                            >
                                        </div>
                                        <div class="col-md-12">
                                            <label for="direccion" class="form-label">
                                                <?= lang('Clientes.direccion') ?>
                                            </label>
                                            <textarea rows="2"
                                                      id="direccion"
                                                      name="direccion"
                                                      style="height: 10em;"
                                                      class="form-control"
                                            ><?= old('direccion', $clienteEntity->direccion) ?>
                                            </textarea>
                                        </div>
                                        <div class="col-md-4">
                                            <label for="paisId" class="form-label">
                                                <?= lang('Clientes.paisId') ?>
                                            </label>
                                            <select id="paisId" name="pais_id" class="form-control select2bs" style="width: 100%;" >
                                            </select>
                                            
                                        </div>
                                        <div class="col-md-4">
                                            <label for="comunidadAutonomaId" class="form-label">
                                                <?= lang('Clientes.comunidadAutonomaId') ?>
                                            </label>
                                            <select id="comunidadAutonomaId"
                                                    name="comunidad_autonoma_id"
                                                    class="select2 form-control"
                                                    style="width: 100%;"
                                            >
                                                <?php if (isset($comunidadAutonomaList) && is_array($comunidadAutonomaList) && !empty($comunidadAutonomaList)) :
                                                    foreach ($comunidadAutonomaList as $k => $v) : ?>
                                                        <option value="<?= $k ?>"<?= $k == $clienteEntity->comunidad_autonoma_id ? ' selected' : '' ?>>
                                                            <?= $v ?>
                                                        </option>
                                                    <?php endforeach;
                                                endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label for="provinciaId" class="form-label">
                                                <?= lang('Clientes.provinciaId') ?>
                                            </label>
                                            <select
                                                    id="provinciaId"
                                                    name="provincia_id"
                                                    class="form-control select2"
                                                    style="width: 100%;"
                                            >
                                                <?php if (isset($provinciaList) && is_array($provinciaList) && !empty($provinciaList)) :
                                                    foreach ($provinciaList as $k => $v) : ?>
                                                        <option value="<?= $k ?>"<?= $k == $clienteEntity->provincia_id ? ' selected' : '' ?>>
                                                            <?= $v ?>
                                                        </option>
                                                    <?php endforeach;
                                                endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="ciudad" class="form-label">
                                                <?= lang('Clientes.ciudad') ?>
                                            </label>
                                            <input type="text" id="ciudad" name="ciudad"
                                                   maxLength="100" class="form-control"
                                                   value="<?= old('ciudad', $clienteEntity->ciudad) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="cp" class="form-label">
                                                <?= lang('Clientes.cp') ?>
                                            </label>
                                            <input type="text" id="cp" name="cp"
                                                   maxLength="10" class="form-control"
                                                   value="<?= old('cp', $clienteEntity->cp) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="telefono" class="form-label">
                                                <?= lang('Clientes.telefono') ?>
                                            </label>
                                            <input type="text" id="telefono" name="telefono"
                                                   maxLength="60" class="form-control"
                                                   value="<?= old('telefono', $clienteEntity->telefono) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="email" class="form-label">
                                                <?= lang('Clientes.email') ?>
                                            </label>
                                            <input type="email" id="email" name="email"
                                                   maxLength="150" class="form-control"
                                                   value="<?= old('email', $clienteEntity->email) ?>"
                                            >
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card accordion-item">
                            <h2 class="accordion-header" id="headingDeliveryOptions">
                                <button
                                        type="button"
                                        class="accordion-button collapsed"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#contabilidad"
                                        aria-expanded="false"
                                        aria-controls="contabilidad">
                                    Contabilidad
                                </button>
                            </h2>
                            <div
                                    id="contabilidad"
                                    class="accordion-collapse collapse"
                                    aria-labelledby="headingDeliveryOptions"
                                    data-bs-parent="#collapsibleSection">
                                <div class="accordion-body">
                                    <div class="row g-3 mb-3">
                                        <div class="col-md-6">
                                            <label for="formaPagoId" class="form-label">
                                                <?= lang('Clientes.formaPagoId') ?>
                                            </label>
                                            <select
                                                    id="formaPagoId"
                                                    name="forma_pago_id"
                                                    class="form-control select2"
                                                    style="width: 100%;"
                                            >
                                                <?php if (isset($formaDePagoList) && is_array($formaDePagoList) && !empty($formaDePagoList)) :
                                                    foreach ($formaDePagoList as $k => $v) : ?>
                                                        <option value="<?= $k ?>"<?= $k == $clienteEntity->forma_pago_id ? ' selected' : '' ?>>
                                                            <?= $v ?>
                                                        </option>
                                                    <?php endforeach;
                                                endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="vencimiento" class="form-label">
                                                <?= lang('Clientes.vencimiento') ?>
                                            </label>
                                            <input type="number" id="vencimiento" name="vencimiento"
                                                   placeholder="15" maxLength="10" class="form-control"
                                                   value="<?= old('vencimiento', $clienteEntity->vencimiento) ?>"
                                            >
                                        </div>
                                        <div class="col-md-3">
                                            <label for="fechaVencimiento" class="form-label">
                                                <?= lang('Clientes.fechaVencimiento') ?>
                                            </label>
                                            <input type="text" id="fechaVencimiento" name="fecha_vencimiento"
                                                   maxLength="100" class="form-control"
                                                   value="<?= old('fecha_vencimiento', $clienteEntity->fecha_vencimiento) ?>"
                                            >
                                        </div>
                                        <div class="col-md-4">
                                            <label for="ccc" class="form-label">
                                                <?= lang('Clientes.ccc') ?>
                                            </label>
                                            <input type="text" id="ccc" name="ccc"
                                                   maxLength="100" class="form-control"
                                                   value="<?= old('ccc', $clienteEntity->ccc) ?>"
                                            >
                                        </div>
                                        <div class="col-md-4">
                                            <label for="cccCliente" class="form-label">
                                                <?= lang('Clientes.cccCliente') ?>
                                            </label>
                                            <input type="text" id="cccCliente" name="ccc_cliente"
                                                   maxLength="100" class="form-control"
                                                   value="<?= old('ccc_cliente', $clienteEntity->ccc_cliente) ?>"
                                            >
                                        </div>
                                        <div class="col-md-4">
                                            <label for="numCuenta" class="form-label">
                                                <?= lang('Clientes.numCuenta') ?>
                                            </label>
                                            <input type="text" id="numCuenta" name="num_cuenta"
                                                   maxLength="10" class="form-control"
                                                   placeholder="Cuenta 4300000 por defecto"
                                                   value="<?= old('num_cuenta', $clienteEntity->num_cuenta) ?>"
                                            >
                                        </div>
                                        <div class="col-md-3">
                                            <label for="limiteCredito" class="form-label">
                                                <?= lang('Clientes.limiteCredito') ?>
                                            </label>
                                            <input type="number" id="limiteCredito"
                                                   name="limite_credito"
                                                   placeholder="0.00" maxLength="8"
                                                   step="0.01" class="form-control"
                                                   value="<?= old('limite_credito', $clienteEntity->limite_credito) ?>"
                                            >
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">

                                                <label for="creditoAsegurado" class="form-check-label">
                                                    <input type="checkbox" id="creditoAsegurado"
                                                           name="credito_asegurado" value="1"
                                                           class="form-check-input"<?= $clienteEntity->credito_asegurado == true ? 'checked' : ''; ?>>
                                                    <?= lang('Clientes.creditoAsegurado') ?>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="comentarios" class="form-label">
                                                <?= lang('Clientes.comentarios') ?>
                                            </label>
                                            <textarea rows="3" id="comentarios" name="comentarios"
                                                      style="height: 10em;"
                                                      class="form-control">
                                                <?= old('comentarios', $clienteEntity->comentarios) ?>
                                            </textarea>
                                        </div><!--//.mb-3 -->

                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card accordion-item">
                            <h2 class="accordion-header" id="headingPaymentMethod">
                                <button
                                        type="button"
                                        class="accordion-button collapsed"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#compras_ventas"
                                        aria-expanded="false"
                                        aria-controls="compras_ventas">
                                    Compras / Ventas
                                </button>
                            </h2>
                            <div
                                    id="compras_ventas"
                                    class="accordion-collapse collapse"
                                    aria-labelledby="headingPaymentMethod"
                                    data-bs-parent="#collapsibleSection"
                            >
                                <div class="accordion-body">
                                    <div class="row g-3 mb-3">
                                        <div class="col-md-6">
                                            <label for="comercialId" class="form-label">
                                                <?= lang('Clientes.comercialId') ?>
                                            </label>
                                            <select
                                                    id="comercialId"
                                                    name="comercial_id"
                                                    class="form-control select2"
                                                    style="width: 100%;"
                                            >
                                                <?php if (isset($userList) && is_array($userList) && !empty($userList)) :
                                                    foreach ($userList as $k => $v) : ?>
                                                        <option value="<?= $k ?>"<?= $k == $clienteEntity->comercial_id ? ' selected' : '' ?>>
                                                            <?= $v ?>
                                                        </option>
                                                    <?php endforeach;
                                                endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="soporteId" class="form-label">
                                                <?= lang('Clientes.soporteId') ?>
                                            </label>
                                            <select
                                                    id="soporteId"
                                                    name="soporte_id"
                                                    class="form-control select2"
                                                    style="width: 100%;"
                                            >
                                                <?php if (isset($userList2) && is_array($userList2) && !empty($userList2)) :
                                                    foreach ($userList2 as $k => $v) : ?>
                                                        <option value="<?= $k ?>"<?= $k == $clienteEntity->soporte_id ? ' selected' : '' ?>>
                                                            <?= $v ?>
                                                        </option>
                                                    <?php endforeach;
                                                endif; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="margen" class="form-label">
                                                <?= lang('Clientes.margen') ?>*
                                            </label>
                                            <input
                                                    type="number"
                                                    id="margen"
                                                    name="margen"
                                                    required
                                                    placeholder="40.00"
                                                    maxLength="8"
                                                    step="0.01"
                                                    class="form-control"
                                                    value="<?= old('margen', $clienteEntity->margen) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="descuento" class="form-label">
                                                <?= lang('Clientes.descuento') ?>*
                                            </label>
                                            <input type="number"
                                                   id="descuento"
                                                   name="descuento"
                                                   required
                                                   placeholder="0.00"
                                                   maxLength="8"
                                                   step="0.01"
                                                   class="form-control"
                                                   value="<?= old('descuento', $clienteEntity->descuento) ?>"
                                            >
                                        </div>
                                        <div class="col-md-6">
                                            <label for="margenPlantillaId" class="form-label">
                                                <?= lang('Clientes.margenPlantillaId') ?>
                                            </label>
                                            <input type="number"
                                                   id="margenPlantillaId"
                                                   name="margen_plantilla_id"
                                                   maxLength="10"
                                                   class="form-control"
                                                   value="<?= old('margen_plantilla_id', $clienteEntity->margen_plantilla_id) ?>"
                                            >
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="card accordion-item">
                            <h2 class="accordion-header" id="headingPaymentMethod">
                                <button
                                        type="button"
                                        class="accordion-button collapsed"
                                        data-bs-toggle="collapse"
                                        data-bs-target="#configuracion"
                                        aria-expanded="false"
                                        aria-controls="configuracion">
                                    Configuración
                                </button>
                            </h2>
                            <div
                                    id="configuracion"
                                    class="accordion-collapse collapse"
                                    aria-labelledby="headingPaymentMethod"
                                    data-bs-parent="#collapsibleSection"
                            >
                                <div class="accordion-body">
                                    <div class="row g-3 mb-3">

                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <label for="messageTracking" class="form-check-label">
                                                    <input type="checkbox" id="messageTracking" name="message_tracking"
                                                           value="1"
                                                           class="form-check-input"<?= $clienteEntity->message_tracking == true ? 'checked' : ''; ?>>
                                                    <?= lang('Clientes.messageTracking') ?>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <label for="messageProductionStart" class="form-check-label">
                                                    <input type="checkbox" id="messageProductionStart"
                                                           name="message_production_start" value="1"
                                                           class="form-check-input"<?= $clienteEntity->message_production_start == true ? 'checked' : ''; ?>>
                                                    <?= lang('Clientes.messageProductionStart') ?>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <label for="tiradaFlexible" class="form-check-label">
                                                    <input type="checkbox" id="tiradaFlexible" name="tirada_flexible"
                                                           value="1"
                                                           class="form-check-input"<?= $clienteEntity->tirada_flexible == true ? 'checked' : ''; ?>>
                                                    <?= lang('Clientes.tiradaFlexible') ?>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <label for="descuentoTiradaFlexible" class="form-label">
                                                <?= lang('Clientes.descuentoTiradaFlexible') ?>
                                            </label>
                                            <input type="number" id="descuentoTiradaFlexible"
                                                   name="descuento_tirada_flexible"
                                                   placeholder="20.00" maxLength="8" step="0.01" class="form-control"
                                                   value="<?= old('descuento_tirada_flexible', $clienteEntity->descuento_tirada_flexible) ?>"
                                            >
                                        </div>
                                        <div class="col-md-9">
                                            <label for="comentariosTiradaFlexible" class="form-label">
                                                <?= lang('Clientes.comentariosTiradaFlexible') ?>
                                            </label>
                                            <textarea rows="3" id="comentariosTiradaFlexible"
                                                      name="comentarios_tirada_flexible"
                                                      style="height: 10em;"
                                                      class="form-control">
                                                <?= old('comentarios_tirada_flexible', $clienteEntity->comentarios_tirada_flexible) ?>
                                            </textarea>
                                        </div><!--//.mb-3 -->
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>

                    <div class="d-flex align-items-center pt-3">
                        <div class="d-flex align-items-center">
                            Creado por [<?= $clienteEntity->user_created_id ?>] el <?= $clienteEntity->created_at ?>
                        </div>
                        <div class="ms-auto">
                            Editado por [<?= $clienteEntity->user_update_id ?>] el <?= $clienteEntity->updated_at ?>
                        </div>
                    </div>

                </div>


                <?php if ($formAction !== route_to('clienteAdd')){ ?>
                <div class="tab-pane fade" id="tarifascliente" role="tabpanel">
                    <div class='row'>
                        <div class="col-md-12 col-lg-4 px-4">
                            <div class="mb-3">
                                <label id="label_plantilla" for="plantillas" class="form-label">
                                    <?= lang('ClientePrecios.plantilla') ?>
                                </label>

                                <select id="plantillas" name="plantillas" class="form-control select2bs2" style="width: 100%;">
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class='row'>
                        <div class="col-md-12 col-lg-4 px-4">
                            <button id="convert2template" type="button" class="btn btn-secondary waves-effect waves-light float-start"><?= lang("ClientePrecios.convertir2plantilla")?></button>
                        </div>
                    </div>
                    <div class="table-responsive">

                        <table id="tableOfPrecios" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th><?= lang('ClientePrecios.tipo') ?></th>
                                    <th><?= lang('ClientePrecios.tipo_maquina') ?></th>
                                    <th><?= lang('ClientePrecios.tipo_impresion') ?></th>
                                    <th><?= lang('ClientePrecios.tiempo_min') ?></th>
                                    <th><?= lang('ClientePrecios.tiempo_max') ?></th>
                                    <th class="noFilter"><?= lang('ClientePrecios.precio_hora') ?></th>
                                    <th class="noFilter"><?= lang('ClientePrecios.margen') ?></th>
                                    <th class="noFilter"><?= lang('ClientePrecios.total_precio_hora') ?></th>
                                    <th class="noFilter"><?= lang('ClientePrecios.user_updated_id') ?></th>
                                    <th class="noFilter"><?= lang('ClientePrecios.updated_at') ?></th>
                                    <th class="noFilter noVis">plantilla_id</th>
                                    <th class="text-nowrap noFilter noVis" style="min-width:100px"><?= lang('Basic.global.Action') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                            
                            </tbody>
                        </table>   
                    </div>
                    
                </div>

                <div class="tab-pane fade" id="contactos" role="tabpanel">
                    <table id="tableOfClienteContactos"
                           class="table table-striped table-hover" style="width: 100%;">
                        <thead>
                        <tr>
                            <th><?= lang('ClienteContactos.nombre') ?></th>
                            <th><?= lang('ClienteContactos.apellidos') ?></th>
                            <th><?= lang('ClienteContactos.cargo') ?></th>
                            <th><?= lang('ClienteContactos.telefono') ?></th>
                            <th><?= lang('ClienteContactos.email') ?></th>
                            <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>

                <div class="tab-pane fade" id="domicilio-entrega" role="tabpanel">
                    <?= view("themes/vuexy/form/clientes/cliente/_clienteDireccionesForm") ?>
                    <div class="table-responsive">
                        <table id="tableOfDireccionesEnvio" class="table dt-responsive dataTable" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('ClienteDirecciones.alias') ?></th>
                                <th><?= lang('ClienteDirecciones.att') ?></th>
                                <th><?= lang('ClienteDirecciones.email') ?></th>
                                <th><?= lang('ClienteDirecciones.direccion') ?></th>
                                <th><?= lang('ClienteDirecciones.cp') ?></th>
                                <th><?= lang('ClienteDirecciones.municipio') ?></th>
                                <th><?= lang('ClienteDirecciones.provincia') ?></th>
                                <th><?= lang('ClienteDirecciones.pais') ?></th>
                                <th><?= lang('ClienteDirecciones.telefono') ?></th>
                                <th class="text-nowrap" style="min-width:100px;"><?= lang('Basic.global.Action') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="presupuestos" role="tabpanel">
                    <?= view("themes/vuexy/form/clientes/cliente/_presupuestosClienteItems") ?>
                </div>

                <div class="tab-pane fade" id="facturacion" role="tabpanel">
                    <?= view("themes/vuexy/form/clientes/cliente/_facturacionClienteItems") ?>
                </div>

                <div class="tab-pane fade" id="pedidos" role="tabpanel">
                    <?= view("themes/vuexy/form/clientes/cliente/_pedidosClienteItems") ?>
                </div>

                <div class="tab-pane fade" id="usuarios" role="tabpanel">

                    <div class="row align-items-end">

                        <div class="col-md-12 col-lg-4 px-4">
                            <div>
                                <label id="label_usuario" for="usuarios" class="form-label">
                                    <?= lang('Users.usersAvailables') ?>
                                </label>

                                <select id="usuariosDisponibles" name="usuarios_disponibles" class="form-control select2bs2" style="width: 100%;">
                                </select>
                            </div>
                        </div>
                        <div class="col-md-12 col-lg-4 px-4">
                            <button id="addUserToClient" type="button" class="btn btn-secondary waves-effect waves-light float-start"><?= lang("Users.add")?></button>
                        </div>
                    </div>

                    <table id="tableOfClienteUsuarios" class="table table-striped table-hover" style="width: 100%;">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th><?= lang('App.profile_first_name') ?></th>
                            <th><?= lang('App.profile_last_name') ?></th>
                            <th><?= lang('App.profile_email') ?></th>
                            <th class="text-nowrap" style="min-width:100px"><?= lang('Basic.global.Action') ?></th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>

                <?php } ?>

            </div>
        </div>
    </div>

</div>



<?php if ($formAction !== route_to('clienteAdd')){ ?>
<?= $this->section("additionalInlineJs") ?>
/****************************************
    Funcionamiento general
*****************************************/
const url = window.location.href;
const url_parts = url.split('/');
let id = -1;
if(url_parts[url_parts.length-2] == 'edit'){
    id = url_parts[url_parts.length-1];
}

$(document).on('click', '.btn-remove', function(e) {
    
    const dataId = $(this).attr('data-id');
    const tableId = $(this).attr('table-id');
    
    if ($.isNumeric(dataId)) {
        if(tableId=='#tableOfDireccionesEnvio')
            delete_direccion_envio(dataId)
        else if(tableId=='#tableOfPrecios'){
            const row = $(this).attr('row');
            delete_precio(dataId, row)
        }
            
    }
});

<?=$this->endSection() ?>



<?= $this->section("additionalInlineJs") ?>
/****************************************
    Contactos
*****************************************/

    const lastColNr = $('#tableOfClienteContactos').find("tr:first th").length - 1;

    const actionBtns = function(data) {
        return `
                    <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
                    <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-deleted mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
                    <span class="cancel"></span>
                `;
    };

    editor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfClienteContactos') ?>",
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfClienteContactos",
        idSrc:  'id',
        fields: [ {
                name: "nombre"
            }, {
                name: "apellidos"
            }, {
                name: "cargo"
            }, {
                name: "telefono"
            }, {
                name: "email"
            }, {
                "name": "cliente_id",
                "type": "hidden"
            },{
                "name": "deleted_at",
                "type": "hidden"
            }
        ]
    } );

    editor.on( 'preSubmit', function ( e, d, type ) {
        if ( type === 'create'){
            d.data[0]['cliente_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['cliente_id'] = id;
            }
        }
    });


    editor.on( 'postSubmit', function ( e, json, data, action ) {
        yeniden(json.<?= csrf_token() ?>);
    });

    editor.on( 'submitSuccess', function ( e, json, data, action ) {

        theTable.clearPipeline();
        theTable.draw();
    });

    // Activate an inline edit on click of a table cell
    $('#tableOfClienteContactos').on( 'click', 'tbody span.edit', function (e) {
        editor.inline(
            theTable.cells(this.parentNode.parentNode, '*').nodes(),
            {
                cancelHtml: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
                cancelTrigger: 'span.cancel',
                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
                submitTrigger: 'span.edit',
                submit: 'allIfChanged'
            }
        );
    } );

    // Delete row
    $(document).on('click', '.btn-deleted', function(e) {
        $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    });

    $(document).on('click', '.btn-remove', function(e) {
        const dataId = $(this).attr('data-id');
        const row = $(this).closest('tr');
        if ($.isNumeric(dataId)) {
            $.ajax({
                url: `/clientecontactos/delete/${dataId}`,
                method: 'GET',
            }).done((data, textStatus, jqXHR) => {
                $('#confirm2delete').modal('toggle');
                theTable.clearPipeline();
                theTable.row($(row)).invalidate().draw();
                popSuccessAlert(data.msg ?? jqXHR.statusText);
            }).fail((jqXHR, textStatus, errorThrown) => {
                popErrorAlert(jqXHR.responseJSON.messages.error)
            })
        }
    });

	var theTable = $('#tableOfClienteContactos').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25],
        order: [[ 0, "asc" ], [ 1, "asc" ]],
        pageLength: 10,
        lengthChange: true,
        searching: false,
        paging: true,
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfClienteContactos') ?>',
            data: {
                id_cliente: id,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'nombre' },
            { 'data': 'apellidos' },
            { 'data': 'cargo' },
            { 'data': 'telefono' },
            { 'data': 'email' },
            {
                data: actionBtns,
                className: 'row-edit dt-center'
            }
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            },
            {
                "orderData": [ 0, 1 ],
                "targets": 0
            },

        ],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        buttons: [ {
            className: 'btn btn-primary float-end me-sm-3 me-1',
            extend: "createInline",
            editor: editor,
            formOptions: {
                submitTrigger: -1,
                submitHtml: '<i class="ti ti-device-floppy"/>'
            }
        } ]
    } );

<?=$this->endSection() ?>


<?= $this->section("additionalInlineJs") ?>
/****************************************
    Direcciones cliente
*****************************************/
const actionBtns_add = function(data) {
    return `
            <span class="edit-add"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-add mx-2" data-id="${data.id}"></i></a></span>
            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-add mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
            <span class="cancel"></span>
        `;
};

function saveAdd_callback(){
    if($('#addressForm').attr('action')=='create'){
        editorAddress
            .create( false )
            .set( 'cliente_id', id )
            .set( 'alias', $('#add_alias').val() )
            .set( 'att', $('#add_att').val() )
            .set( 'email', $('#add_email').val() )
            .set( 'direccion', $('#add_direccion').val() )
            .set( 'pais_id', $("#add_pais_id option:selected").val())
            .set( 'municipio', $('#add_municipio').val() )
            .set( 'provincia', $('#add_provincia').val() )
            .set( 'cp', $('#add_cp').val() )
            .set( 'telefono', $('#add_telefono').val() )
            .submit();
    }
    else{ // edit
        editorAddress
            .edit( '#tableOfDireccionesEnvio tbody tr:eq('+$("#addressForm").attr('row-index')+ ')', false )
            .set( 'cliente_id', id )
            .set( 'alias', $('#add_alias').val() )
            .set( 'att', $('#add_att').val() )
            .set( 'email', $('#add_email').val() )
            .set( 'direccion', $('#add_direccion').val() )
            .set( 'pais_id', $("#add_pais_id option:selected").val())
            .set( 'municipio', $('#add_municipio').val() )
            .set( 'provincia', $('#add_provincia').val() )
            .set( 'cp', $('#add_cp').val() )
            .set( 'telefono', $('#add_telefono').val() )
            .submit();

    }
}


const editorAddress = new DataTable.Editor({
    ajax: {
        url: "<?= route_to('editorOfClienteDirecciones') ?>",
        headers: {
            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table   : "#tableOfDireccionesEnvio",
    idSrc:  'id',
    fields: [ {
            name: "alias"
        }, {
            name: "att"
        }, {
            name: "email"
        }, {
            name: "direccion"
        }, {
            name: "municipio"
        }, {
            name: "provincia"
        }, {
            name: "pais_id"
        }, {
            name: "cp"
        }, {
            name: "telefono"
        }, {
            "name": "cliente_id",
            "type": "hidden"
        },
    ],
    template: '#direccionesForm'
});

editorAddress.on( 'postSubmit', function ( e, json, data, action ) {
    
    yeniden(json.<?= csrf_token() ?>);

    $( ".error-text-form" ).remove();
    if('fieldErrors' in json){
        if(json.fieldErrors.length > 0){
            json.fieldErrors.forEach((error) => {
                $('#add_' + error.name).after(
                    "<p style='font-size: 11px !important;" +  
                        "padding: 0 !important; " + 
                        "color: #b11f1f !important;' " + 
                        "class='error-text-form'>" + error.status + '</p>')
            })
        }
    }
    else{
        $('#addressForm').modal("hide");        
    }

})

editorAddress.on( 'submitSuccess', function ( e, json, data, action ) {
        
    tableDirecciones.clearPipeline();
    tableDirecciones.draw();
});

editorAddress.on( 'close', function ( e, json, data, action ) {
    $('#tableOfDireccionesEnvio').DataTable().ajax.reload();
})

const lastColNr2 = $('#tableOfDireccionesEnvio').find("tr:first th").length - 1;

var tableDirecciones = $('#tableOfDireccionesEnvio').DataTable( {
		draw:2,
        serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        order: [0, "asc" ],
        pageLength: 10,
        lengthChange: false,
        searching: false, 
        paging: true, 
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfClienteDirecciones') ?>',
            data: function ( d ) {
                d.cliente_id = id;
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'alias' },
            { 'data': 'att' },
            { 'data': 'email' },
            { 'data': 'direccion' },
            { 'data': 'cp' },
            { 'data': 'municipio' },
            { 'data': 'provincia' },
            { 'data': 'pais_id'  ,
                "render": function (data, type, row, meta) {
                    return row.pais;
                }},
            { 'data': 'telefono' },
            {
                data: actionBtns_add,
                className: 'row-edit dt-center'
            }
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr2]
            },
            {"orderData": [ 0],    "targets": 0 },

        ],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        buttons: [ {
            className: 'btn btn-primary float-end me-sm-3 me-1',
            text: "<?= lang('Basic.global.addNew'); ?>",
            action: function ( e, dt, node, config ) {
                $("#addressForm").attr('action','create')
                var $newAddDialog = $("#addressForm")
                $newAddDialog.modal('show')
            }
        } ]
    } );


$('#tableOfDireccionesEnvio').on( 'click', 'tbody span.edit-add', function (e) {
    
    const row = $(this).closest('tr');
    const data = tableDirecciones.row(row).data() 
    
    $("#addressForm").attr('action','edit')
    $("#addressForm").attr('row-index',row[0]._DT_RowIndex)
    
    $('#add_alias').val(data.alias)
    $('#add_att').val(data.att)
    $('#add_email').val(data.email)
    $('#add_direccion').val(data.direccion)
    $("#add_pais_id").val(data.pais_id).change()
    $('#add_municipio').val(data.municipio)
    $('#add_provincia').val(data.provincia)
    $('#add_cp').val(data.cp)
    $('#add_telefono').val(data.telefono)
    
    var $newAddDialog = $("#addressForm")
    $newAddDialog.modal('show')
})

$(document).on('click', '.btn-delete-add', function(e) {
    $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    $(".btn-remove").attr('table-id', '#tableOfDireccionesEnvio');
});

function delete_direccion_envio(dataId){
    $.ajax({
        url: `/clientes/clientedirecciones/delete/${dataId}`,
        method: 'GET',
    }).done((data, textStatus, jqXHR) => {
        $('#confirm2delete').modal('toggle');
        tableDirecciones.clearPipeline();
        tableDirecciones.ajax.reload();
        popSuccessAlert(data.msg ?? jqXHR.statusText);
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.responseJSON.messages.error)
    })
}

<?=$this->endSection() ?>


<?=$this->section('css') ?>
    <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.bootstrap5.min.css') ?>">
    <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
    <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-bs5/datatables.bootstrap5.css") ?>">
    <link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.css') ?>" />
<?=$this->endSection() ?>

<?= $this->section('additionalExternalJs') ?>
    <script src="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.js') ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
    <script src="<?= site_url('themes/vuexy/js/datatables-editor/dataTables.editor.min.js') ?>"></script>
    <script type="module" src="<?= site_url("assets/js/safekat/pages/cliente/clienteFacturacion.js") ?>"></script>
<?=$this->endSection() ?>
<?php } ?>



