<?php
/**
 * Description of Ajax
 *
 * @author carlos
 */

class PagoAjax extends PagoRepository {
    #estaba extends a entity
    
    public function getResponse($request, $options) {
        return $this->$request($options);
    }    

    public function _getTranslation($text){
        $translator = new Translator();
        return $translator->_getTranslation($text);
    }    

    public function getListFacturasByProveedor($options){        
      //  var_dump($options); exit;
        if($options['proveedor'] === null){return null;}
        if(isset($options['proveedor']) && trim($options['proveedor'])==''){return array('response'=>true,'listFacturas'=>"");}

        $purchaseRepo = new PurchaseRepository();
        
        #facturas con saldo pendiente
        $result = $purchaseRepo->getListFacturaPendientesByProveedor(array('proveedor'=>$options['proveedor']));
      //  var_dump($result); exit;
        if($result){
            $string = '';            
            #imprimie las facturas pendientes y las facturas liquidadas (las liquidadas se ocultan)
            foreach($result as $row){
                $id = $row['id'];
                #Esto aplica para cuando se edita un pago, y se elimina una factura de Facturas a pagar.
                #$row[saldo_pendiente] trae el saldoPendiente y se suma los pagosParciales
                #Estos tr permanece oculto en FacturasPendientes Hasta que se elimina esta factura de Facturas a pagar.
                if(isset($_SESSION['pagosOriginales']) && key_exists($row['id'], $_SESSION['pagosOriginales'])){
                    $row['saldo_pendiente'] += $_SESSION['pagosOriginales'][$row['id']]['montoPago'];
                }

                $string .= "<tr id='addInvoice_{$id}'>";
                $string .= "<td class='text-center'>{$row['purchase_number']}</td>";
                $string .= "<td class='text-center'>{$row['proveedorName']}</td>";
                $string .= "<td class='text-center'>{$row['fecha']}</td>";
                $string .= "<td class='text-right'>".number_format($row['total'],2)."</td>";
                $string .= "<td class='text-right'>".number_format($row['saldo_pendiente'],2)."</td>";
                $string .= "<td class='text-center'>"
                        . "<label' onclick=\"addInvoiceToPayment('{$id}')\" class='btn btn-sm btn-primary' style='width:50px;padding:2px 4px'>"
                        . "<span class='fa fa-check fa-lg'></span>"
                        . "</label>"
                        . "</td>";
                $string .= "</tr>";          
            }
        }else{           
            $string = "<tr id='default' ><td style='text-align:center' colspan='8'>".$this->_getTranslation('No hay facturas pendientes para Proveedor seleccionado.')."</tr></td>";
        }       
          
            #imprime las facturas que se pagaron
            if(isset($_SESSION['facturasLiquidadas']) && count($_SESSION['facturasLiquidadas'])>0){             
                foreach ($_SESSION['facturasLiquidadas'] as $row){                    //var_dump($row);exit;
                    $id = $row['idFactura'];
                    $string .= "<tr id='addInvoice_{$id}'>";
                    $string .= "<td  class='text-center'>{$row['purchase_number']}</td>";                               
                    $string .= "<td  class='text-center'>{$row['proveedorName']}</td>";
                    $string .= "<td  class='text-center'>{$row['fecha']}</td>";
                    $string .= "<td  class='text-right'>".number_format($row['montoFactura'],2)."</td>";
                    $string .= "<td  class='text-right'>".number_format($row['saldoPendiente'],2)."</td>";
                    $string .= "<td class='text-center'>"
                            . "<label onclick=\"addInvoiceToPayment('{$id}')\" class='btn btn-sm btn-primary' style='width:50px;padding:2px 4px'>"
                            . "<span class='fa fa-check fa-lg'></span>"
                            . "</label>"
                            . "</td>"
                            . "</tr>";
                }

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

    public function addInvoiceToPayment($options){ 
        $idFactura = $options['idFactura'];
        //$montoTotalPago = $options['montoTotalPago'];
        $sumPagos = $options['sumPagos'];

        $entity = new PurchaseRepository();
        $pagoData = $entity->getById($idFactura);    
        //echo "<pre>";var_dump($options);echo "</pre>";exit;
        if($pagoData){  
            $form = new PagoForm();
            $form->addItem($idFactura);      

            //$_SESSION['pagosOriginales'] creada en Controller Pago
            if(isset($_SESSION['pagosOriginales']) && key_exists($idFactura, $_SESSION['pagosOriginales'])){
                $pagoData['saldo_pendiente'] += $_SESSION['pagosOriginales'][$idFactura]['montoPago'];
            }            

            /*
            if($montoTotalPago > $sumPagos){
                $disponible = $montoTotalPago - $sumPagos;
                if($disponible >= $pagoData['saldo_pendiente']){$form->setValueToElement(number_format(round($pagoData['saldo_pendiente'],2),2,'.',''), "pago[$idFactura]");}
                if($disponible < $pagoData['saldo_pendiente']){$form->setValueToElement(number_format(round($disponible,2),2,'.',''), "pago[$idFactura]");}
            }   */     
            
            
            $form->setValueToElement(number_format(round($pagoData['saldo_pendiente'],2),2,'.',''), "pago[$idFactura]");

            $element = $form->getElementString("pago[$idFactura]");
            $string = null;                        

            $string .= "<tr id='deleteInvoice_{$idFactura}'>";
            $string .= "<td class='text-center'>"
                    ."<a class='btn btn-sm btn-danger' onclick=\"deleteInvoiceFromPayment('{$idFactura}')\" ><i class='fa fa-trash'></i></a>"
                    . "</td>";

            $string .= "<td style='text-align:center'>{$pagoData['purchase_number']}</td>";
            $string .= "<td style='text-align:center'>{$pagoData['vendor_name']}</td>";
            $string .= "<td style='text-align:center'>{$pagoData['purchase_date_formated']}</td>";
            $string .= "<td style='text-align:right'>".number_format($pagoData['total'],2)."</td>";
            $string .= "<td style='text-align:right'>".number_format($pagoData['saldo_pendiente'],2)."</td>";
            $string .= "<td class='col-md-2' style='text-align:right'>$element</td>";
            $string .= "</tr>";
        }               

        return array(
            'response'=>true,
            'factura'=>$string
        );
    }
    
    public function getListFacturasByProveedorForAPReport($options){
        //  var_dump($options); exit;
        if($options['proveedor'] === null){return null;}
        if(isset($options['proveedor']) && trim($options['proveedor'])==''){return array('response'=>true,'listFacturas'=>"");}

        $entity = new PurchaseRepository();
        
        #facturas con saldo pendiente
        $result = $entity->getListFacturaPendientesByProveedor(array('proveedor'=>$options['proveedor']));
      //  var_dump($result); exit;
        if($result){
            $string = '';            
            #imprimie las facturas pendientes y las facturas liquidadas (las liquidadas se ocultan)
            foreach($result as $row){
                $id = $row['id'];

                $string .= "<tr>";                
                $string .= "<td class='text-center'>{$row['proveedorName']}</td>";
                $string .= "<td class='text-center'>{$row['purchase_number']}</td>";
                $string .= "<td class='text-center'>{$row['fecha']}</td>";
                $string .= "<td class='text-right'>".number_format($row['total'],2)."</td>";
                $string .= "<td class='text-right'>".number_format($row['saldo_pendiente'],2)."</td>";
                $string .= "<td class='text-center'>"
                        . "<label' onclick=\"$('#active_invoice').val({$row['id']});$('#modalpayVendorInvoice').modal('show')\" class='btn btn-sm btn-primary'>"
                        . "<span class='fa fa-check'></span>"
                        . "</label>"
                        . "</td>";
                $string .= "</tr>";          
            }
        }else{           
            $string = "<tr id='default' ><td style='text-align:center' colspan='8'>".$this->_getTranslation('No hay facturas pendientes para Proveedor seleccionado.')."</tr></td>";
        } 
            
         return array(
                'response'=>true,
                'listFacturas'=>$string);
    }
    
    public function payVendorInvoice($options){
        $data = array();
        foreach($options['options'] as $option){
            $data[$option['name']] = $option['value'];
        }

        $activeVendor = $data['active_vendor'];
        $activeInvoice = $data['active_invoice'];
        $entityPago = new PagoEntity();
        $entityPago->setOptions($data);
        $data = $entityPago->getOptions();
        $data['proveedor'] = $activeVendor;
        $data['pago'] = array($activeInvoice=>$data['monto']);
        
        $result = $entityPago->save($data);
        
        if($result){
            return $this->getListFacturasByProveedorForAPReport(array('proveedor'=>$activeVendor));
        } 
    }
}