<?php

require ROOT.'class/Autorizhe/autoload.php';
//require_once 'constants/SampleCodeConstants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

/*PRODUCTION*/
//const MERCHANT_LOGIN_ID = "93DG8Vzf4QK";
//const MERCHANT_TRANSACTION_KEY = "3k5758V5W2rL9pgM";

/*SANDOBOX*/
const MERCHANT_LOGIN_ID = "5KP3u95bQpv";
const MERCHANT_TRANSACTION_KEY = "346HZ32z3fP4hTG2";

define("AUTHORIZENET_LOG_FILE", "phplog");

class OperacionesTarjetasRepository extends EntityRepository {

    private $table = 'operaciones_tarjetas';
    public $flashmessenger = null;
    private $request_sent_id = null;
    
    private $options = array(
        'type'=>null,
        'refId'=>null,
        'reference'=>null,
        'brand'=>null,
        'last_4'=>null,
        'expiration_date'=>null,
        'amount'=>null,
        'parent_reference'=>null,
        'id_sale'=>null
    );
    
    private $options_request = array(
        'type'=>null,
        'refId'=>null,
        'last_4'=>null,
        'expiration_date'=>null,
        'amount'=>null,
    );
      
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function setOptions($data){
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
    }
    
    public function setOptionsRequest($data){
      foreach ($this->options_request as $option => $value){
          if(isset($data[$option])){
            $this->options_request[$option] = $data[$option];
          }
      }
    }
    
    public function getOptionsRequest(){
        return $this->options_request;
    }
    
    public function _getTranslation($text){
        return $this->flashmessenger->_getTranslation($text);
    }
    
