<?php
/**
 * Description of Cobro
 *
 * @author carlos
 */
class CobroEntity extends CobroRepository{
    private $options = array (
        'fecha' => null,
        'idVenta' => null,
        'monto' => null,
        'formaPago' => null,
        'numCheque'=>null,
        'cuentaBancaria' => null,
        'notas' => null,
        'status'=>null,
        'ultimaModificacion' => null,
        'usuario' => null
     );
    
  public function setOptions($data){
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
      
      $this->setNotaCredito();
      $this->setUltimaModificacion();
      $this->setUsuario();
  }
  
  public function getOptions(){
      return $this->options;
  }
  
  public function setNotaCredito (){
      if($this->options['formaPago']  == '6'){
          $notaCredito = explode('-', $this->options['numCheque']);
          $this->options['numCheque'] = $notaCredito[0];
      }
  }
  
  public function getIdVenta(){
      return $this->options['idVenta'];
  }
  
  private function setUltimaModificacion(){
      $this->options['ultimaModificacion'] = date('Y-m-d H:i:s');
  }
  
   private function setUsuario(){
       $login = new Login();
       $usuario = $login->getId();
      $this->options['usuario'] = $usuario;
  }
  
  public function getDataToEditMultiple($idMultiple){
    $query = "SELECT c.*,v.cliente,"
              . "v.id as VentaId,"
              . "v.fecha as VentaFecha,"
              . "v.fecha_pago as VentaFechaPago,"
              . "fxGetMontoVenta(v.id)as VentaTotal,"
              . "fxGetMontoVenta(v.id) - fxGetMontoCobros(c.id)as VentaSaldoPendiente,"
              . "v.status as VentaStatusPago,"
              . "c.status as idStatus,"
              . "fxGetStatusName(c.status,'status','cobro') as CobroStatus "
              . "FROM cobros c,ventas v "
              . "WHERE c.idVenta = v.id "
              . "AND c.multiple = '$idMultiple' ";
      $result = $this->query($query);
      
      if($result->num_rows > 0){
        $result = $this->resultToArray($result);
            
        $arrayTemp = array();
        $arrayTemp['fecha'] = $result[0]['fecha'];
        $arrayTemp['cuentaBancaria'] = $result[0]['cuentaBancaria'];  
        $arrayTemp['status'] = $result[0]['status'];  
        
        $cobrosYaGuardados = null;
        foreach ($result as $pago){
            $fieldName = $pago['idVenta']."-".$pago['id'];
            $pagos[$fieldName] = array(
                'cobro'=>$pago['monto'],
                'formaPago'=>$pago['formaPago'],
                'numCheque'=>$pago['numCheque'],
                'status'=>$pago['CobroStatus'],
                'idStatus'=>$pago['idStatus']);
            $cobrosOriginales[$pago['VentaId']] = $pago; 
            
            $facturasLiquidadas = array();
            if($pago['VentaStatusPago']=='2'){
                $pago['VentaSaldoPendiente'] += $pago['monto'];
                $facturasLiquidadas[$pago['VentaId']] = $pago; 
            }            
        }
        $arrayTemp['cobro'] = $pagos;
        $arrayTemp['cobrosYaGuardados'] = $cobrosYaGuardados;

        return array(
            'data'=>$arrayTemp,
            'facturasLiquidadas'=>$facturasLiquidadas,
            'cobrosOriginales'=>$cobrosOriginales);   
      }         
   }
   
   public function resultSearchToExcel($options){
        $result = $this->paginationExcel($options);

        $reporte = new ReportFinanzasEntity();
        $reporte->setReporte($result);
        $reporte->setNombreReporteManual($this->_getTranslation('Cobros'));
        $startDate = $options['fechaInicio'];
        $endDate = $options['fechaFin'];
        if(trim($startDate)=='' && trim($endDate)==''){
                $startDate = $this->_getTranslation("Desde el inicio de los tiempos");
                $endDate = strftime('%B %d, %Y',strtotime('now'));
            }elseif(trim($startDate)=='' && trim($endDate)!=''){
                $startDate = $endDate;
            }elseif(trim($startDate)!='' && trim($endDate)==''){
                $endDate = $startDate;
            }
        $empresa = new EmpresaEntity();
        $empresa = $empresa->getById(1);
        $reporte->setHeaderExcelReportManual($empresa['nombre']."\n".$this->_getTranslation('Cobros')."\n".$startDate." - ".$endDate);
        $reporte->getReporteOnFile();
  }
  
