<?php
/**
 * Description of PFAAjax
 *
 * @author carlos
 */
class PosAjax extends VentaRepository
{
    private $formCliente = null;

    private function getClienteForm()
    {
        if ($this->formCliente === null) {
            $this->formCliente = new ClienteForm();
        }
        return $this->formCliente;
    }

    public function getResponse($request, $options)
    {
        return $this->$request($options);
    }

    public function isSpecialRequisition()
    {
        $detalles = $this->getVentaDetalles();
        if ($detalles) {
            foreach ($detalles as $detalle) {
                if ($detalle['idProducto'] == '0') {
                    $repo = new SpecialRequisitionRepository();
                    # Descripcion de para pago de SpecialREquisition en el POS siempre debe llevar el simbolo '#'seguido del numero de special requisition
                    $reqNumber = explode('#', $detalle['descripcion']);
                    $reqData = $repo->getByReqNumber($reqNumber[1]);
                    if ($reqData) {
                        return $reqData['id'];
                    }
                }
            }
        }
        return null;
    }

    public function setVentaDetalles(array $data)
    {
        $options = array();
        foreach ($data['options'] as $row) {
            $options[$row['name']] = $row['value'];
        }

        #Cuando se da enter en el campo producto del POS, el producto se busca por codigo, 
        #el valor del codigo ingresado se almacena en idProducto
        if (isset($data['byCode'])) {
            $result = $this->getProductoByCode($options['idProducto']);
            if ($result) {
                $options['idProducto'] = $result['id'];
            }
        }

        /*PCG CODE*/
        #En pagos de specialRequisition no se pueden agregar productos desde el POS, deben agregar desde specialRequisition
        $idSpecialRequisition = $this->isSpecialRequisition();
        if ($idSpecialRequisition && $options['idProducto'] != '0') {
            $this->flashmessenger->addMessage(array('info' => "Oops.!! Lo siento. Para agregar un producto <br>debes ingresar a la <a href='/Controller/Special-requisition.php?action=edit&id=$idSpecialRequisition'>Orden Especial"));
            return $json = array(
                'response' => null,
                'message' => $this->flashmessenger->getMessageString()
            );
        }
        /* END PCG CODE*/

        $producto = $this->getProductoById($options['idProducto']);
        /*PCG CODE*/
        #producto = 0 es para requisiciones especiales
        if ($options['idProducto'] == '0') {
            $producto = true;
        }
        /* END PCG CODE*/
        if ($producto) {
            if ($options['idDetalleTemp'] != '' && $options['idDetalleTemp'] != null) {
                $data = array(
                    'idDetalleTemp' => $options['idDetalleTemp'],
                    'idProducto' => $options['idProducto'],
                    #'descripcion'=>$options['descripcion'],
                    'cantidad' => $options['cantidad'],
                    'precio' => $options['precio'],
                    'descuento_item_tipo' => $options['descuento_item_tipo'],
                    'descuento_item_valor' => $options['descuento_item_valor'],
                    'descuento_orden_tipo' => $options['descuento_orden_tipo'],
                    'descuento_orden_valor' => $options['descuento_orden_valor'],
                    #Anteriormente enviaba 'impuestos' que se mostraba en modal de edicion del producto (Anteriormente se podia modificar este campo)
                    #Pero ahora el campo 'impuestos' no se muestra en modal (Ya no se puede editar en la venta), entonces lo traemos de la tabla productos
                    #'impuestos'=>$options['impuestos'],
                    'impuestos' => $producto['impuestos'],
                    'impuestos_incluidos' => $producto['impuestos_incluidos']
                );

                /*PCG CODE*/
                #producto = 0 es para requisiciones especiales
                if ($options['idProducto'] == '0') {
                    $data['impuestos'] = 1;
                    $data['impuestos_incluidos'] = 'no';
                }
                /* END PCG CODE*/

            } else {
                $data = array(
                    'idDetalleTemp' => $options['idDetalleTemp'],
                    'idProducto' => $producto['id'],
                    'descripcion' => $producto['descripcion'],
                    'cantidad' => $options['cantidad'],
                    'precio' => $producto['punitarioventa'],
                    'descuento_item_valor' => $producto['descuento'],
                    'impuestos' => $producto['impuestos'],
                    'impuestos_incluidos' => $producto['impuestos_incluidos'],
                    'descuento_item_tipo' => $options['descuento_item_tipo'], # Se debe cambiar $options por $producto , pero primero se debe agregar la opcion para configurar descuento en productos
                    'descuento_item_valor' => $options['descuento_item_valor'], # Se debe cambiar $options por $producto, pero primero se debe agregar la opcion para configurar descuento en productos
                    'descuento_orden_tipo' => $options['descuento_orden_tipo'],
                    'descuento_orden_valor' => $options['descuento_orden_valor'],
                );
            }


            $ventasDetallesTemp = new VentaDetallesTempRepository();
            $ventasDetallesTemp->save($data);

            //$this->insertDetalle($data);

            /*Si existe Descuento de orden por Monto se aplica despues de insertar el producto
              Se calcula el descuento para todos los productos */
            if ($data['descuento_orden_tipo'] == 'monto' && trim($data['descuento_orden_valor']) != '') {
                $this->setDescuentoOrden($data);
            }

            $ventaDetalles = $this->getVentaDetalles();
            $detalles = $this->listVentaDetalles($ventaDetalles, $options['descuento_orden_tipo']);

            /*Esto es solo cuando se inserta nuevo producto*/
            $showModal = false;
            $settings = new SettingsEntity();
            $panPorLibra = $settings->_get('id_pan_por_libra');
            if ($panPorLibra == $data['idProducto']) {
                $showModal = true;
            }
            $lastIdInsertForSale = $ventasDetallesTemp->getLastInsertId();

            $json = array(
                'response' => true,
                'ventaDetalles' => $detalles['listDetalles'],
                'subtotal' => $detalles['subtotal'],
                'montoTotal' => $detalles['montoTotal'],
                'impuestosTotal' => $detalles['impuestosTotal'],
                'descuentoOrden' => $detalles['descuentoOrden'],
                'descuentoItems' => $detalles['descuentoItems'],
                'descuentoTotal' => $detalles['descuentoTotal'],
                'regularPrice' => $detalles['regularPrice'],
                'itemsTotal' => $detalles['itemsTotal'],
                'lastInsertId' => $lastIdInsertForSale,
                'showModal' => $showModal,
                'venta_solo_para_mayores' => $detalles['venta_solo_para_mayores']
            );

            return $json;
        } else {
            $this->flashmessenger->addMessage(array('info' => 'Producto no registrado.'));
            return $json = array(
                'response' => null,
                'message' => $this->flashmessenger->getMessageString()
            );
        }
    }

    public function setDescuentoOrden($options)
    {
        if ($options['descuento_orden_tipo'] == 'monto') {
            $ventasDetallesTemp = new VentaDetallesTempRepository();
            $options['descuento_orden_valor'] = $ventasDetallesTemp->getPorcentajeDescuentoDandoMonto($options['descuento_orden_valor']);
        }

        parent::setDescuentoOrden($options);
        return $this->getListVentaDetalles();
    }

    public function cancelDescuentoOrden($options = null)
    {
        parent::setDescuentoOrden(array('descuento_orden_valor' => ''));
        return $this->getListVentaDetalles();
    }