    public function saveRequest($data){       
        $data['created_date'] = date('Y-m-d H:i:s');
        parent::save($data, '_request_sent_to_authorizone');
        $this->request_sent_id =  parent::getInsertId();
    }
    
    
    public function charge($options,$retry = true){      
        $originalOptions = $options;
        $amount = $options['amount'];
        $cardNumber = $options['cardnumber'];
        $expirationDate =  $options['exp_year'].'-'.$options['exp_month'];
        $cardCode = null;
        
         // Set the transaction's refId
        $refId = 'ref' . time();
        $options['refId'] = $refId;        
        if(isset($options['cvv']) && trim($options['cvv'] !== '')){$cardCode = $options['cvv'];}
        
        $options['last_4'] = substr($options['cardnumber'], -4);
        $options['expiration_date'] = $expirationDate;
        $options['type'] = 'charge';      
        $this->setOptions($options);      
        
        $this->setOptionsRequest($options);       
        $dataRequest = $this->getOptionsRequest();
        $dataRequest['refId'] = $refId;
        $this->saveRequest($dataRequest);
       
        try {
            /* Create a merchantAuthenticationType object with authentication details
            retrieved from the constants file */
            $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
            $merchantAuthentication->setName(MERCHANT_LOGIN_ID);
            $merchantAuthentication->setTransactionKey(MERCHANT_TRANSACTION_KEY);          

            // Create the payment data for a credit card
            $creditCard = new AnetAPI\CreditCardType();
            $creditCard->setCardNumber($cardNumber);
            $creditCard->setExpirationDate($expirationDate);
            if($cardCode){$creditCard->setCardCode($cardCode);}            

            // Add the payment data to a paymentType object
            $paymentOne = new AnetAPI\PaymentType();
            $paymentOne->setCreditCard($creditCard);

            // Create order information/
            /*
            $order = new AnetAPI\OrderType();
            $order->setInvoiceNumber("10101");
            $order->setDescription("Golf Shirts");*/

            // Set the customer's Bill To address
            /*
            $customerAddress = new AnetAPI\CustomerAddressType();
            $customerAddress->setFirstName("Ellen");
            $customerAddress->setLastName("Johnson");
            $customerAddress->setCompany("Souveniropolis");
            $customerAddress->setAddress("14 Main Street");
            $customerAddress->setCity("Pecan Springs");
            $customerAddress->setState("TX");
            $customerAddress->setZip("44628");
            $customerAddress->setCountry("USA");*/

            // Set the customer's identifying information
            /*
            $customerData = new AnetAPI\CustomerDataType();
            $customerData->setType("individual");
            $customerData->setId("99999456654");
            $customerData->setEmail("EllenJohnson@example.com");*/

            // Add values for transaction settings            
            $duplicateWindowSetting = new AnetAPI\SettingType();
            $duplicateWindowSetting->setSettingName("duplicateWindow");
            $duplicateWindowSetting->setSettingValue("15");

            // Add some merchant defined fields. These fields won't be stored with the transaction,
            // but will be echoed back in the response.
            /*
            $merchantDefinedField1 = new AnetAPI\UserFieldType();
            $merchantDefinedField1->setName("customerLoyaltyNum");
            $merchantDefinedField1->setValue("1128836273");

            $merchantDefinedField2 = new AnetAPI\UserFieldType();
            $merchantDefinedField2->setName("favoriteColor");
            $merchantDefinedField2->setValue("blue");*/

            // Create a TransactionRequestType object and add the previous objects to it
            $transactionRequestType = new AnetAPI\TransactionRequestType();
            $transactionRequestType->setTransactionType("authCaptureTransaction");
            $transactionRequestType->setAmount($amount);
            //$transactionRequestType->setOrder($order);
            $transactionRequestType->setPayment($paymentOne);
            //$transactionRequestType->setBillTo($customerAddress);
            //$transactionRequestType->setCustomer($customerData);
            $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
            //$transactionRequestType->addToUserFields($merchantDefinedField1);
            //$transactionRequestType->addToUserFields($merchantDefinedField2);

            // Assemble the complete transaction request
            $request = new AnetAPI\CreateTransactionRequest();
            $request->setMerchantAuthentication($merchantAuthentication);
            $request->setRefId($refId);
            $request->setTransactionRequest($transactionRequestType);

            // Create the controller and get the response
            $controller = new AnetController\CreateTransactionController($request);
            $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
            
            $entityRepo = new EntityRepository();
            /*if(isset($retry) && !is_null($retry)){$response = null;}*/
            if ($response != null) {
                // Check to see if the API request was successfully received and acted upon
                if ($response->getMessages()->getResultCode() == "Ok") {
                    // Since the API request was successful, look for a transaction response
                    // and parse it to display the results of authorizing the card
                    $tresponse = $response->getTransactionResponse();
                    //if ($tresponse != null && $tresponse->getMessages() != null) {
                    if ($tresponse != null && $tresponse->getResponseCode() == '1') {
                        /*
                        echo " Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n";
                        echo " Transaction Response Code: " . $tresponse->getResponseCode() . "\n";
                        echo " Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n";
                        echo " Auth Code: " . $tresponse->getAuthCode() . "\n";
                        echo " Description: " . $tresponse->getMessages()[0]->getDescription() . "\n";       
                         */                 
                        $this->flashmessenger->addMessage(array('success'=>'Pago con tarjeta realizado correctamente.'));
                        $this->saveCharge($tresponse);
                        return $tresponse->getTransId();
                        
                    } else {
                        $error = '';
                        if($tresponse->getResponseCode() == '2'){
                            $this->flashmessenger->addMessage(array('danger'=>'Transaccion declinada.'));
                            $error .= "Transaccion declinada";
                        }
                        
                        if ($tresponse->getErrors() != null) {
                           
                            $this->flashmessenger->addMessage(array('danger'=> $tresponse->getErrors()[0]->getErrorText()));
                            $error .= "Error Code: " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                            $error .= "Error Message: " . $tresponse->getErrors()[0]->getErrorText() . "\n";                            
                           
                            $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');                           
                        }             
                        return null;
                    }
                    
                    // Or, print errors if the API request wasn't successful
                } else {
                    $tresponse = $response->getTransactionResponse();
                    
                    if ($tresponse != null && $tresponse->getErrors() != null) {
                        $duplicate_transaction = '';
                        if($tresponse->getErrors()[0]->getErrorCode() == 11){
                            $duplicate_transaction = ' Original transaction: '.$tresponse->getTransId(); 
                            
                            /*Aqui entra cuando hacemos es segundo intento porque el servicio no nos dio respuesta*/
                            if(is_null($retry)){
                                $this->flashmessenger->addMessage(array('success'=>'Pago con tarjeta realizado correctamente 2.'));
                                $this->saveCharge($tresponse);
                                return $tresponse->getTransId();
                            }                            
                        }                        
                        
                        $this->flashmessenger->addMessage(array('danger'=> $tresponse->getErrors()[0]->getErrorText().$duplicate_transaction));
                        $error = " Error Code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                        $error .= " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . " $duplicate_transaction\n";
                    } else {
                        $this->flashmessenger->addMessage(array('danger'=>$response->getMessages()->getMessage()[0]->getText()));
                        $error = " Error Code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                        $error .= " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . " $duplicate_transaction\n";
                    }
                    
                    $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');
                    return null;
                }
            } else {
               //echo  "No response returned \n";
               if(isset($retry) && !is_null($retry)){            
                   sleep(2);
                   return $this->charge($originalOptions,null);
               }else{
                    $this->flashmessenger->addMessage(array('danger'=>'Servicio sin respuesta.'));  
                    return null;
               }              
            }

        }
        catch (Exception $e) {
            $this->flashmessenger->addMessage(array('danger'=>$e->getMessage()));
            return null;
        }
        
        //return 500;
    }
    