  public function paginationBuscarCobro($pag,$options){
      $paginacion = new Paginacion($pag);
      $cliente = null;
      $id = null;
      $fecha = $this->createFilterFecha($options,'p.fecha');
      
      if($options['cliente']!='' && $options['cliente']!= null ){$cliente = " AND e.cliente = '".$options['cliente']."'";}
      if($options['idVenta']!='' && $options['idVenta']!= null ){$id = "AND e.id = '".$options['idVenta']."'";}
      
      $query = "SELECT 
                IF(p.multiple IS NULL,p.id,min(p.id))as id,
                IF(p.multiple IS NULL,p.id,CONCAT('PM-',p.multiple))as numPago,
                IF(p.multiple IS NULL,p.idVenta,SUBSTRING_INDEX(GROUP_CONCAT(p.idVenta SEPARATOR ','),',',3))as idVenta,
                DATE_FORMAT(p.fecha,'%b-%d-%Y') as fecha,
                e.id as idVenta,
                pr.nombre as cliente,
                p.numCheque,
                SUM(CASE WHEN (p.multiple IS NULL) OR (p.multiple IS NOT NULL AND p.status = 1) THEN monto ELSE NULL END)as monto,
                p.formaPago as idFormaPago,
                IF(p.multiple IS NULL,fxGetFormaPagoName(p.formaPago),IF(LOCATE(',',GROUP_CONCAT(DISTINCT(p.formaPago) SEPARATOR ',')) = 0,fxGetFormaPagoName(p.formaPago),'-'))as formaPago,
                IF(p.multiple IS NULL,fxGetStatusName(p.status,'status','cobro'),IF(LOCATE(',',GROUP_CONCAT(DISTINCT(p.status) SEPARATOR ',')) = 0,fxGetStatusName(p.status,'status','cobro'),'-'))as statusName,
                p.multiple,
                IFNULL(p.multiple,UUID()) as unq_id
                FROM ventas e,cobros p,clientes pr
                WHERE 1=1 
                AND e.cliente = pr.id 
                AND p.idVenta = e.id 
                $cliente  
                $id 
                $fecha
                GROUP BY(unq_id)
                ORDER BY p.fecha DESC, p.id DESC";
      $paginacion->setQueryString($query);
      $paginacion->setLayout(new Tradicional());

      return $paginacion;   
  }
  
  public function paginationExcel($options){      
      $fecha = $this->createFilterFecha($options,'p.fecha');
      $cliente = null;
      $id = null;
      
      if($options['cliente']!='' && $options['cliente']!= null ){$cliente = " AND e.cliente = '".$options['cliente']."'";}
      if($options['idVenta']!='' && $options['idVenta']!= null ){$id = "AND e.id = '".$options['idVenta']."'";}
      
      $query = "SELECT 
                IF(p.multiple IS NULL,p.id,CONCAT('PM-',p.multiple))as '".$this->_getTranslation('#pago')."',                
                DATE_FORMAT(p.fecha,'%b-%d-%Y') as '".$this->_getTranslation('fecha')."',    
                IF(p.multiple IS NULL,p.idVenta,SUBSTRING_INDEX(GROUP_CONCAT(p.idVenta SEPARATOR ','),',',3))as '".$this->_getTranslation('#venta')."',    
                pr.nombre as '".$this->_getTranslation('cliente')."',                  
                fxGetFormaPagoName(p.formaPago)as '".$this->_getTranslation('formadepago')."',    
                p.numCheque as '".$this->_getTranslation('# documento')."',    
                SUM(p.monto)as '".$this->_getTranslation('monto')."',    
                fxGetStatusName(p.status,'status','cobro')as '".$this->_getTranslation('status')."'  
                FROM ventas e,cobros p,clientes pr
                WHERE 1=1 
                AND e.cliente = pr.id 
                AND p.idVenta = e.id 
                $cliente  
                $id 
                $fecha
                GROUP BY IFNULL(p.multiple,UUID())
                ORDER BY p.fecha DESC, p.id DESC";
      
      $result = $this->query($query);
      if($result->num_rows > 0){
          return $this->resultToArray($result);
      }

      return null;   
  }
  
    public function processCardPayment(){
        $payment = new BluePay('100429263810', 'FyRv5gEz', 'TEST');

        $payment->setCustomerInformation(array(
            'firstName' => 'Bob', 
            'lastName' => 'Tester', 
            'addr1' => '1234 Test St.', 
            'addr2' => 'Apt #500', 
            'city' => 'Testville', 
            'state' => 'IL', 
            'zip' =>'54321', 
            'country' => 'USA', 
            'phone' => '1231231234', 
            'email' => 'test@bluepay.com' 
        ));

        # Set payment information for a swiped credit card transaction 
        $payment->swipe("%B4111111111111111^TEST/BLUEPAY
          ^1911101100001100000000667000000?;4111111111111111=191110110000667?");

        $payment->sale('3.00'); // Sale Amount: $3.00

        // Makes the API request with BluePAy
       $payment->process();
 
    // Reads the response from BluePay
    if($payment->isSuccessfulResponse()){
        echo 
        'Transaction Status: '. $payment->getStatus() . "\n" .
        'Transaction Message: '. $payment->getMessage() . "\n" .
        'Transaction ID: '. $payment->getTransID() . "\n" .
        'AVS Response: ' . $payment->getAVSResponse() . "\n" .
        'CVS Response: ' . $payment->getCVV2Response() . "\n" .
        'Masked Account: ' . $payment->getMaskedAccount() . "\n" .
        'Card Type: ' . $payment->getCardType() . "\n" .
        'Authorization Code: ' . $payment->getAuthCode() . "\n";
    } else{
        echo $payment->getMessage() . "\n";
    }
}

}