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

class CustomerPaymentAjax extends CustomerPaymentRepository {
    #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 getListFacturasByCustomer($options){        
        //var_dump($options); exit;
        if($options['customer'] === null || $options['to_store'] === null){return null;} //UG agrego el to_store para conciderar en consulta
        if(isset($options['customer']) && trim($options['customer'])=='' || isset($options['to_store']) && trim($options['to_store'])==''){return array('response'=>true,'listFacturas'=>"");}

        if(!isset($options['startDate']) || !isset($options['endDate'])){
            $options['startDate']= '';
            $options['endDate']= '';

        }
        $purchaseRepo = new InvoiceRepository();
        $store_balance = "0.00";  
        #facturas con saldo pendiente
        $result = $purchaseRepo->getListFacturaPendientesByCustomer(array('customer'=>$options['customer'], 'to_store' => $options['to_store'], 'startDate'=> $options['startDate'], 'endDate' => $options['endDate'] ));
        #UG obtener saldos_sucursales para mostrar en customer payment view
        $customerPaymentRepo = new CustomerPaymentRepository();
        $result_saldosSucursales = $customerPaymentRepo->getSaldosSucursales($options['customer'], $options['to_store']);
        $string_saldoRestante = '';
        $saldo_restante_sucursal = "0.00";
        //var_dump($result_saldosSucursales);
        if(isset($result_saldosSucursales)){

            foreach($result_saldosSucursales as $row){
                $id = $row['saldo_id'];
                
               

                $string_saldoRestante .= "<tr id='addInvoice_{$id}'>";
              
                $string_saldoRestante .= "<td class='text-center'>{$row['saldo_restante']}</td>";
                $string_saldoRestante .= "<td class='text-center'>{$row['formatedDate']}</td>";              
                $string_saldoRestante .= "<td class='text-center'>"
                        . "<label' onclick=\"addSaldoSucursal('{$row['saldo_restante']}','{$id}')\" class='btn btn-sm btn-primary' style='width:50px;padding:2px 4px'>"
                        . "<span class='fa fa-check fa-lg'></span>"
                        . "</label>"
                        . "</td>";
                $string_saldoRestante .= "</tr>";
                
                $saldo_restante_sucursal += $row['saldo_restante']; #UG guardamos el acumulado de saldos restantes para print 
            }           
        }else{
            $saldo_restante_sucursal = "0.00";
        }
      //  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[balance] 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['balance'] += $_SESSION['pagosOriginales'][$row['id']]['paymentAmount'];
                }

                $string .= "<tr id='addInvoice_{$id}'>";
                $string .= "<td class='text-center'>{$row['invoice_num']}</td>";
               
                $string .= "<td class='text-center'>{$row['noPedido']}</td>";
                $string .= "<td class='text-center'>{$row['formatedDate']}</td>";
                $string .= "<td class='text-center'>{$row['formatedDueDate']}</td>";
                $string .= "<td class='text-right'>".number_format($row['total'],2)."</td>";
                $string .= "<td class='text-right'>".number_format($row['balance'],2)."</td>";
                $string .= "<td class='text-center'>"
                        . "<label' onclick=\"addInvoiceToPaymentCustomer('{$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>";
                
                $store_balance += $row['balance']; #UG guardamos el balance por store, tomando en cuenta solo este foreach
            }
        }else{           
            //$string = "<tr id='default' ><td class='text-center' colspan='8'>".$this->_getTranslation('No hay facturas pendientes para Customer seleccionado.')."</tr></td>";
             $string = ""; /*lo mando asi, porque colspan no es compatible con datatable*/
        }       
          
            #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['invoice_id'];
                    $string .= "<tr id='addInvoice_{$id}'>";
                    $string .= "<td class='text-center'>{$row['invoice_num']}</td>";                             
                   
                    $string .= "<td  class='text-center'>{$row['noPedido']}</td>";  
                    $string .= "<td  class='text-center'>{$row['formatedDate']}</td>";
                    $string .= "<td  class='text-center'>{$row['formatedDueDate']}</td>";
                    $string .= "<td  class='text-right'>".number_format($row['amountFactura'],2)."</td>";
                    $string .= "<td  class='text-right'>".number_format($row['balance'],2)."</td>";
                    $string .= "<td class='text-center'>"
                            . "<label onclick=\"addInvoiceToPaymentCustomer('{$row['balance']}')\" 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,
                'store_balance'=> $store_balance,#Enviamos ese monto al view de customerPayment
                'listSaldosRestantes' => $string_saldoRestante,
                'result_saldosSucursales' => $saldo_restante_sucursal); #UG enviamos el total de saldo restante por sucursal y customer
    }    

    public function addInvoiceToPaymentCustomer($options){ 
        $invoice_id = $options['invoice_id'];
        $montoTotalPayment = $options['montoTotalPago'];
        $sumPayments = $options['sumPagos'];

        $entity = new InvoiceRepository();
        $pagoData = $entity->getById($invoice_id);    
        //echo "<pre>";var_dump($options);echo "</pre>";exit;
        if($pagoData){  
            $form = new CustomerPaymentForm();
            $form->addItem($invoice_id);            

            //$_SESSION['pagosOriginales'] creada en Controller CustomerPayment
            if(isset($_SESSION['pagosOriginales']) && key_exists($invoice_id, $_SESSION['pagosOriginales'])){
                $pagoData['balance'] += $_SESSION['pagosOriginales'][$invoice_id]['paymentAmount'];
            }            
            
            if($montoTotalPayment > $sumPayments){
                $disponible = $montoTotalPayment - $sumPayments;
                if($disponible >= $pagoData['balance']){$form->setValueToElement(number_format(round($pagoData['balance'],2),2,'.',''), "pago[$invoice_id]");}
                if($disponible < $pagoData['balance']){$form->setValueToElement(number_format(round($disponible,2),2,'.',''), "pago[$invoice_id]");}
            }        
            
            $element = $form->getElementString("pago[$invoice_id]");
            $string = null;                        

            $string .= "<tr id='deleteInvoice_{$invoice_id}'>";
            $string .= "<td class='text-center'>"
                    ."<a class='btn btn-sm btn-danger' onclick=\"deleteInvoiceFromPayment('{$invoice_id}')\" ><i class='fa fa-trash'></i></a>"
                    . "</td>";
            
            $string .= "<td class='text-center'>{$pagoData['invoice_num']}</td>";
            $string .= "<td class='text-center'>{$pagoData['customerName']}</td>";
            $string .= "<td class='text-center'>{$pagoData['customer_po']}</td>";
            $string .= "<td class='text-center'>{$pagoData['formatedDate']}</td>";
            $string .= "<td class='text-center'>{$pagoData['formatedDueDate']}</td>";
            $string .= "<td class='text-right'>".number_format($pagoData['total'],2)."</td>";
            $string .= "<td class='text-right'>".number_format($pagoData['balance'],2)."</td>";
            $string .= "<td class='col-md-2' class='text-right'>$element</td>";
            $string .= "</tr>";
        }               

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

        $entity = new InvoiceRepository();
        
        #facturas con saldo pendiente
        $result = $entity->getListFacturaPendientesByCustomer(array('customer'=>$options['customer']));
      //  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['customerName']}</td>";
                $string .= "<td class='text-center'>{$row['customer_po']}</td>";
                $string .= "<td class='text-center'>{$row['formatedDate']}</td>";
                $string .= "<td class='text-center'>{$row['formatedDueDate']}</td>";
                $string .= "<td class='text-right'>".number_format($row['total'],2)."</td>";
                $string .= "<td class='text-right'>".number_format($row['balance'],2)."</td>";
                $string .= "<td class='text-center'>"
                        . "<label' onclick=\"$('#active_invoice').val({$row['id']});$('#modalpayCustomerInvoice').modal('show')\" class='btn btn-sm btn-primary'>"
                        . "<span class='fa fa-check'></span>"
                        . "</label>"
                        . "</td>";
                $string .= "</tr>";          
            }
        }else{           
            //$string = "<tr id='default' ><td class='text-center' colspan='8'>".$this->_getTranslation('No hay facturas pendientes para Cliente seleccionado.')."</tr></td>";
             $string = ""; /*lo mando asi, porque colspan no es compatible con datatable*/
        } 
            
         return array(
                'response'=>true,
                'listFacturas'=>$string);
    }
    
    public function payCustomerInvoice($options){
        $data = array();
        foreach($options['options'] as $option){
            $data[$option['name']] = $option['value'];
        }

        $activeCustomer = $data['active_vendor'];
        $activeInvoice = $data['active_invoice'];
        $entityCustomerPayment = new CustomerPaymentEntity();
        $entityCustomerPayment->setOptions($data);
        $data = $entityCustomerPayment->getOptions();
        $data['customer'] = $activeCustomer;
        $data['pago'] = array($activeInvoice=>$data['monto']);
        
        $result = $entityCustomerPayment->save($data);
        
        if($result){
            return $this->getListFacturasByCustomerForAPReport(array('customer'=>$activeCustomer));
        } 
    }
}