    public function refund($options){
        $refTransId = $options['charge'];
        $amount = $options['amount'];
        $chargeData = $this->getByReference($refTransId);
        
        $this->options['type'] = 'refund';
        $this->options['amount'] = $amount;
        $this->options['parent_reference'] = $refTransId;
        $this->options['id_sale'] = $chargeData['id_sale'];
        
        $this->setOptionsRequest($this->options);    
        $dataRequest = $this->getOptionsRequest();        
        $dataRequest['refId'] = $refTransId;
        $this->saveRequest($dataRequest);
        
        try {
            /* Create a merchantAuthenticationType object with authentication details
            retrieved from the constants file */
            $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
            $merchantAuthentication->setName(MERCHANT_LOGIN_ID);
            $merchantAuthentication->setTransactionKey(MERCHANT_TRANSACTION_KEY);
            
            // Create the payment data for a credit card
            $creditCard = new AnetAPI\CreditCardType();
            $creditCard->setCardNumber($chargeData['last_4']);
            $creditCard->setExpirationDate('XXXX');/*Asi se debe enviar*/
            $paymentOne = new AnetAPI\PaymentType();
            $paymentOne->setCreditCard($creditCard);

            //create a transaction
            $transactionRequest = new AnetAPI\TransactionRequestType();
            $transactionRequest->setTransactionType( "refundTransaction"); 
            $transactionRequest->setAmount($amount);
            $transactionRequest->setPayment($paymentOne);
            $transactionRequest->setRefTransId($refTransId);

            $request = new AnetAPI\CreateTransactionRequest();
            $request->setMerchantAuthentication($merchantAuthentication);
            $request->setTransactionRequest( $transactionRequest);
            $controller = new AnetController\CreateTransactionController($request);
            $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
            
            $entityRepo = new EntityRepository();
            if ($response != null){
                if($response->getMessages()->getResultCode() == "Ok"){
                    $tresponse = $response->getTransactionResponse();        
                    if ($tresponse != null && $tresponse->getMessages() != null){
                        /*
                        echo " Transaction Response code : " . $tresponse->getResponseCode() . "\n";
                        echo "Refund SUCCESS: " . $tresponse->getTransId() . "\n";
                        echo " Code : " . $tresponse->getMessages()[0]->getCode() . "\n"; 
                        echo " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";*/
                        
                        $this->flashmessenger->addMessage(array('success'=>'Reembolso realizado correctamente.'));
                        $this->saveRefund($tresponse);
                        
                        return $tresponse->getTransId();
                    }
                    else{                        
                        if($tresponse->getErrors() != null){
                            $error = " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                            $error .=" Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";            
                        }
                        
                        $this->flashmessenger->addMessage(array('danger'=>$tresponse->getErrors()[0]->getErrorText()));
                        
                        $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');
                        return null;
                    }
                }
                else{                    
                    $tresponse = $response->getTransactionResponse();
                    if($tresponse != null && $tresponse->getErrors() != null){
                        $error = " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . " => $refTransId\n";
                        $error .=" Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";    
                        $errorText = $tresponse->getErrors()[0]->getErrorText();
                    }
                    else{
                        $error = " Error code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                        $error .= " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
                        $errorText = $response->getMessages()->getMessage()[0]->getText();
                    }
                    
                    $this->flashmessenger->addMessage(array('danger'=>$errorText));
                    
                    $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');
                    return null;
                }      
            }
            else{
                //echo  "No response returned \n";
                $this->flashmessenger->addMessage(array('danger'=>'Servicio sin respuesta.'));
                return null;
            }
            return $response;
                
            }
            catch (Exception $e) {
                $this->flashmessenger->addMessage(array('danger'=>$e->getMessage()));
                return null;
            }
    }
    