    public function listVentaDetalles($detalles, $descuentoOrdenTipo = null, $descuentoOrden = null)
    {
        $listDetalles = "";
        $montoTotal = 0;
        $montoImpuestos = 0;
        $descuentoOrdenTotal = 0;
        $descuentoItemTotal = 0;
        $descuentoTotal = 0;
        $itemsTotal = 0;
        $totalRegularPrice = 0;
        $sale_only_for_adults = 0;

        foreach ($detalles as $detalle) {
            $regularPriceString = '';
            $id = $detalle['id'];
            unset($detalle['id']);

            if ($detalle['venta_solo_para_mayores'] == '1') {
                $sale_only_for_adults = 1;
            }

            $itemsTotal += $detalle['cantidad'];
            //$total = $detalle['cantidad'] * $detalle['precio_sin_impuestos'];
            $total = (float) $detalle['subtotal'];

            $regularPrice = $total;
            $totalRegularPrice += $total;

            //$total -= $detalle['descuento_item_monto'];
            //$total -= $detalle['descuento_orden_monto'];

            $descuentoItemTotal += (float) $detalle['descuento_item_monto'];
            $descuentoOrdenTotal += (float) $detalle['descuento_orden_monto'];

            if ($detalle['descuento_item_monto'] !== '0') {
                $regularPriceString = "<br><span style='color:#aaa;font-size: 10px'>Reg. $regularPrice</span>";
            } elseif ($detalle['descuento_orden_monto'] !== '0') {
                $regularPriceString = "<br><span style='color:#aaa;font-size: 10px'>Reg. $regularPrice</span>";
            }

            $montoTotal += $total;
            $montoImpuestos += (float) $detalle['impuestos_monto'];

            # $detalle['idProducto'] == '0' Significa Pago de specialRequisition; y siempre debe existir un solo registro en la tabla ventasdetalles
            if ($detalle['idProducto'] == '0') {
                $idSpecialRequisition = $this->isSpecialRequisition();
                $listDetalles .= ""
                    . "<tr>"
                    . "<td class='text-center' style='width:10%'>" . $detalle['cantidad'] . "</td>"
                    . "<td style='width:60%'>"
                    . "<a href='/Controller/Special-requisition.php?action=edit&id=$idSpecialRequisition'>" . $detalle['descripcion'] . "</a>"
                    . "</td>"
                    . "<td class='text-right' onclick='setProductToEdit(this)' data-toggle='modal' data-target='#modalEditarProducto' data-idproduct='$id' style='width:20%'>$" . number_format($total, 2) . "</td>"
                    . "<td></td>";
            } else {
                $listDetalles .= ""
                    . "<tr>"
                    . "<td class='text-center' style='width:10%'>" . $detalle['cantidad'] . "</td>"
                    . "<td  style='width:60%' onclick='setProductToEdit(this)' data-toggle='modal' data-target='#modalEditarProducto' data-idproduct='$id'>" . $detalle['descripcion'] . "</td>"
                    . "<td class='text-right' style='width:20%' onclick='setProductToEdit(this)' data-toggle='modal' data-target='#modalEditarProducto' data-idproduct='$id'>$" . number_format($total, 2) . "$regularPriceString</td>";

                #Esto no se agrega a pagos de SpecialRequisition, porque no debe eliminarse producto, debe pagarse tal como esta configurado.
                #El precio si se puede cambiar

                $listDetalles .= "<td style='width:5%'><a class='btn btn-sm btn-danger' onclick='deleteDetallesVenta($id);'><i class='fa fa-trash'></i></a></td>";
            }
            $listDetalles .= "</tr>";
        }

        $descuentoTotal = $descuentoItemTotal + $descuentoOrdenTotal;
        $subtotal = $montoTotal;
        $montoTotal = $montoTotal + $montoImpuestos;

        return array(
            'listDetalles' => $listDetalles,
            'subtotal' => round($subtotal, 2),
            'montoTotal' => round($montoTotal, 2),
            'impuestosTotal' => round($montoImpuestos, 2),
            'descuentoOrden' => $descuentoOrdenTotal,
            'descuentoItems' => $descuentoItemTotal,
            'descuentoTotal' => $descuentoTotal,
            'regularPrice' => round($totalRegularPrice, 2),
            'itemsTotal' => $itemsTotal,
            'venta_solo_para_mayores' => $sale_only_for_adults
        );
    }

    public function getListVentaDetalles($options = null)
    {
        $descuentoOrdenTipo = null;
        if (isset($options['descuento_orden_tipo'])) {
            $descuentoOrdenTipo = $options['descuento_orden_tipo'];
        }

        $ventaDetalles = $this->getVentaDetalles();
        $detalles = $this->listVentaDetalles($ventaDetalles, $descuentoOrdenTipo);
        $json = array(
            'response' => true,
            'ventaDetalles' => $detalles['listDetalles'],
            'subtotal' => $detalles['subtotal'],
            'montoTotal' => $detalles['montoTotal'],
            'impuestosTotal' => $detalles['impuestosTotal'],
            'descuentoOrden' => $detalles['descuentoOrden'],
            'descuentoItems' => $detalles['descuentoItems'],
            'descuentoTotal' => $detalles['descuentoTotal'],
            'regularPrice' => $detalles['regularPrice'],
            'itemsTotal' => $detalles['itemsTotal'],
            'venta_solo_para_mayores' => $detalles['venta_solo_para_mayores']
        );

        return $json;
    }

    public function getListVentasSuspendidas($options = null)
    {
        $ventasSuspendidas = $this->getVentasSuspendidas();
        $listDetalles = "";

        if ($ventasSuspendidas) {
            foreach ($ventasSuspendidas as $detalle) {
                $id = $detalle['id'];

                $listDetalles .= "<tr>"
                    . "<td style='width:35%'>{$detalle['referencia']}</td>"
                    . "<td style='width:35%' class='text-right'>$" . number_format($detalle['total_venta'], 2) . "</td>"
                    . "<td style='width:30%' class='text-right'>"
                    . "<a class='btn btn-default' onclick='activarVentaSuspendida($id)'><i class='fa fa-pencil'></i></a> "
                    . "<a class='btn btn-danger' onclick='deleteVentaSuspendida($id);'><i class='fa fa-trash'></i></a>"
                    . "</td>"
                    . "</tr>";
            }
        }
        $json = array(
            'response' => true,
            'ventasSuspendidas' => $listDetalles
        );

        return $json;
    }

    public function agregarCliente($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        $form = $this->getClienteForm();
        $form->populate($data);

        if (!$form->isValid()) {
            $elements = $this->getElementsStringClienteForm();
            return array('response' => null, 'message' => $this->flashmessenger->getMessageString(), 'formString' => $elements);
        }

        $entity = new ClienteEntity();
        $entity->setOptions($data);
        $entity->save($entity->getOptions());

        return array(
            'response' => true,
            'listClientes' => $this->getListClientes()
        );
    }

    public function getElementsClienteForm()
    {
        return array(
            'response' => true,
            'elementsFormString' => $this->getElementsStringClienteForm()
        );
    }

    private function getElementsStringClienteForm()
    {
        $form = $this->getClienteForm();

        $formClienteElements = $form->getElements();
        $string = "";
        foreach ($formClienteElements as $element) {
            if (isset($element['label'])) {
                $string .= $form->getElementString($element['name']);
            }
        }
        return $string;
    }

    public function getListClientes($selectedCustomer = null)
    {
        $entity = new ClienteRepository();
        $listClientes = $entity->getListaSelectClientes();

        $list = "<option value=''>" . $this->_getTranslation('Seleccionar una opcion...') . "</option>";
        foreach ($listClientes as $key => $value) {
            $selected = "";
            if ($key == $selectedCustomer) {
                $selected = "selected";
            }
            $list .= "<option value='$key' $selected >$value</option>";
        }
        return $list;
    }

    public function getListaProductosPos($options)
    {
        $repository = new ProductoRepository();
        $item = $options['item'];

        $items = $repository->getProductosLike($item);

        if ($items) {
            $array = array();
            foreach ($items as $item) {
                $array[] = array(
                    'value' => $item['id'],
                    'label' => $item['descripcion'] . " (" . $item['codigo'] . ")",
                    'precio' => $item['punitarioventa'],
                    'descuento' => $item['descuento'],
                    'impuestos' => $item['impuestos']
                );
            }
        }
        return array(
            'response' => true,
            'productos' => $array
        );
    }

    public function setProductToEdit($options)
    {
        $idProduct = $options['idProduct'];

        $repo = new VentaDetallesTempRepository();
        /*$idproduct; realmente contiene el id el registro a editar.*/
        $data = $repo->getById($idProduct);
        $data['idDetalleTemp'] = $data['id'];
        $data['cantidadOrigen'] = $data['cantidad'];
        unset($data['id']);

        $image = "main_" . $data['idProducto'] . ".jpg";

        if (!file_exists(PATH_IMG_PRODUCTS . $image)) {
            $image = "default.jpg";
        }
        // $divimg = "<div class='item-image'  style='background-image: url('../public/img/products/$image)'></div> ";
        $divimg = "<div class='item-image ' style='background-image: url(\"../public/img/products/$image\")'></div>";


        return array(
            'response' => true,
            'data' => $data,
            'divimg' => $divimg,
        );
    }

