<?php

use yii\helpers\Html;
use yii\grid\GridView; // Cambiado de kartik\grid\GridView a yii\grid\GridView
use yii\web\View;
use yii\widgets\ActiveForm;
$baseUrl = Yii::$app->getUrlManager()->getBaseUrl();
/* @var $this yii\web\View */
/* @var $searchModel app\models\ClienteSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Clientes';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="cliente-index">

    <?php $form = ActiveForm::begin([
    'options' => ['enctype' => 'multipart/form-data'],
        'id' => 'cliente-form',
        'enableClientValidation' => false,
    ]); ?>    
    <section class="content" style="min-height:100px!important;padding-bottom: 0px!important">
        <div class="box card">    
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                    <div class="">
                        <i class="fa fa-file-o"></i>
                        <label>Cargar archivo</label>
                        <input type="hidden" name="bodega_id" id="bodega_id_hidden">
                        <input id="fileSelect" type="file" accept=".xlsx" name="archivo" class="p-0 form-control" />
                    </div>
                    </div>
                </div>
            </div>
            <div class="box-footer card-footer">
            <?= Html::button('Descargar Template', ['id' => 'btn_devolucion', 'class' => 'butt btn btn-info py-1 px-2', 'onclick' => 'fn_template()']) ?>
            <?= Html::button('Procesar archivo', ['id' => 'btn_procesar', 'class' => 'butt btn btn-success py-1 px-2', 'onclick' => 'fn_upload()']) ?>
            </div> 
        </div>
    </section>   

    <?php ActiveForm::end(); ?>       

    <p>
        <?= Html::a('Crear Cliente', ['create'], ['class' => 'btn btn-success']) ?>
        
        <?= Html::a('Descargar Ruta', 'javascript:void(0);', ['class' => 'btn btn-info','onclick' => 'fn_getruta()']) ?>
        
        <?= Html::a('Descargar Inventario', 'javascript:void(0);', ['class' => 'btn btn-warning','onclick' => 'fn_getinventario()']) ?>
    </p>    

<?php

// Definición de columnas para el GridView estándar
$columns = [
    ['class' => 'yii\grid\SerialColumn'],

    [
        'attribute' => 'codigo',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ],

    [
        'attribute' => 'nombre',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ],  
    
    [
        'attribute' => 'contacto',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ], 
    
    [
        'attribute' => 'tipo',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ],    
    
    [
        'attribute' => 'fecha_exhibidor',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ],
    
    [
        'attribute' => 'fecha_registro',
        'headerOptions' => ['class' => 'text-center'],
        'contentOptions' => ['class' => 'text-center']
    ],

    [
        'class' => 'yii\grid\ActionColumn',
        'template' => '{update} {delete}',
        'buttons' => [
            'update' => function ($url, $model, $key) {
                return Html::a('<i class="bi bi-pencil"></i>', $url, [
                    'title' => 'Actualizar',
                    'data-pjax' => '0',
                    'class' => 'btn btn-sm btn-primary',
                ]);
            },
            'delete' => function ($url, $model, $key) {
                return Html::a('<i class="bi bi-trash"></i>', $url, [
                    'title' => 'Eliminar',
                    'data-pjax' => '0',
                    'data-confirm' => '¿Está seguro de eliminar este elemento?',
                    'data-method' => 'post',
                    'class' => 'btn btn-sm btn-danger',
                ]);
            },
        ],
    ]
];

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $columns,
    'options' => ['class' => 'table-responsive'],
    'tableOptions' => ['class' => 'table table-striped table-bordered'],
    'pager' => [
        'options' => ['class' => 'pagination justify-content-end'],
        'linkContainerOptions' => ['class' => 'page-item'],
        'linkOptions' => ['class' => 'page-link']
    ],
    'summary' => '<div class="summary">Mostrando <b>{begin}-{end}</b> de <b>{totalCount}</b> elementos</div>',
    'layout' => "{summary}\n{items}\n<div class='card-footer clearfix'>{pager}</div>",
]);

?>
</div>

<?php
$this->registerJs('  

function fn_upload(){

    Swal.fire({
      title: "¿Está seguro de cargar el archivo seleccionado?",
      icon: "question",
      showCancelButton: true,
      confirmButtonText: "Cargar",
      cancelButtonText: "Cancelar",
    }).then((result) => {
      if (result.isConfirmed) {
        var url = "' . $baseUrl . '/cliente/upload";
        $(".se-pre-con").fadeIn("slow");
        const formElement = document.getElementById("cliente-form");
        const request = new XMLHttpRequest();
        request.open("POST", url);
        request.onload = function() {
            if (this.status == 200) {
               $(".se-pre-con").fadeOut("slow");
               var resp = JSON.parse(this.response);
               if(resp.error){
                  show_message(resp.message);
               }else{
                Swal.fire({	
                  title:"Mensaje",
                  html: resp.message,
                  icon: "warning",
                  allowEscapeKey: false,
                  allowOutsideClick: false,
                  confirmButtonText: "Aceptar",
                }).then((result) => {
                    if (result.isConfirmed) {		
                      window.location.reload();    		    				
                    }
                });	                  
               }
            }
        }
        request.send(new FormData(formElement)); 
      } else if (result.dismiss === Swal.DismissReason.cancel) {
        Swal.fire("Cancelado", "No se guardaron los datos", "error");
      }
    })
}

  function show_message(message){
      Swal.fire({	
        title:"Mensaje",
        html: message,
        icon: "warning",
        allowEscapeKey: false,
        allowOutsideClick: false,
        confirmButtonText: "Aceptar",
        onAfterClose: () => window.scrollTo(0,0)
      }).then((result) => {
          if (result.isConfirmed) {		    		    				
          }
      });	
  }

  function fn_template(){
    var url = "'.$baseUrl.'/template/plantilla_cliente.xlsx";
    window.open(url, "_blank");
  }    
  
  function fn_getruta(){
    var url = "' . $baseUrl . '/cliente/export-ruta";
    location.href = url;
  }  
  
  function fn_getinventario(){
    var url = "' . $baseUrl . '/cliente/export-inventario";
    location.href = url;
  }    

', View::POS_END);
?>