    public function voidTransaction($transactionid){    
    $chargeData = $this->getByReference($transactionid);
        
    $this->options['type'] = 'void';
    $this->options['amount'] = $chargeData['amount'];
    $this->options['parent_reference'] = $transactionid;
    $this->options['id_sale'] = $chargeData['id_sale'];
    
    // Set the transaction's refId
    $refId = 'ref' . time();
    
    $this->setOptionsRequest($this->options);       
    $dataRequest = $this->getOptionsRequest();
    $dataRequest['refId'] = $transactionid;
    $this->saveRequest($dataRequest);
    
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(MERCHANT_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(MERCHANT_TRANSACTION_KEY);  

    //create a transaction
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType( "voidTransaction"); 
    $transactionRequestType->setRefTransId($transactionid);

    $request = new AnetAPI\CreateTransactionRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setRefId($refId);
    $request->setTransactionRequest( $transactionRequestType);
    $controller = new AnetController\CreateTransactionController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
    
    $entityRepo = new EntityRepository();
    if ($response != null){
        if($response->getMessages()->getResultCode() == "Ok"){
            $tresponse = $response->getTransactionResponse();
        
            if ($tresponse != null && $tresponse->getMessages() != null){/*
                echo " Transaction Response code : " . $tresponse->getResponseCode() . "\n";
                echo " Void transaction SUCCESS AUTH CODE: " . $tresponse->getAuthCode() . "\n";
                echo " Void transaction SUCCESS TRANS ID  : " . $tresponse->getTransId() . "\n";
                echo " Code : " . $tresponse->getMessages()[0]->getCode() . "\n"; 
                echo " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";*/
                $this->flashmessenger->addMessage(array('success'=>'Pago con tarjeta cancelado correctamente.'));
                $this->saveVoid($tresponse);
                
                return true;
                //return $tresponse->getTransId();
                
            }
            else{                
                $this->flashmessenger->addMessage(array('danger'=>'Transaction Failed.'));
                $error = 'Transaction Failed.';
                if($tresponse->getErrors() != null){
                    $this->flashmessenger->addMessage(array('danger'=>$tresponse->getErrors()[0]->getErrorText()));
                    $error = " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                    $error .=" Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";            
                }

                $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');
                return null;
            }
        }else{                       
            $tresponse = $response->getTransactionResponse();
            if($tresponse != null && $tresponse->getErrors() != null){
                $this->flashmessenger->addMessage(array('danger'=>$tresponse->getErrors()[0]->getErrorText()));
                $error = " Error code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                $error .=" Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";                      
            }
            else{
                $this->flashmessenger->addMessage(array('danger'=>$response->getErrors()[0]->getErrorText()));
                $error = " Error code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                $error .= " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
            }

            $entityRepo->save(array('request_sent_id'=>$this->request_sent_id,'cadena'=>$error,'created_at'=>date('Y-m-d H:i:s')), '_error_log_card_reader');
            return null;
        }      
    }
    else{
        $this->flashmessenger->addMessage(array('danger'=>'Servicio sin respuesta.'));
        return null;
    }

    return $response;
  }

    public function _save($data, $table = null) {        
        if($data['object'] == 'charge'){
            return $this->saveCharge($data);
        }elseif($data['object'] == 'refund'){
            return $this->saveRefund($data);
        }
    }
    
     public function saveCharge($charge){
        $login = new Login();     
        $data = array( 
                'type'=>$this->options['type'],
                'refId'=>$this->options['refId'],
                'reference'=>$charge->getTransId(),
                'receipt_number'=>'',
                'brand'=>$charge->getAccountType(),
                'last_4'=>$this->options['last_4'],
                'expiration_date'=>$this->options['expiration_date'],
                'amount'=>$this->options['amount'],
                'status'=>'1',
                'creado_fecha'=>date('Y-m-d H:i:s'),
                'creado_por'=>$login->getId(),
                'id_store'=>$login->getSucursal());
        
        return parent::save($data, $this->table);
    }
    
    public function saveRefund($refund){
        $login = new Login();        
        $data = array( 
                'type'=>$this->options['type'],
                'reference'=>$refund->getTransId(),
                'parent_reference'=>$this->options['parent_reference'],
                'id_sale'=>$this->options['id_sale'],
                'amount'=>$this->options['amount'],
                'status'=>'1',
                'creado_fecha'=>date('Y-m-d H:i:s'),
                'creado_por'=>$login->getId(),
                'id_store'=>$login->getSucursal());
        
        $rs = parent::save($data, $this->table);
        if($rs){
            $rs = $this->addRefundToCharge($this->options['parent_reference'],$this->options['amount']);
            if(!$rs){
                return null;
            }
        }
        return true;
    }
    
    public function addRefundToCharge($reference,$amount){        
        $query = "UPDATE $this->table SET refund_amount = (IFNULL(refund_amount,0) + $amount) WHERE reference = '$reference'";
        $result = $this->query($query);
        
        if($result){
            $this->setStatusAfterRefund($reference);
            return true;         
        }
        return null;
    }
    
    public function setStatusAfterRefund($reference){
        $charge = $this->getByReference($reference);
        
        if($charge['amount'] == $charge['refund_amount']){
            $status = '3';
        }elseif($charge['refund_amount'] != 0 && $charge['refund_amount'] < $charge['amount']){
            $status = '2';
        }
        
        $query = "UPDATE $this->table SET status = '$status' WHERE reference = '$reference'";
        $result = $this->query($query);
        
        if($result){
            return true;
        }
        
        return null;
    }
    
    public function saveVoid($refund){
        $login = new Login();        
        $data = array( 
                'type'=>$this->options['type'],
                'reference'=>$refund->getTransId(),
                'parent_reference'=>$this->options['parent_reference'],
                'id_sale'=>$this->options['id_sale'],
                'amount'=>$this->options['amount'],
                'status'=>'1',
                'creado_fecha'=>date('Y-m-d H:i:s'),
                'creado_por'=>$login->getId(),
                'id_store'=>$login->getSucursal());
        
        $rs = parent::save($data, $this->table);
        if($rs){
            $query = "UPDATE $this->table SET status = '4' WHERE reference = '{$this->options['parent_reference']}'";
            $result = $this->query($query);
            
            if($result){
                return true;
            }
        }
        return null;
    }
    
    public function getByReference($reference){
        $query = "SELECT o.*,"
                . "v.num_venta,"
                . "DATE_FORMAT(o.creado_fecha,'%m/%d/%Y %H:%i')as date_formated, "
                . "IFNULL(o.refund_amount,0)as refund_amount,"
                . "IFNULL(o.id_sale,0)as id_sale,"
                . "fxGetStatusName(o.status,'status','Charge')as statusName "
                . "FROM $this->table o LEFT JOIN ventas v ON o.id_sale = v.id "
                . "WHERE o.reference = '$reference'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result)[0];
        }
        return null;
    }
    