    public function deleteDetalles($options)
    {
        $id = $options['id'];
        $repository = new VentaDetallesTempRepository();

        if ($repository->delete($id)) {
            $response = true;
            $msj = $this->_getTranslation('Producto eliminado correctamente.');
        } else {
            $response = null;
            $msj = $this->_getTranslation("No se pudo eliminar producto. Intente nuevamente.");
        }

        $descuentoOrdenTipo = 0;
        if (isset($options['descuento_orden_tipo'])) {
            $descuentoOrdenTipo = $options['descuento_orden_tipo'];
        }
        $ventaDetalles = $this->getVentaDetalles();
        $detalles = $this->listVentaDetalles($ventaDetalles, $descuentoOrdenTipo);
        $json = array(
            'response' => true,
            'ventaDetalles' => $detalles['listDetalles'],
            'subtotal' => $detalles['subtotal'],
            'montoTotal' => $detalles['montoTotal'],
            'impuestosTotal' => $detalles['impuestosTotal'],
            'descuentoOrden' => $detalles['descuentoOrden'],
            'descuentoItems' => $detalles['descuentoItems'],
            'descuentoTotal' => $detalles['descuentoTotal'],
            'regularPrice' => $detalles['regularPrice'],
            'itemsTotal' => $detalles['itemsTotal'],
            'venta_solo_para_mayores' => $detalles['venta_solo_para_mayores']
        );

        return $json;
    }

    /* COBROS FROM POS*/
    public function existPaymentsInActiveSale($options = null)
    {
        $cobros = $this->getCobrosVentaActiva();
        if ($cobros) {
            return array('response' => true);
        }

        return array('response' => null);
    }

    public function setCobroTemp($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        $msg = null;
        $idCharge = null;

        if ($data['formaPago'] == '8') {
            $balanceEBT = $this->getEBTBalance();
            if ((float) $data['monto'] > (float) $balanceEBT) {
                $message = $this->_getTranslation('El monto maximo a pagar con EBT es: ') . '$' . $balanceEBT;
                $this->flashmessenger->addMessage(array('danger' => $message));
                return array(
                    'response' => null,
                    'msg' => $this->flashmessenger->getMessageString()
                );
            }
        }

        /*
        if($data['formaPago']=='5' || $data['formaPago']=='6'){
            $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
            $data['amount'] = $data['monto'];
            $charge = $operacionesTarjetaRepo->charge($data);

            if(!$charge){
                return array(
                    'response'=>null,
                    'msg'=>$this->flashmessenger->getMessageString()
                );
            }
            
            $data['numDocumento'] = $charge;
            //$idCharge = $charge;
         }*/

        $repoTemp = new CobroTempRepository();
        $repoTemp->save($data);

        $cobros = $this->listaCobros();
        $msg = $this->flashmessenger->getMessageString();

        return array(
            'response' => true,
            'listCobros' => $cobros['listCobros'],
            'totalPagado' => $cobros['totalPagado'],
            'msg' => $msg
        );
        //'idCharge'=>$idCharge);
    }

    public function getCobrosVentaActiva()
    {
        $repo = new CobroTempRepository();
        return $repo->getCobrosVentaActiva();
    }

    public function listaCobros()
    {
        $cobros = $this->getCobrosVentaActiva();

        $totalPagado = 0;
        $listCobros = '';
        if ($cobros != null) {
            foreach ($cobros as $cobro) {
                $id = $cobro['id'];
                $totalPagado += $cobro['monto'];
                $array = json_encode($cobro);
                $onclick = "onclick='setCobroToEdit($array,this)'";

                if ($cobro['formaPago'] == '5' || $cobro['formaPago'] == '6') {
                    $onclick = null;
                }

                $listCobros .= "<tr>
                                <td style='width:60%'>
                                    <a href='#' {$onclick} data-toggle='modal' data-target='#modalPagoDetalle'>{$cobro['formaPagoName']}</a>
                                </td>
                                <td class='text-right' style='width:25%'>$" . number_format($cobro['monto'], 2) . "</td>"
                    . " <td class='text-center' style='width:15%'>                        
                                    <a class='btn btn-sm btn-danger' onclick='deleteCobro($id);'><i class='fa fa-trash'></i></a>
                                </td>";
            }
        }

        $totalPagado = $totalPagado;
        return array(
            'listCobros' => $listCobros,
            'totalPagado' => $totalPagado
        );

    }

    public function clearListCobros()
    {
        #Si el usuario esta logueado en dos estaciones borrara todos los cobros.
        $cobroTemp = new CobroTempRepository();
        $cobros = $cobroTemp->getCobrosVentaActiva();

        $msg = '';
        $listCobros = $this->listaCobros();
        $listCobros = $listCobros['listCobros'];

        if ($cobros) {
            foreach ($cobros as $cobro) {
                $rs = $this->deleteCobro(array('id' => $cobro['id']));
                $msg .= $rs['msg'];

                if (!$rs['response']) {
                    return array(
                        'response' => null,
                        'listCobros' => $listCobros,
                        'msg' => $msg
                    );
                }

                $listCobros = $rs['listCobros'];
            }
        }

        return array(
            'response' => true,
            'listCobros' => $listCobros,
            'msg' => $msg
        );
    }

    public function deleteCobro($options)
    {
        $id = $options['id'];
        $msg = '';
        $repo = new CobroTempRepository();
        /*$data = $repo->getById($id);
        
        if($data['formaPago'] == '5' || $data['formaPago'] == '6'){    
            $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
            $void = $operacionesTarjetaRepo->voidTransaction($data['numDocumento']);
            $msg = $this->flashmessenger->getMessageString();
            
            if(!$void){
                return array(
                    'response'=>null,
                    'msg'=>$msg
                );
            }
        }*/

        $repo->delete($id);
        $cobros = $this->listaCobros();

        return array(
            'response' => true,
            'listCobros' => $cobros['listCobros'],
            'totalPagado' => $cobros['totalPagado'],
            'msg' => $msg
        );
    }

