<?php
class VentaForm extends Form {
    public function __construct() {
        $this->setName('venta');
        $this->setActionForm('Venta.php');
        $this->setMethod('post');
        $this->setClass('venta');
        parent::__construct();
        $this->init();
    }

    public function init() {        
        $attributes_wrapper_append_select = array('class'=>'select2-bootstrap-append');
        /*Se utiliza para consulta si existe en la tabla de ventasdetalles_X, si existe se actualiza registro.*/
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'idDetalleTemp',
            'required'=>false
        ));
        
        $settings = new SettingsEntity();
        $panPorLibra = $settings->_get('id_pan_por_libra'); 

        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'id_pan_por_libra',
            'value'=>$panPorLibra
        ));    
        
        /*Se almacena id de venta que se acba de realizar, y se ocupa para imprimir o mandar por email*/
         $this->addElement(array(
            'type' => 'hidden',
            'name' => 'last_sale_id',
        ));    
         
         /*Se utiliza cuando se edita los detalles de venta. Aqui se setea la cantidad original from ventasdetalles_X*/
         $this->addElement(array(
            'type' => 'hidden',
            'name' => 'cantidadOrigen',
        ));                 

        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'subtotal',
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'total_venta',
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'sale_only_for_adult',
        ));
         
         /*id_sepecial_requisition; cuando se hacen pagos de Special requisition*/
         $this->addElement(array(
            'type' => 'hidden',
            'name' => 'id_special_requisition',
            'value'=>'0'
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'fecha',
            'label'=>'Fecha',
            'optionals'=>array('style'=>'width:100px','onChange'=>'setFechaPagoVenta()'),
            'value'=>date('m/d/Y'),
            'validators'=>array('date'),
            'required'=>true
        ));
        
        $append = "<span style='width:20px'; class = 'btn input-group-addon' data-toggle='modal' data-target='#modalAgregarClientePos'><i class='fa fa-plus'></i></span>";     
        $this->addElement(array(
            'type' => 'select',
            'name' => 'cliente',
            'label'=>'Cliente',
            'multiOptions'=>$this->listClientes(),
            'optionals'=>array('onChange'=>'setMetodoPago()'),
            'value'=>'1',
            'required'=>true,
            'class'=>'selectCliente', // Clase para selecto cuando se agrega un nuevo proveedor y se recarga lista.
            'append'=>$append,
            'wrapper_attributes'=>$attributes_wrapper_append_select,
            'col-size-element'=>'12'
        )); 
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'telefono',
            'label'=>'Telefono',
            'optionals'=>array('placeholder'=>'Telefono'),
            'col-size-element'=>'12',
            'required'=>false
        ));   
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'guardarCliente',
            'value'=> $this->_getTranslation('Guardar'),
            'class'=>'btn btn-primary',
            'optionals'=>array('onclick'=>'saveCliente()'),
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'idVentaReimprimir',
            'label'=>'Venta #',
            'required'=>false
        ));   
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'descuentoItems',
            'required'=>false
        ));
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'descuentoOrden',
            'required'=>false
        ));
        
        $append = "<div class='input-group-btn'>
                    <select class='form-control' id='descuento_orden_tipo' name='descuento_orden_tipo'>
                      <option value='porcentaje'>Porcentaje</option>
                      <option value='monto'>Monto</option>
                    </select>
                  </div>";
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'descuento_orden_valor',
            'label'=>'Descuento',
            'required'=>true,
            'append'=>$append,
            //'class'=>'numPad'
            /*'optionals'=>array(
                'readonly'=>true
            )*/
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'referencia_venta_suspendida',
            'label'=>'Referencia',
            'required'=>true
        ));
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'idProducto',
        ));
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'idProducto_detalle',
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'producto',
            'label'=>'Producto',
            'optionals'=>array('onKeyPress'=>'onEnterPos(event.keyCode,this)','placeholder'=>'Teclea o escanea producto para venta'),
            'col-size-element'=>'12',
        ));
        
        $attributes_wrapper_cantidad = array('class'=>'input-prepend input-append');
        //$prepend = "<span class='input-group-addon'><i class='fa fa-minus'></i></span>";   
        $append = "<span class='input-group-addon _addClassCalculator'><i class='fa fa-calculator'></i></span>";    
        $this->addElement(array(
            'type' => 'text',
            'name' => 'cantidad',
            'label'=>'Cantidad',
            'value'=>1,
            'wrapper_attributes'=>$attributes_wrapper_cantidad,
            //'prepend'=>$prepend,
            'append'=>$append,
            'required'=>true,
            //'class'=>'numPad'
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'precio',
            'label'=>'Precio',
            'required'=>false,
            'class'=>'numPad'
        ));
        
        $append = "<div class='input-group-btn'>
                    <select class='form-control' name='descuento_item_tipo'>                    
                      <option value='porcentaje'>Porcentaje</option>".
                      //<option value='monto'>Monto</option>
                    "</select>
                  </div>";
        
           
       $this->addElement(array(
            'type' => 'text',
            'name' => 'descuento_item_valor',
            'label'=>'Descuento',
            'required'=>true,
            'append'=>$append,
            'class'=>'numPad',
           'optionals'=>array(
               'readonly'=>true
           )
        ));
        
        $this->addElement(array(
            'type' => 'select',
            'name' => 'impuestos',
            'label'=>'Impuestos',
            'multiOptions'=>$this->listaImpuestos(),
            'append'=>$append,
            'required'=>false
        ));
        
        
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'punitariocompra',
            'required'=>false
        ));
        
        $this->addElement(array(
            'type' => 'hidden',
            'name' => 'comentarios',
        ));
        
        $this->addElement(array(
            'type' => 'textarea',
            'name' => 'comentariosTemp',
            'label'=>'Agregar comentario',
            'optionals'=>array('style'=>'width:565px;height:98px')
        ));
        
        $this->addElement(array(
            'type'=>'select',
            'name'=>'metodo_pago',
            'label'=>'Metodo de pago',
            'multiOptions'=>$this->listMetodosPago(),
            'optionals'=>array('style'=>'width:160px','onChange'=>'onChangeMetodoPagoVenta()')
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'diasCredito',
            'label'=>'Periodo de credito',
            'optionals'=>array('style'=>'width:100px','onBlur'=>'setFechaPagoVenta()','readOnly'=>'true')
        ));
        
        $this->addElement(array(
            'type' => 'text',
            'name' => 'fecha_pago',
            'label'=>'Fecha de pago',
            'optionals'=>array('style'=>'width:100px','readOnly'=>'true')
        ));
        
        /*Existe un boton guardar que se ocupa al momento de guardar el cobro 'Agregar', pero ese es del CobroForm.*/
        $this->addElement(array(
            'type'=>'button',
            'name'=>'guardar',
            'value'=>$this->_getTranslation('Guardar'),
            'class'=>'btn btn-primary',
            'optionals'=>array("onClick"=>"setVentaPos();$('#modalEditarProducto').modal('hide')"),
            'col-size-element'=>'12',
        ));       
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'cerrar',
            'value'=> $this->_getTranslation('Cerrar'),
            'class'=>'btn btn-default',
            'optionals'=>array(
                'data-dismiss'=>'modal',
                'aria-hidden'=>'true',
                ),
            'col-size-element'=>'6',
        ));
        
        $login = new Login();
        if($login->getRole() == '1'){$onclick = "reimprimirTicketVenta();";}
        else{$onclick = " confirmarAccion('reemprimir_ticket',function(){ reimprimirTicketVenta();})";}
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'btnReimprimirTicket',
            'value'=> $this->_getTranslation('Reimprimir'),
            'class'=>'btn btn-primary',
            'optionals'=>array(
                'data-dismiss'=>'modal',
                'aria-hidden'=>'true',
                'onclick'=>$onclick
                ),
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'aplicarDescuento',
            'value'=> $this->_getTranslation('Aplicar'),
            'class'=>'btn btn-primary',
            'optionals'=>array('onclick'=>'setDescuento()'),
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'cerrarDescuento',
            'value'=> $this->_getTranslation('Cerrar'),
            'class'=>'btn btn-default',
            'optionals'=>array('onclick'=>"$('#modalAgregarDescuento').modal('hide')"),
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'cancelarDescuento',
            'value'=> $this->_getTranslation('Eliminar'),
            'class'=>'btn btn-default',
            'optionals'=>array('onclick'=>'cancelDescuento()'),
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type'=>'button',
            'name'=>'btnSuspenderVenta',
            'value'=>$this->_getTranslation('Suspender'),
            'class'=>'btn btn-primary',
            'optionals'=>array("onClick"=>"suspenderVenta();$('#modalSuspenderVenta').modal('hide');"),
            'col-size-element'=>'12',
        ));       
        
        $this->addElement(array(
            'type'=>'button',
            'name'=>'terminar',
            'value'=>$this->_getTranslation('Terminar'),
            'class'=>'btn btn-primary',
            'optionals'=>array("onClick"=>"saveVentaPos();"),
            'col-size-element'=>'6',
        ));       
        
        $this->addElement(array(
            'type' => 'button',
            'name' => 'cerrarPago',
            'value'=> $this->_getTranslation('Cancelar'),
            'class'=>'btn btn-default setCursor',
            'optionals'=>array(
                'onclick'=>'clearModalCobros()'),
            'col-size-element'=>'6',
        ));
        
        $this->addElement(array(
            'type'=>'button',
            'name'=>'guardarDevolucion',
            'value'=>$this->_getTranslation('Guardar'),
            'class'=>'btn btn-primary',
            'optionals'=>array("onClick"=>"saveDevolucion();$('#modalDevolucion').modal('hide');"),
            'col-size-element'=>'12',
        ));         
        
         $this->addElement(array(
            'type' => 'button',
            'name' => 'cerrarDevolucion',
            'value'=> $this->_getTranslation('Cancelar'),
            'class'=>'btn btn-default',
            'optionals'=>array(
                'data-dismiss'=>'modal',
                'aria-hidden'=>'true',
                'onclick'=>'clearModalDevolucion()'),
            'col-size-element'=>'6',
        ));
        
        /* Para Devoluciones */
        
         /*Se utiliza para capturar id de Venta que se usara para generar devolucion*/
        $append = "<span class = 'btn input-group-addon' onclick='setVentaDetallesDevolucion();'><i class='fa fa-search'></i> Buscar</span>";     
         $this->addElement(array(
             'type'=>'text',
             'name'=>'idVentaDevolucion',
             'label'=>'Numero de transaccion',
             'optionals'=>array('onKeyPress'=>'onEnterPos(event.keyCode,this)'),
             'col-size-element'=>'12',
             'append'=>$append
         ));
         
         $this->addElement(array(
             'type'=>'hidden',
             'name'=>'idPagoDevolucion'
         ));
         
        $this->addElement(array(
            'type' => 'select',
            'name' => 'formaPagoDevolucion',
            'label'=>'Forma de pago',
            'multiOptions'=>$this->listaFormasDePago(),
            'value'=>'1',
            'required'=> true
        ));
         
         $this->addElement(array(
             'type'=>'text',
             'name'=>'montoDevolucion',
             'label'=>'Monto',
             'class'=>'numPad'
         ));
         
         $this->addElement(array(
             'type'=>'text',
             'name'=>'numDocumentoDevolucion',
             'label'=>'Referencia'
         ));
         
         $this->addElement(array(
             'type'=>'textarea',
             'name'=>'notasDevolucion',
             'label'=>'Notas'
         ));
         
        $this->addElement(array(
            'type'=>'button',
            'name'=>'guardarPagoDevolucion',
            'value'=>$this->_getTranslation('Agregar'),
            'optionals'=>array('onclick'=>'setPagoDevolucionTemp()'),
            'class'=>'btn btn-primary',
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type'=>'button',
            'name'=>'guardarDevolucion',
            'value'=>$this->_getTranslation('Terminar'),
            'optionals'=>array('onclick'=>'saveDevolucion()'),
            'class'=>'btn btn-primary',
            'col-size-element'=>'12',
        ));
        
        $this->addElement(array(
            'type'=>'button',
            'name'=>'agregarPagoDevolucion',
            'value'=>$this->_getTranslation('Agregar pago'),
            'optionals'=>array('onclick'=>"$('#modalPagoDevolucion').modal('show');",'disabled'=>'true'),
            'class'=>'btn btn-info',
            'col-size-element'=>'12',
        ));
        
    }
    
    public function listClientes(){
        $repository = new ClienteRepository();
        $result = $repository->getListaSelectClientes();
        
        $array = array();
        if ($result) {
            foreach ($result as $key => $value) {
                $array[$key] = $value;
            }
            return $array;
        }
    }
    
     public function listCuentasContables(){
        $repository = new CatalogoCuentaRepository();
        // parametro '2' es para filtrar cuentas de clase Expense = Gastos
        $result = $repository->getFillCuentas();
        
        if ($result) {
            $array = array('');
            foreach ($result as $key => $value) {
                $array[$key] = $value;
            }
            return $array;
        }
    }
    
    public function getListProductos(){
        $repository = new ProductoRepository();
        $productos = $repository->getListVentaProductos();
        
        $array = array('');
        foreach($productos as $producto){          
            $array[$producto['id']] = $producto['descripcion']." (".$producto['codigo'].")";
        }
        
        $list= array();
        foreach ($array as $key => $value) {
            $list[$key] = $value;
        }
        return $list;
    }
    
    public function listaImpuestos(){            
        $repository = new ImpuestosRepository();
        $result = $repository->getListaSelectImpuestos();
        
        $array = array('0' => 'Seleccionar una opcion...');
        if ($result) {            
            foreach ($result as $key => $value) {
                $array[$key] = $value;
            }
            return $array;
        }
    }   
    
    public function listMetodosPago(){
        $repository = new FormaMetodoPagoRepository();
        $result = $repository->getListMetodosPago();
        
        if ($result) {
            $array = array(0 => 'Seleccionar una opcions...');
            $array = array();
            foreach ($result as $key => $value) {
                $array[$key] = $value;
            }
            return $array;
        }
    }
    
    public function getListaCategorias(){
        $repository = new CategoriaRepository();
        return $repository->getListaSelectCategorias('Producto');
    }
    
    public function getListaProductos(){
        $repository = new ProductoRepository();
        return $repository->getListaProductos();
    }
    
    public function listaFormasDePago(){
        $repository = new FormaMetodoPagoRepository();
        $result = $repository->getListFormasPago();
        
        if ($result) {
            //$array = array(null => 'Seleccionar una opcion...');
            $array = array();
            foreach ($result as $key => $value) {
                $array[$key] = $value;
            }
            return $array;
        }
    }
    
    public function populate($data) {
        $tools = new Tools();
        if(isset($data['fecha']) && $tools->isValidaDateYYYMMDD($data['fecha'])){
            $data['fecha'] = $tools->setFormatDateToForm($data['fecha']);
        }
        if(isset($data['fecha_pago']) && $tools->isValidaDateYYYMMDD($data['fecha_pago'])){
            $data['fecha_pago'] = $tools->setFormatDateToForm($data['fecha_pago']);
        }
        
        if(isset($data['metodo_pago']) && $data['metodo_pago'] == '1'){
            $this->addOptionals('diasCredito', array('disabled'=>'disabled'));
        }

        parent::populate($data);
    }
}