    public function delete($id, $table = null) {        
        return parent::delete($id, $this->table);
    }

    public function update($id, $data, $table = null) {        
        return parent::update($id, $data, $this->table);
    }

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table,$selectAux);
    }
    
    public function getChargesWithBalanceByIdSale($idSale){
        $query = "SELECT * FROM $this->table WHERE id_sale = '$idSale' AND type = 'charge' AND (amount - IFNULL(refund_amount,0)) > 0  ";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return $this->resultToArray($result);
        }
        return null;
    }
    
   public function getListaOperacionesTarjetas($options = null) {
        $idSucursal = null;
        $type = null;
        $sale_id = null;
        $date = $this->createFilterFecha($options,'DATE(o.creado_fecha)');
        
        if($options){
            if(isset($options['type'])){$type = " AND o.type = '{$options['type']}'";}
            if(isset($options['store_id'])){$idSucursal = " AND o.id_store = '{$options['store_id']}'";}
            if(isset($options['sale_id'])){$sale_id = " AND o.id_sale = '{$options['sale_id']}'";}
        }
        
        $select = "SELECT o.*,v.num_venta, "
                . "fxGetStatusName(o.status,'status','Charge')as statusName,"
                . "DATE_FORMAT(o.creado_fecha,'%m/%d/%y %h:%i%p')as date_formated "
                . "FROM $this->table o "
                . "LEFT JOIN ventas v ON o.id_sale = v.id $idSucursal "
                . "WHERE 1 = 1 "
                . "$type "
                . "$date "
                . "$sale_id "
                . "ORDER BY o.id DESC";
        
        $result = $this->query($select);

        if ($result) {
           return $this->resultToArray($result);
        }
        return null;
    }
    
    public function setIdSale($reference,$idSale){
        $query = "UPDATE $this->table SET id_sale = '$idSale' WHERE reference = '$reference'";
        $result = $this->query($query);
        
        if($result){
            return true;
        }
        return null;            
    }
    
    public function getDataPayment($reference){
        $log = null;
        $data = $this->getByReference($reference);
        
        $query = "SELECT *,"
                . "DATE_FORMAT(creado_fecha,'%m/%d/%Y %H:%i')as date_formated "
                . " FROM $this->table "
                . "WHERE reference = '$reference' OR parent_reference = '$reference' "
                . "ORDER BY id DESC";        
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $log = $this->resultToArray($result);
        }
        
        return array(
            'data'=>$data,
            'log'=>$log
        );
        
    }
    
    public function createFilterFecha($options,$campoFecha = null ){
        if(!isset($options['fechaInicio']) && !isset($options['fechaFin'])){return null;}        
        $fechaInicio = null;
        $fechaFin = null;
        $fecha = null;
        $tools = new Tools();
        
        if(isset($options['fechaInicio'])){$fechaInicio = $options['fechaInicio'];}
        if(isset($options['fechaFin'])){$fechaFin = $options['fechaFin'];}
        
        if($fechaInicio!=null){
            $fechaInicio = $tools->setFormatDateToDB($fechaInicio);
            if($fechaFin!=null){
                $fechaFin = $tools->setFormatDateToDB($fechaFin);
                $fecha .=" AND $campoFecha BETWEEN '{$fechaInicio}' AND '{$fechaFin}' ";
            }else{
                $fecha .=" AND $campoFecha BETWEEN '{$fechaInicio}' AND '{$fechaInicio}' ";
            }
        }elseif($fechaFin!=null){
            $fecha .=" AND $campoFecha BETWEEN '{$fechaFin}' AND '{$fechaFin}' ";
        }
        
        return $fecha;
    }
}