    public function saveVentaPos($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        $data['fecha'] = date('m/d/Y');
        $data['fecha_pago'] = date('m/d/Y');
        $data['metodo_pago'] = 1;

        $entity = new VentaEntity();
        $entity->setOptions($data);
        $result = $entity->savePos($entity->getOptions());

        if ($result) {
            $this->flashmessenger->addMessage(array('success' => 'Genial. La venta se realizo exitosamente.'));
            return array(
                'response' => true,
                'idVenta' => $entity->getLastInsertId(),
                'message' => $this->flashmessenger->getMessageString()
            );
        } else {
            $this->flashmessenger->addMessage(array('danger' => 'Oops. Algo salio mal al tratar de guardar la venta. Trata nuevamente.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }
    }

    public function suspenderVenta($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        $entity = new VentaEntity();
        $entity->setOptions($data);
        $options = $entity->getOptions();
        $options['referencia'] = $data['referencia_venta_suspendida'];
        unset($options['num_venta']); // No se utiliza en tabla ventas_suspendidas
        $result = $entity->suspenderVenta($options);

        if ($result) {
            $ventasSuspendidas = $this->getListVentasSuspendidas();
            $this->flashmessenger->addMessage(array('success' => 'Genial. La venta se almaceno correctamente.'));
            return array(
                'response' => true,
                'message' => $this->flashmessenger->getMessageString(),
                'ventasSuspendidas' => $ventasSuspendidas['ventasSuspendidas']
            );
        } else {
            $this->flashmessenger->addMessage(array('danger' => 'Oopss. Algo salio mal al tratar de suspender la venta. Trata nuevamente.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

    }

    public function getActivarVentaSuspendida($options)
    {
        $idVentaSuspendida = $options['idVenta'];

        $infoVenta = $this->activarVentaSuspendida($idVentaSuspendida);
        $detalles = $this->getListVentaDetalles();

        $ventasSuspendidas = $this->getListVentasSuspendidas();

        return array(
            'response' => true,
            'descuento_orden_tipo' => $infoVenta['descuento_orden_tipo'],
            'descuento_orden_valor' => $infoVenta['descuento_orden_valor'],
            'cliente' => $infoVenta['cliente'],
            'descuentoOrden' => $detalles['descuentoOrden'],
            'descuentoItems' => $detalles['descuentoItems'],
            'regularPrice' => $detalles['regularPrice'],

            'ventaDetalles' => $detalles['ventaDetalles'],
            'subtotal' => $detalles['subtotal'],
            'montoTotal' => $detalles['montoTotal'],
            'impuestosTotal' => $detalles['impuestosTotal'],
            'itemsTotal' => $detalles['itemsTotal'],
            'venta_solo_para_mayores' => $detalles['venta_solo_para_mayores'],
            'ventasSuspendidas' => $ventasSuspendidas['ventasSuspendidas']
        );
    }

    public function deleteVentaPosActual()
    {
        /*PCG CODE*/
        #En pagos de specialRequisition no se pueden agregar productos desde el POS, deben agregar desde specialRequisition
        $idSpecialRequisition = $this->isSpecialRequisition();
        if ($idSpecialRequisition) {
            $this->flashmessenger->addMessage(array('info' => "Oops.!! Lo siento. No puedes eliminar esta descripcion"));
            return $json = array(
                'response' => null,
                'message' => $this->flashmessenger->getMessageString()
            );
        }
        /* END PCG CODE*/

        $this->clearDetalles();
        $repo = new CobroTempRepository();
        $repo->clearDetalles();

        return array('response' => true);
    }

    public function deleteVentaSuspendida($options)
    {
        $repoTemp = new VentaDetallesTempRepository();
        $result = $repoTemp->deleteVentaSuspendida($options['idVentaSuspendida']);

        $ventasSuspendidas = $this->getListVentasSuspendidas();

        if ($result) {
            $this->flashmessenger->addMessage(array('success' => 'Venta suspendida se ha eliminado.'));
        } else {
            $this->flashmessenger->addMessage(array('danger' => ''));
        }

        return array(
            'response' => true,
            'ventasSuspendidas' => $ventasSuspendidas['ventasSuspendidas'],
            'message' => $this->flashmessenger->getMessageString()
        );

    }

    /* DEVOLUCIONES FROM POS*/

    public function getVentaDetallesDevolucion($options)
    {
        $id = $options['idVentaDevolucion'];

        $ventaDetalles = $this->getVentaDetallesSaved($id);
        #Contiene la suma de productos que se han devuelto de esa venta
        $repo = new DevolucionRepository();
        $sumProductosDevueltos = $repo->getSumProductosDevueltosPorIdVenta($id);
        if (!$sumProductosDevueltos) {
            $sumProductosDevueltos = array();
        }

        $ventaInfo = $this->getById($id);
        $detalles = $this->listVentaDetallesDevolucion($ventaDetalles, $sumProductosDevueltos);

        $json = array(
            'response' => true,
            'clienteName' => $ventaInfo['clienteName'],
            'subtotal' => $ventaInfo['importe'],
            'descuentoOrden' => $ventaInfo['descuento_items_monto'] + $ventaInfo['descuento_orden_monto'],
            'ventaDetalles' => $detalles['listDetalles'],
            'montoTotal' => $ventaInfo['total_venta'],
            'impuestosTotal' => $ventaInfo['total_impuestos'],
            'itemsTotal' => $detalles['itemsTotal']
        );

        return $json;
    }

    public function listVentaDetallesDevolucion($detalles, $sumProductosDevueltos = array(), $edit = null)
    {
        $listDetalles = "";
        $montoTotal = 0;
        $montoImpuestos = 0;
        $itemsTotal = 0;

        foreach ($detalles as $detalle) {
            #Debo eliminar id de $array, de lo contrario se setea como id de la Venta, y realmente es id del detalle
            #El cual ya esta dentro de este array como idDetalleTemp      
            $itemsTotal += $detalle['cantidad'];
            $id = $detalle['id'];

            $totalDetalleUnitario = $detalle['precio_sin_impuestos'] * $detalle['cantidad'];
            $totalDetalleUnitario = $totalDetalleUnitario - ($detalle['descuento_item_monto'] + $detalle['descuento_orden_monto']);
            $totalDetalleUnitario = $totalDetalleUnitario + $detalle['impuestos_monto'];
            $totalDetalleUnitario = number_format($totalDetalleUnitario / $detalle['cantidad'], 2);

            //$image = "main_".$detalle['idProducto'].".jpg";
            //if(!file_exists(PATH_IMG_PRODUCTS.$image)){$image = "default.jpg";}

            $totalProductosDevueltos = 0;
            if (key_exists($detalle['id'], $sumProductosDevueltos)) {
                $totalProductosDevueltos = $sumProductosDevueltos[$detalle['id']];
            }
            $cantidadDisponible = $detalle['cantidad'] - $totalProductosDevueltos;
            $listDetalles .= "<tr>                                   
                            <td style='width:35%' class='text-center'>" . $detalle['descripcion'] . "</td>                                
                            <td style='width:12%' class='text-center'>" . $detalle['cantidad'] . "</td>
                            <td style='width:17%' class='text-right'>" . $totalDetalleUnitario . "</td>
                            <td style='width:12%' class='text-center'>" . $totalProductosDevueltos . "</td>
                            <td style='width:12%' class='text-right'><input type='text' class='col-lg-12 col-md-12 text-right devolucionInput' onblur='setSubtotalDevolucion($cantidadDisponible,this,{$totalDetalleUnitario},{$detalle['id']})' name='devolucion[" . $detalle['id'] . "|$totalDetalleUnitario]'/></td>
                            <td style='width:12%' class='text-right'><span id='{$detalle['id']}-devolucion' class='subtotal-devolucion'></span></td>
                            </tr>";
        }

        return array(
            'listDetalles' => $listDetalles,
            'itemsTotal' => $itemsTotal
        );
    }

    public function setPagoDevolucionTemp($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        if (trim($data['montoDevolucion']) == '' || trim($data['formaPagoDevolucion']) == '') {
            $this->flashmessenger->addMessage(array('info' => 'Lo sentimos. El campo forma de pago y monto son obligatorios.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

        $_SESSION['pagoDevolucion'][] = $data;
        $pagos = $this->listaPagosDevolucion();

        return array(
            'response' => true,
            'listPagos' => $pagos['listPagos'],
            'totalPagado' => $pagos['totalPagado']
        );
    }

    public function listaPagosDevolucion()
    {
        $pagos = $_SESSION['pagoDevolucion'];

        $totalPagado = 0;
        $listPagos = '';
        if ($pagos != null) {
            foreach ($pagos as $key => $pago) {
                $id = $key;
                $totalPagado += $pago['montoDevolucion'];
                $pago['idPagoDevolucion'] = $key;
                $array = json_encode($pago);

                $listPagos .= "<tr>
                                <td style='width:60%'>
                                    <a href='#' onclick='setPagoDevolucionToEdit($array)' data-toggle='modal' data-target='#modalPagoDevolucionDetalle'>{$pago['formaPagoNameDevolucion']}</a>
                                </td>
                                <td style='width:25%' class='text-right'>$" . number_format($pago['montoDevolucion'], 2) . "</td>"
                    . " <td style='width:15%' class='text-right'>                        
                                    <a class='btn btn-sm btn-danger' onclick='deletePagoDevolucion($id);'><i class='fa fa-trash'></i></a>
                                </td>";
            }
        }

        $totalPagado = number_format($totalPagado, 2);
        return array(
            'listPagos' => $listPagos,
            'totalPagado' => $totalPagado
        );

    }

    public function deletePagoDevolucion($options)
    {
        $id = $options['id'];
        unset($_SESSION['pagoDevolucion'][$id]);

        $pagos = $this->listaPagosDevolucion();

        return array(
            'response' => true,
            'listPagos' => $pagos['listPagos'],
            'totalPagado' => $pagos['totalPagado']
        );
    }

    public function saveDevolucion($options)
    {
        $dataDevolucion = array();
        foreach ($options['options'] as $row) {
            $dataDevolucion[$row['name']] = $row['value'];
        }

        $devolucionesDetalles = array();
        foreach ($options['devoluciones'] as $row) {
            if (trim($row['value']) !== '' or trim($row['value']) > 0) {
                $devolucionesDetalles[$row['name']] = $row['value'];
            }
        }

        if (count($devolucionesDetalles) <= 0) {
            $this->flashmessenger->addMessage(array('info' => 'Para registrar Devolucion, es necesario hacer devolucion de almenos un producto.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

        if (!isset($_SESSION['pagoDevolucion']) || count($_SESSION['pagoDevolucion']) <= 0) {
            $this->flashmessenger->addMessage(array('info' => 'Para registrar Devolucion, es necesario registrar el pago.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

        $tools = new Tools();
        $arrayDevoluciones = array();
        foreach ($devolucionesDetalles as $devolucion => $cantidad) {
            $idVentaDetalle = $tools->get_string_between($devolucion, '[', ']');
            #$idVentaDetalle contiene idVentaDetalle y monto por ese detalle. Con formato idVentaDetalle|Monto
            $arrayDevoluciones[$idVentaDetalle] = $cantidad;
        }

        $repoVenta = new VentaRepository();
        $ventaInfo = $repoVenta->getById($dataDevolucion['idVentaDevolucion']);

        $dataVenta = array(
            'options' => array(
                'fecha' => date('Y-m-d'),
                'cliente' => $ventaInfo['cliente'],
                'idVenta' => $ventaInfo['id'],
                'notas' => $dataDevolucion['notasDevolucion']
            ),
            'detalleDevolucion' => $arrayDevoluciones,
            'pagoDevolucion' => $_SESSION['pagoDevolucion']
        );

        $devolucionEntity = new DevolucionEntity();
        $result = $devolucionEntity->save($dataVenta);

        if ($result) {
            $this->flashmessenger->addMessage(array('success' => 'Devolucion registrada exitosamente.'));
            return array(
                'response' => true,
                'idDevolucion' => $devolucionEntity->getLastInsertId(),
                'message' => $this->flashmessenger->getMessageString()
            );
        }
    }

    public function clearListPagosDevolucion($options = null)
    {
        $_SESSION['pagoDevolucion'] = null;
        return array('response' => true);
    }

    public function sumDenominaciones($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            if (trim($row['value']) === '') {
                $row['value'] = 0;
            }
            $data[$row['name']] = $row['value'];
        }

        $form = new DenominacionesForm();
        $form->populate($data);
        $sumMonto = $form->getSumDenominaciones();

        return array(
            'response' => true,
            'sumMonto' => $sumMonto
        );
    }

    public function saveCliente($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        $entity = new ClienteEntity();
        $entity->setOptions(
            array(
                'nombre_empresa' => $data['nombre_empresa'],
                'nombre' => $data['nombre'],
                'calle' => $data['calle'],
                'ciudad' => $data['ciudad'],
                'telefono' => $data['telefono'],
                'correo' => $data['correo'],
            )
        );

        if (trim($data['nombre']) == '') {
            $this->flashmessenger->addMessage(array('info' => 'Lo sentimos. El campo nombre es obligatorio.'));
            return array(
                'response' => false,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

        if ($data['action'] == 'insert') {
            $result = $entity->saveClientePos(
                array(
                    'nombre_empresa' => $entity->getNombreEmpresa(),
                    'nombre' => $entity->getNombre(),
                    'calle' => $entity->getCalle(),
                    'ciudad' => $entity->getCiudad(),
                    'telefono' => $entity->getTelefono(),
                    'correo' => $entity->getCorreo(),
                )
            );

            $lastCliente = $entity->getInsertId();

        } elseif ($data['action'] == 'edit') {
            $result = $entity->updateClientePos($options['idCustomer'], array(
                'nombre_empresa' => $entity->getNombreEmpresa(),
                'nombre' => $entity->getNombre(),
                'calle' => $entity->getCalle(),
                'ciudad' => $entity->getCiudad(),
                'telefono' => $entity->getTelefono(),
                'correo' => $entity->getCorreo(),
            )
            );

            $lastCliente = $options['idCustomer'];
        }

        if ($result) {
            $this->flashmessenger->addMessage(array('success' => 'Excelente!! El cliente se registro exitosamente.'));
        } else {
            $this->flashmessenger->addMessage(array('danger' => 'Opss. Algo salio mal al intetar registrar el cliente.'));
        }

        return array(
            'response' => true,
            'message' => $this->flashmessenger->getMessageString(),
            'listClientes' => $this->getListClientes($lastCliente)
        );
    }

    public function getDataVenta($options)
    {
        $idRegister = $options['idRegister'];
        $entity = new VentaEntity();
        $data = $entity->getDataVentaParaResumen($idRegister);

        $entityRegister = new AperturaCierreCajaEntity();
        $entityRegister->setOptions($entityRegister->getById($idRegister));

        $repoGeneric = new GenericRepository();
        $totalRetiros = round($repoGeneric->getSumTotalRetiros($idRegister), 2); #$idRegister = id_apertura_cierre

        $string = "<div class='col-lg-12 col-md-12 col-sm-12'>";
        $string .= "<div>"
            . "<label>" . $this->_getTranslation('Desde') . ":</label> " . strftime('%d/%b/%Y %H:%M:%S', strtotime($entityRegister->getFechaCreacion())) . " "
            . "<label>" . $this->_getTranslation('Hasta') . ":</label> " . strftime('%d/%b/%Y %H:%M:%S', strtotime(date('Y-m-d h:i:s')))
            . "</div>";
        $string .= "<div class='col-lg-12 col-md-12 col-sm-12'>";
        //$string .= "<h3 style='padding:10px;'>".$this->_getTranslation('Informacion ventas')."</h3>";

        $montoVentasTotal = 0;
        if ($data) {
            $string .= "<table class='table table-condensed'>";
            $string .= "<thead>";
            $string .= "<th>" . $this->_getTranslation('Forma pago') . "</th>";
            $string .= "<th class='text-right'>" . $this->_getTranslation('Monto') . "</th>";
            $string .= "</thead>";
            $string .= "<tbody>";

            foreach ($data as $row) {
                $string .= "<tr>";
                $string .= "<td>" . $this->_getTranslation($row['formaPago']) . "</td>";
                $string .= "<td class='text-right'>" . number_format($row['monto'], 2) . "</td>";
                $string .= "</tr>";
                $montoVentasTotal += $row['monto'];
            }

            $string .= "<tr>";
            $string .= "<td>" . $this->_getTranslation('Retiros') . "</td>";
            $string .= "<td class='text-right'> " . number_format($totalRetiros, 2) . "</td>";
            $string .= "<tr>";

            /*
            $string .= "<tr>";
            $string .= "<td>".$this->_getTranslation('Apertura')."</td>";
            $string .= "<td class='text-right'>- ".number_format($entityRegister->getEfectivoInicial(),2)."</td>";
            $string .= "<tr>";*/

            $string .= "</tbody>";
            $string .= "</table>";
        }
        $string .= "</div>";
        $string .= "</div>"; #col-lg-12


        $string .= "<div class='col-lg-12 col-md-12 col-sm-12'>";
        $string .= "<div class='col-lg-6 col-md-6 col-sm-6'>"
            . "    <label class='pull-left'>" . $this->_getTranslation('Total ventas') . "</label>"
            . "    <span class='pull-right'>$" . number_format($montoVentasTotal, 2) . "</span>"
            . "</div>";

        return array(
            'response' => true,
            'string' => $string
        );
    }

    public function getDataVentaArqueo($options)
    {
        $idRegister = $options['idRegister'];
        $entity = new VentaEntity();
        $data = $entity->getDataVentaParaArqueo($idRegister); 

        $entityRegister = new AperturaCierreCajaEntity();
        $entityRegister->setOptions($entityRegister->getById($idRegister));

        $repoGeneric = new GenericRepository();
        $totalRetiros = round($repoGeneric->getSumTotalRetiros($idRegister), 2); #$idRegister = id_apertura_cierre

        $string = "<div class='col-lg-12 col-md-12 col-sm-12'>";
        $string .= "<div>"
            . "<label>" . $this->_getTranslation('Desde') . ":</label> " . strftime('%b/%d/%Y %H:%M:%S', strtotime($entityRegister->getFechaCreacion())) . " "
            . "<label>" . $this->_getTranslation('Hasta') . ":</label> " . strftime('%b/%d/%Y %H:%M:%S', strtotime($entityRegister->getFechaCierre()))
            . "</div>";
        $string .= "<div class='col-lg-6 col-md-6 col-sm-6'>";
        $string .= "<h3 style='padding:10px;background-color:#5cb85c;color:#fff'>" . $this->_getTranslation('Informacion ventas') . "</h3>";

        $montoVentasTotal = 0;
        $donacion = 0;
        if ($data) {
            $string .= "<table class='table table-condensed'>";
            $string .= "<thead>";
            $string .= "<th>" . $this->_getTranslation('Forma pago') . "</th>";
            $string .= "<th class='text-right'>" . $this->_getTranslation('Monto') . "</th>";
            $string .= "</thead>";
            $string .= "<tbody>";

            foreach ($data as $row) {
                $string .= "<tr>";
                $string .= "<td>" . $this->_getTranslation($row['formaPago']) . "</td>";
                $string .= "<td class='text-right'>" . number_format($row['monto'], 2) . "</td>";
                $string .= "</tr>";
                $montoVentasTotal += $row['monto'];

                if ($row['formaPagoId'] == 9) {
                    $donacion = $row['monto'];
                }
            }

            $string .= "</tbody>";
            $string .= "</table>";
        }
        $string .= "</div>";

        $string .= "<div class='col-lg-6 col-md-6 col-sm-6'>";
        $string .= "<h3 style='padding:10px;background-color:#f0ad4e;color:#fff'>" . $this->_getTranslation('Informacion cierre') . "</h3>";

        $string .= "<table class='table table-condensed'>";
        $string .= "<thead>";
        $string .= "<th>" . $this->_getTranslation('Forma pago') . "</th>";
        $string .= "<th class='text-right'>" . $this->_getTranslation('Monto') . "</th>";
        $string .= "</thead>";
        $string .= "<tbody>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('Efectivo') . "</td>";
        $string .= "<td class='text-right'>" . number_format($entityRegister->getEfectivoFinal(), 2) . "</td>";
        $string .= "<tr>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('Tarjetas') . "</td>";
        $string .= "<td class='text-right'>" . number_format($entityRegister->getTarjetasFinal(), 2) . "</td>";
        $string .= "<tr>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('EBT') . "</td>";
        $string .= "<td class='text-right'>" . number_format($entityRegister->getElectronicoFinal(), 2) . "</td>";
        $string .= "<tr>";
        
        $string .= "<tr>";
        $string .= "<td>".$this->_getTranslation('Door Dash')."</td>";
        $string .= "<td class='text-right'>".number_format($entityRegister->getDoorDashFinal(),2)."</td>";
        $string .= "<tr>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('Cheques') . "</td>";
        $string .= "<td class='text-right'>" . number_format($entityRegister->getChequesFinal(), 2) . "</td>";
        $string .= "<tr>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('Devoluciones') . "</td>";
        $string .= "<td class='text-right'> " . number_format($entityRegister->getDevoluciones(), 2) . "</td>";
        $string .= "<tr>";

        $string .= "<tr>";
        $string .= "<td>" . $this->_getTranslation('Retiros') . "</td>";
        $string .= "<td class='text-right'> " . number_format($totalRetiros, 2) . "</td>";
        $string .= "<tr>";

        /*
        $string .= "<tr>";
        $string .= "<td>".$this->_getTranslation('Apertura')."</td>";
        $string .= "<td class='text-right'>- ".number_format($entityRegister->getEfectivoInicial(),2)."</td>";
        $string .= "<tr>";*/

        $string .= "</tbody>";
        $string .= "</table>";
        $string .= "</div>";

        $string .= "</div>"; #col-lg-12


        $string .= "<div class='col-lg-12 col-md-12 col-sm-12'>";
        $string .= "<div class='col-lg-6 col-md-6 col-sm-6'>"
            . "    <label class='pull-left'>" . $this->_getTranslation('Total ventas') . "</label>"
            . "    <span class='pull-right'>$" . number_format($montoVentasTotal, 2) . "</span>"
            . "</div>";

        //$montoTotalCierre = $entityRegister->getMontoCierreMenosInicial()  + $totalRetiros + $donacion;
        $montoTotalCierre = $entityRegister->getMontoCierre() + $totalRetiros + $donacion;
        $string .= "<div class='col-lg-6 col-md-6 col-sm-6'>"
            . "    <label class='pull-left'>" . $this->_getTranslation('Total cierre') . "</label>"
            . "    <span class='pull-right'>$" . number_format($montoTotalCierre, 2) . "</span>"
            . "</div>";

        if ($data) {
            $titleDiferencia = '';
            $diferencia = bccomp($montoTotalCierre, $montoVentasTotal, 2);
            switch ($diferencia) {
                case '0':
                    $titleDiferencia = 'Balance';
                    break;
                case '1':
                    $titleDiferencia = 'Sobrante';
                    break;
                default:
                    $titleDiferencia = 'Faltante';
                    break;
            }

            $string .= "<div class='col-lg-6 col-md-6 col-sm-6 p-t-2 pull-right'>"
                . "    <label class='pull-left'>" . $this->_getTranslation($titleDiferencia) . "</label>"
                . "    <span class='pull-right'>$" . number_format(abs($montoVentasTotal - $montoTotalCierre), 2) . "</span>"
                . "</div>";

        }

        $string .= "</div>";

        return array(
            'response' => true,
            'string' => $string
        );
    }

    public function prepareToSendMail($options)
    {
        $optionsMail = array();
        foreach ($options['optionsmail'] as $row) {
            $optionsMail[$row['name']] = $row['value'];
        }

        $string = null;
        unset($optionsMail['optionsFromGet']);
        foreach ($optionsMail as $option => $value) {
            $string .= "&" . $option . "=" . $value;
        }

        $string = trim($string, "&");
        $reporteUrl = $options['optionsget'] . "&" . $string;

        return array(
            'response' => true,
            'reportUrl' => $reporteUrl
        );
    }

    public function getLastSales()
    {
        $report = new ReportListasRepository();
        //Crear fechas del dia
        $dateOptions = array(
            'fechaInicio' => date('Y-m-d'),
            'fechaFin' => date('Y-m-d'),
        );
        $data = parent::getSalesTodayByIdStore();
        $dataVentas = parent::getTotalSalesTodayByIdStore($dateOptions);
        $string = "";
        $login = new Login();

        $ventaCount = []; // Arreglo para contar las apariciones de num_venta

        if ($data) {
            foreach ($data as $venta) {

                // Incrementa el contador para este num_venta
                if (!isset($ventaCount[$venta['num_venta']])) {
                    $ventaCount[$venta['num_venta']] = 0;
                }
                $ventaCount[$venta['num_venta']]++;

                // Determina si los botones deben ser deshabilitados o no pintados
                $disableButtons = ($ventaCount[$venta['num_venta']] > 1);


                $class = " deleteVenta ";
                if ($login->getRole() == 1) {
                    //$printFunction2 = " changeMetodoPago({$venta['id']}, {$venta['id_cobros']}); ";
                    $printFunction = "reimprimirTicketVenta(); ";
                } else {
                    $printFunction = " confirmarAccion('reemprimir_ticket',function(){ reimprimirTicketVenta(); }) ";
                    // $printFunction2 = "confirmarAccion('changeMetodoPago',function(){ changeMetodoPago({$venta['id']}, {$venta['id_cobros']})";
                }

                $function_credito = "confirmarAccion('changeMetodoPago',function(){ changeMetodoPago({$venta['id']}, {$venta['id_cobros']});})";
                $function_efectivo = "confirmarAccion('changeMetodoPago',function(){ changeMetodoPago({$venta['id']}, {$venta['id_cobros']});})";
                $function_ebt = "confirmarAccion('changeMetodoPago',function(){ changeMetodoPago({$venta['id']}, {$venta['id_cobros']});})";

                if ($venta['status'] == '3') {
                    $class = " disabled ";

                    if ($login->getRole() == 1) {
                        $printFunction = "printTicketVentaCancelada({$venta['id']}) ";
                    } else {
                        $printFunction = " confirmarAccion('reemprimir_ticket',function(){ printTicketVentaCancelada({$venta['id']}) }) ";
                    }
                }
                // Inicializamos las clases para los botones como 'btn-default'
                $clase_efectivo = "btn-default";
                $clase_credito = "btn-default";
                $clase_ebt = "btn-default";

                // Verificamos el ID del método de pago y asignamos la clase adecuada
                if ($venta['formaPago'] == 5 && $venta['se_repite'] !== "2") {
                    $clase_credito = "btn-success";
                    $function_credito = ""; //No es necesario cambiar el metodo de pago
                } elseif ($venta['formaPago'] == 3 && $venta['se_repite'] !== "2") {
                    $clase_efectivo = "btn-success";
                    $function_efectivo = ""; //No es necesario cambiar el metodo de pago
                } elseif ($venta['formaPago'] == 8 && $venta['se_repite'] !== "2") {
                    $clase_ebt = "btn-success";
                    $function_ebt = ""; //No es necesario cambiar el metodo de pago
                } else {
                    $clase_ebt = " disabled ";
                    $clase_credito = " disabled ";
                    $clase_efectivo = " disabled ";

                    $function_ebt = ""; //No es necesario cambiar el metodo de pago

                }


                $string .= "<tr>"
                    . "<td class='text-center' style='width:10%'># {$venta['num_venta']}</td>"
                    . "<td class='text-right' style='width:15%'>$ " . number_format($venta['total_venta'], 2) . "</td>"
                    . "<td class='text-center' style='width:15%'> {$venta['statusName']}</td>"

                    . "<td class='text-right' style='width:35%'>" // UG Agregar botones para cambiar metodo de pago
                    . " <a class='btn btn-md $clase_efectivo' onclick=\"$('#new_formaPago').val('3');$function_efectivo\"><i class=' fa fa-dollar'></i> Efectivo</a>"
                    . " <a class='btn btn-md $clase_credito' onclick=\"$('#new_formaPago').val('5');$function_credito\" ><i class='fa fa-credit-card'></i> Credito</a>"
                    . " <a class='btn btn-md $clase_ebt' onclick=\"$('#new_formaPago').val('8');$function_ebt\"><i class='fa fa-credit-card'></i> EBT</a>"
                    . "</td>"

                    . "<td class='text-right' style='width:25%'>"
                    . " <a class='btn btn-md btn-default' onclick=\"$('#idVentaReimprimir').val('{$venta['num_venta']}');$printFunction\"><i class='fa fa-print'></i></a>"
                    . " <a class='btn btn-md btn-default re_email' data-idventa='{$venta['id']}' ><i class='fa fa-envelope'></i></a>"
                    . " <a class='btn btn-md btn-danger $class' data-idventa='{$venta['id']}'><i class='fa fa-trash'></i></a>"
                    . "</td>"
                    . "</tr>";
            }
        }
        // var_dump($dataVentas);exit;
        if (isset($dataVentas)) {
            $dataVentas[0]['total'] = number_format($dataVentas[0]['total'], 2);
        }
        // var_dump( $dataVentas);exit;
        return array(
            'response' => true,
            'listLastSales' => $string,
            'ventasPorFormaDePago' => $dataVentas,
        );
    }
    public function changeMetodoPago($options)
    {
        $idVenta = $options['id'];
        $id_pago = $options['id_pago'];
        $formaPago = $options['formaPago'];
        $repo = new CobroRepository();
        $repo->updateFormaPago($idVenta, $id_pago, $formaPago);

        if ($repo) {
            return array(
                'response' => true
            );
        }
        return array(
            'response' => false
        );
    }

    public function getLastDevoluciones()
    {
        $data = parent::getDevolucionesTodayByIdCaja();
        $data = $data['data'];

        $string = "";
        if ($data) {
            foreach ($data as $devolucion) {
                $string .= "<tr>"
                    . "<td class='text-center'># {$devolucion['idDevolucion']}</td>"
                    . "<td class='text-center'># {$devolucion['idVenta']}</td>"
                    . "<td class='text-right' style='width:15%'>$ " . number_format(round($devolucion['total'], 2, PHP_ROUND_HALF_UP), 2) . "</td>"
                    . "<td class='text-center'> {$devolucion['statusName']}</td>"
                    . "<td class='text-right'>"
                    . " <a class='btn btn-md btn-success' onclick='printDevolucion({$devolucion['idDevolucion']});'><i class='fa fa-print'></i></a>"
                    . " <a class='btn btn-md btn-danger' onclick='deleteDevolucion({$devolucion['idDevolucion']});'><i class='fa fa-trash'></i></a>"
                    . "</td>"
                    . "</tr>";
            }
        }
        return array(
            'response' => true,
            'listLastDevoluciones' => $string
        );
    }

    public function deleteDevolucion($options)
    {
        $id = $options['id'];
        $repo = new DevolucionRepository();

        $repo->delete($id);

        return array(
            'response' => true
        );
    }

    public function cancelVenta($options)
    {
        $repo = new VentaRepository();
        $delete = $repo->delete($options['idVenta']);

        if (!$delete) {
            $this->flashmessenger->addMessage(array('success' => 'Error al tratar de cancelar venta.'));
            return array(
                'response' => null,
                'message' => $this->flashmessenger->getMessageString()
            );
        }

        $lastSales = $this->getLastSales();
        $this->flashmessenger->addMessage(array('success' => 'Venta cancelada con exito.'));

        /*Refund pagos con tarjeta*/
        $operacionesRepo = new OperacionesTarjetasRepository();
        $charges = $operacionesRepo->getChargesWithBalanceByIdSale($options['idVenta'], 'charge');

        if ($charges) {
            $msg = $this->flashmessenger->_getTranslation('Existen cargos a tarjeta por esta venta.');
            $msg .= '<br/>' . $this->flashmessenger->_getTranslation('Para reembolsar vaya a lista de operaciones con tarjeta.');
            $this->flashmessenger->addMessage(array('info' => $msg));
        }
        /*
        if($charges){
            new InitStripe();
            \Stripe\Stripe::setApiKey("sk_test_Q1h2teyoIIKuGv0UgjkcenU8");
            foreach($charges as $charge){
                try {                    
                    $refund = \Stripe\Refund::create(["charge" => $charge['reference']]);

                    $msg = $this->flashmessenger->addMessage(array('success'=>'El pago fue cancelado exitosamente.'));

                    //Save on operaciones_tarjetas
                    $operacionesRepo = new OperacionesTarjetasRepository();
                    $refund['id_sale'] = $charge['id_sale'];
                    $operacionesRepo->_save($refund, true);
                }
                catch (Exception $e) {
                    $msg = $this->flashmessenger->addMessage(array('danger'=>$e->getMessage()));
                    
                    //return array(
                    //    'response'=>null,
                    //    'msg'=>$this->flashmessenger->getMessageString()
                    //);
                }
            }
        }*/

        return array(
            'response' => true,
            'lastSales' => $lastSales['listLastSales'],
            'message' => $this->flashmessenger->getMessageString()
        );
    }

    public function getEBTBalance()
    {
        $repo = new VentaDetallesTempRepository();
        return $repo->_getEBTBalance();
    }

    public function confirmarAccion($options)
    {
        $query = "SELECT * FROM usuarios WHERE usuario = '{$options['usuario']}' AND contrasena = MD5('{$options['contrasena']}') LIMIT 1";
        $result = $this->query($query);

        $data = null;
        if ($result->num_rows > 0) {
            $result = $this->resultToArray($result);
            $data = $result[0];
        }

        if ($data) {
            if ($data['role'] == '1' || $data['role'] == '3') {
                return array(
                    'response' => true
                );
            } else {
                $this->flashmessenger->addMessage(array('danger' => 'No tienes provilegios para confirmar esta accion.'));
                return array(
                    'response' => false,
                    'msg' => $this->flashmessenger->getMessageString()
                );
            }
        } else {
            $this->flashmessenger->addMessage(array('danger' => 'Usuario o contraseÃ±a incorrectos.'));
            return array(
                'response' => false,
                'msg' => $this->flashmessenger->getMessageString()
            );
        }
    }

    public function confirmarAccionResumen($options)
    {
        $query = "SELECT * FROM usuarios WHERE usuario = '{$options['usuario']}' AND contrasena = MD5('{$options['contrasena']}') LIMIT 1";
        $result = $this->query($query);

        $data = null;
        if ($result->num_rows > 0) {
            $result = $this->resultToArray($result);
            $data = $result[0];
        }

        if ($data) {
            $operacion = $options['operacion'];
            $permisos = array(
                'cancelar_venta' => array('1', '3'), #admin, supervisor
                'eliminar_detalle_requisicion' => array('1', '3'), #admin, supervisor
                'reemprimir_ticket' => array('1', '3', '6'), #admin,supervisor,tesoreria
                'resumen_ventas' => array('1', '6'), #admin, tesoreria
            );

            $permiso = $permisos[$operacion];
            if (in_array($data['role'], $permiso)) {
                return array(
                    'response' => true
                );
            } else {
                $this->flashmessenger->addMessage(array('danger' => 'No tienes provilegios para confirmar esta accion.'));
                return array(
                    'response' => false,
                    'msg' => $this->flashmessenger->getMessageString()
                );
            }

        } else {
            $this->flashmessenger->addMessage(array('danger' => 'Opss. Usuario o contraseÃ±a incorrectos.'));
            return array(
                'response' => false,
                'msg' => $this->flashmessenger->getMessageString()
            );
        }
    }

    public function getLastCardOperations()
    {
        $login = new Login();
        $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
        $fechaFin = date('Y-m-d');
        $fechaInicio = date("Y-m-d", strtotime($fechaFin . "- 7 days"));
        $data = $operacionesTarjetaRepo->getListaOperacionesTarjetas(array('type' => 'charge', 'fechaInicio' => $fechaInicio, 'fechaFin' => $fechaFin, 'store_id' => $login->getSucursal()));

        $string = "";
        if ($data) {
            foreach ($data as $charge) {
                $class = " refund ";
                $classVoid = " void ";
                $status = "<span class='label label-primary'>" . $charge['statusName'] . " <i class='fa fa-check'></i></span>";

                if ($charge['status'] == '2') {
                    $status = "<span class='label label-primary'>" . $charge['statusName'] . " <i class='fa fa-exclamation-triangule'></i></span>";
                    $classVoid = " disabled ";
                }
                if ($charge['status'] == '3') {
                    $class = " disabled ";
                    $classVoid = " disabled ";
                    $status = "<span class='label label-default'>" . $charge['statusName'] . " <i class='fa fa-undo'></i></span>";
                }

                if ($charge['status'] == '4') {
                    $class = " disabled ";
                    $classVoid = " disabled ";
                    $status = "<span class='label label-danger'>" . $charge['statusName'] . " <i class='fa fa-ban'></i></span>";
                }
                $num_venta = '';
                if (trim($charge['num_venta']) !== '') {
                    $num_venta = "# " . $charge['num_venta'];
                }
                $string .= "<tr>"
                    . "<td class='text-center' style='width:19%'>{$num_venta}<br/>{$charge['date_formated']}</td>"
                    . "<td class='text-center' style='width:23%'> {$charge['brand']} {$charge['last_4']}</td>"
                    . "<td class='text-right' style='width:15%'>$ " . number_format($charge['amount'], 2) . "</td>"
                    . "<td class='text-center' style='width:20%'>{$status}</td>"
                    . "<td class='text-right' style='width:22%;white-space: nowrap'>"
                    . " <a class='btn btn-md btn-default cardPaymentDetails' data-charge='{$charge['reference']}'><i class='fa fa-eye' title='Ver datos del pago'></i></a>"
                    . " <a class='btn btn-md btn-default $class' data-charge='{$charge['reference']}' title='Reembolsar pago'><i class='fa fa-undo'></i></a>"
                    . " <a class='btn btn-md btn-danger $classVoid' data-charge='{$charge['reference']}' title='Cancelar pago'><i class='fa fa-ban'></i></a>"
                    . "</td>"
                    . "</tr>";
            }
        }
        return array(
            'response' => true,
            'lastCardOperations' => $string
        );
    }

    public function getCardOperationBySale($options)
    {
        $login = new Login();
        $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
        $data = $operacionesTarjetaRepo->getListaOperacionesTarjetas(array('type' => 'charge', 'sale_id' => $options['sale'], 'store_id' => $login->getSucursal()));

        $string = "";
        if ($data) {
            foreach ($data as $charge) {
                $class = " refund ";
                $status = "<span class='label label-primary'>" . $charge['statusName'] . " <i class='fa fa-check'></i></span>";

                if ($charge['status'] == '2') {
                    $status = "<span class='label label-primary'>" . $charge['statusName'] . " <i class='fa fa-exclamation-triangule'></i></span>";
                }
                if ($charge['status'] == '3') {
                    $class = " disabled ";
                    $status = "<span class='label label-default'>" . $charge['statusName'] . " <i class='fa fa-undo'></i></span>";
                }


                $string .= "<tr>"
                    . "<td class='text-left' style='width:20%'># {$charge['num_venta']}<br/>{$charge['date_formated']}</td>"
                    . "<td class='text-center' style='width:23%'> {$charge['brand']} {$charge['last_4']}</td>"
                    . "<td class='text-right' style='width:17%'>$ " . number_format($charge['amount'], 2) . "</td>"
                    . "<td class='text-center' style='width:20%'>{$status}</td>"
                    . "<td class='text-right' style='width:20%'>"
                    . " <a class='btn btn-md btn-default cardPaymentDetails' data-charge='{$charge['reference']}'><i class='fa fa-eye' title='Ver datos del pago'></i></a>"
                    . " <a class='btn btn-md btn-default $class' data-charge='{$charge['reference']}' title='Reembolsar pago'><i class='fa fa-undo'></i></a>"
                    . "</td>"
                    . "</tr>";
            }
        }
        return array(
            'response' => true,
            'lastCardOperations' => $string
        );
    }

    /* REFUNDS */
    public function refund($options)
    {
        $data = array();
        foreach ($options['options'] as $row) {
            $data[$row['name']] = $row['value'];
        }

        if (trim($data['amount']) == '') {
            $this->flashmessenger->addMessage(array('danger' => 'El reembolso no puede ser 0'));
            return array('response' => null, 'msg' => $this->flashmessenger->getMessageString());
        }

        $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
        $refund = $operacionesTarjetaRepo->refund($data);

        if ($refund) {
            $lastCardOperations = $this->getLastCardOperations();
            return array(
                'response' => true,
                'msg' => $this->flashmessenger->getMessageString(),
                'lastCardOperations' => $lastCardOperations['lastCardOperations']
            );
        }

        return array(
            'response' => null,
            'msg' => $this->flashmessenger->getMessageString()
        );
    }

    /* END REFUND*/

    /* VOID*/
    public function void($options)
    {
        $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
        $void = $operacionesTarjetaRepo->voidTransaction($options['transaction_id']);

        if ($void) {
            $lastCardOperations = $this->getLastCardOperations();
            return array(
                'response' => true,
                'msg' => $this->flashmessenger->getMessageString(),
                'lastCardOperations' => $lastCardOperations['lastCardOperations']
            );
        }

        return array(
            'response' => null,
            'msg' => $this->flashmessenger->getMessageString()
        );

    }
    /* END VOID*/

    public function getDataPaymentDetails($options)
    {
        $operacionesTarjetaRepo = new OperacionesTarjetasRepository();
        $result = $operacionesTarjetaRepo->getDataPayment($options['charge']);

        $data = $result['data'];
        $log = $result['log'];
        $string = '';

        if ($log) {
            foreach ($log as $operation) {
                $string .= "<tr>"
                    . "<td class='text-center' style='width:25%'> {$operation['date_formated']}</td>"
                    . "<td class='text-center' style='width:30%'> {$operation['type']}</td>"
                    . "<td class='text-right' style='width:25%'>$ " . number_format($operation['amount'], 2) . "</td>"
                    . "</tr>";
            }
        }

        $schemaReceiptOptions = array(
            '1' => 'charge',
            '2' => 'refund',
            '3' => 'refund',
            '4' => 'void'
        );

        return array(
            'response' => true,
            'sale' => $data['num_venta'],
            'phone' => $data['telefono'],
            'card' => $data['brand'] . ' ' . $data['last_4'],
            'amount' => $data['amount'],
            'status' => $data['statusName'],
            'cardPaymentsLog' => $string,
            'schemaReceipt' => $schemaReceiptOptions[$data['status']],
            'charge' => $data['reference']
        );
    }

    public function errorLogCardReader($options)
    {
        $entityRepo = new EntityRepository();
        $entityRepo->save(array('cadena' => $options['swiped'], 'created_at' => date('Y-m-d g:i:s')), '_error_log_card_reader');

        return array('response' => true);
    }

    public function mailingTicketVenta($options)
    {
        $empresa = new EmpresaEntity();
        $empresa->setOptions($empresa->getById(1));

        $venta = new VentaRepository();
        $venta = $venta->getById($options['idVenta']);

        $login = new Login();

        $emailer = new Emailer();
        $rs = $emailer->sendEmail(
            array(
                'to' => $options['email'],
                'subject' => $this->_getTranslation('Su Ticket #') . ' ' . $venta['num_venta'] . ' ' . $this->_getTranslation('de') . " " . $empresa->getNombre(),
                'message' => file_get_contents(ROOT_HOST . "/View/Tickets/email_templates/mailingTicket.php?idVenta={$options['idVenta']}"),
                'msg-success' => 'Ticket enviado correctamente.'
            )
        );

        return array(
            'response' => true,
            'message' => $this->flashmessenger->getMessageString()
        );
    }

    public function readScale($options)
    {
        $query = "SELECT value FROM scale_value WHERE id = 1";
        $result = $this->query($query);

        if ($result->num_rows > 0) {
            $result = $this->resultToArray($result)[0];
            $weight = $result['value'];
        } else {
            $weight = 0;
        }

        return array(
            'weight' => $weight
        );
    }
}