<?php
session_start();
error_reporting(0);
//date_default_timezone_set('America/Guatemala');
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
date_default_timezone_set('America/Guatemala');
$serverName = "10.238.26.69";
$connectionInfo = array( "Database"=>"AGORA_2020", "UID"=>"SA", "PWD"=>"masterkey", "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if(isset($_POST['meth']) || isset($_GET['meth'])){
    
	$metodo = '';
	
	if(isset($_POST['meth'])){
		$metodo = $_POST['meth'];
	}else{
		$metodo = $_GET['meth'];
	}
    
    
    if($metodo == 'geDatosComporbante'){

        $monto = $_POST['valorTexto'];
        setlocale(LC_ALL,"es_ES");

        $diassemana = array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sábado");
        $meses = array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
        
        $fecha =  $diassemana[date('w')]." ".date('d')." de ".$meses[date('n')-1]. " ".date('Y');

        $monmtoEnTecto = number_words("$monto","Quetzales","con","ctv");

        $json['fecha'] =  $fecha;
        $json['monto'] =  $monmtoEnTecto;        

        $trasancion = $_SESSION['IdSession'];
        $sql = "EXECUTE JOIN_ABONOS_RECIBO '".$trasancion."'";
        
        $stmt = sqlsrv_prepare($conn, $sql, array(&$docentry, &$serie));
        if( sqlsrv_execute( $stmt ) === false ) {
            die( print_r( sqlsrv_errors(), true));
            return false; 
        }

        

        while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {

            $_SESSION['ComporbanteNumTran'] = $row['SERIE'].'-'.$row['RECIBO'];
            $json['ComporbanteNumTran'] = $row['SERIE'].'-'.$row['RECIBO'];
            //echo json_encode($row);
        }


        echo json_encode($json);
        return json_encode($json);

    }
    //METODO RECUPERAR LAS FACTURAS
    if($metodo == 'getFac'){

    
        $id = $_POST['id'];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "http://10.238.26.72:8083/api/FC?CardCode=".$id);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        $resJson = json_decode($res);
        
        //var_dump($resJson);
        if($resJson[0]->CardCode != 'NO EXISTE'){
            echo $res;
        }else{
            echo $res;
        }

        $_SESSION['facPorcesar'] = json_decode($res);

        curl_close($ch);
        //return;
    }
    //METRODOD RECUPERAR LOS DEPOSITOS DE UN CLIENTE
    if($metodo == 'getDepos'){

        $cardCode= $_POST['cardCode'];
        //$cardCode= 100876;
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "http://10.238.26.72:8083/api/DEPOSITO?CARDCODE=".$cardCode);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        $resJson = json_decode($res);
        curl_close($ch);
        //var_dump($resJson);
        if($resJson[0]->DocEntry > 0 ){
            echo $res;
        }else{
            echo $res;
        }

        $_SESSION['depositos'] = json_decode($res);
    
        //return;
    }
    //METRODOD RECUPERAR LAS NOTAS DE CREDITO DE UN CLIENTE
    if($metodo == 'getNCreditos'){

        $cardCode= $_POST['cardCode'];
        //$cardCode= 100876;
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "http://10.238.26.72:6083/api/NotaCredito?CardCode=".$cardCode);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        $resJson = json_decode($res);
        curl_close($ch);
        //var_dump($resJson);
        if($resJson[0]->TrackNo > 0 ){
            echo $res;
        }else{
            echo $res;
        }

        $_SESSION['NotasCredito'] = json_decode($res);

        return;
    }
    //recupera los datos del cajero y del cliente
    if($metodo == 'getLogin'){

        $json= array();

        $docentry = $_POST['cardCode'];
        $serie = $_POST['serie'];
        $codCajero = $_POST['codCajero'];

        $_SESSION['CardCodeCl'] = $docentry;
        $_SESSION['SerieFront'] = $serie;
        $_SESSION['CodCajero'] = $codCajero;
		//$_SESSION['CodCaja'] = $codCajero;
        $_SESSION['IdSession'] = $serie.'-'.$docentry.'-'.date("YmdHis");

        if( $conn === false) {
            die( print_r( sqlsrv_errors(), true));
            return false;
        }

        $docentry = intval($docentry);
        $codCajero = intval($codCajero);

        $sql = "EXECUTE JOIN_ABONOS_LOGIN ".$docentry.",'".$serie."',".$codCajero;
        //$json['val'] = $codCajero;
        $stmt = sqlsrv_prepare($conn, $sql, array());
		
        if( sqlsrv_execute( $stmt ) === false ) {
            die( print_r( sqlsrv_errors(), true));
            return false; 
        }

        

        while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {

            array_push($json,$row);
            $_SESSION['CodCaja'] = $row['CAJA'];
            //echo json_encode($row);
        }

        $result = json_encode($json);
        echo $result;

    }
    //recupera las series
    if($metodo == 'getSeries'){

        if( $conn === false) {
            die( print_r( sqlsrv_errors(), true));
            return false;
        }

        $sql = "EXECUTE JOIN_ABONOS_SERIES";

        $stmt = sqlsrv_prepare($conn, $sql);
        if( sqlsrv_execute( $stmt ) === false ) {
            die( print_r( sqlsrv_errors(), true));
            return false; 
        }
        $json= array();

        while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {

            array_push($json,$row);
            //echo json_encode($row);
        }

        $result = json_encode($json);
        echo $result;

    }

    //recupera los nombres de cajeros
    if($metodo == 'getCajeros'){

        if( $conn === false) {
            die( print_r( sqlsrv_errors(), true));
            return false;
        }
        
        $sql = "EXECUTE JOIN_ABONOS_CAJEROS";
 
        $stmt = sqlsrv_prepare($conn, $sql, array());
        if( sqlsrv_execute( $stmt ) === false ) {
            die( print_r( sqlsrv_errors(), true));
            return false; 
        }

        $json= array();

        while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {

            array_push($json,$row);
            //echo json_encode($row);
        }

        $result = json_encode($json);
        echo $result;

        // switch(json_last_error()) {
        //     case JSON_ERROR_NONE:
        //         echo ' - Sin errores';
        //     break;
        //     case JSON_ERROR_DEPTH:
        //         echo ' - Excedido tamaño máximo de la pila';
        //     break;
        //     case JSON_ERROR_STATE_MISMATCH:
        //         echo ' - Desbordamiento de buffer o los modos no coinciden';
        //     break;
        //     case JSON_ERROR_CTRL_CHAR:
        //         echo ' - Encontrado carácter de control no esperado';
        //     break;
        //     case JSON_ERROR_SYNTAX:
        //         echo ' - Error de sintaxis, JSON mal formado';
        //     break;
        //     case JSON_ERROR_UTF8:
        //         echo ' - Caracteres UTF-8 malformados, posiblemente codificados de forma incorrecta';
        //     break;
        //     default:
        //         echo ' - Error desconocido';
        //     break;
        // }

        //var_dump($json);
    }

    //METRODOD RECUPERAR LAS NOTAS DE CREDITO DE UN CLIENTE
    if($metodo == 'setPagos'){

        $jsonResult = array();
		$jsonResult1 = array();
        $carCode = $_POST['carCode'];
        $valorDepos = $_POST['depos'];
        $valorNCred = $_POST['nCred'];
        $valorEfectivo = $_POST['efectivoVal'];
        $valorCheque = $_POST['Cheque'];
        $valorTC = $_POST['tarjetaC'];

        $VoucherTC = $_POST['voucherTCP'];
        $numChequeP = $_POST['numeroChequeP'];
        $CodTCSAP = $_POST['CodTCreditoPagar'];

        $codTCICG = 0;

        if($CodTCSAP == 1 ){
            $codTCICG = 8;
        }elseif($CodTCSAP == 2 ){
            $codTCICG = 7;
        }elseif($CodTCSAP == 3 ){
            $codTCICG = 9;
        }elseif($CodTCSAP == 4 ){
            $codTCICG = 27;
        }
        //$facturasP = $_SESSION['facPorcesar'] ;
        $facturasP = $_POST['facturasProcesar'];
        $facturasP = json_decode($facturasP);
        //echo $_POST['facturasProcesar'];
        //recorremos cada factura
        $jsonResult['NCREDITOSVALOR'] = $valorNCred;
		$cCred = [];
		$cDepos = [];
		$cEfect = [];
		$cCheque = [];
		$cTC = [];
        foreach($facturasP as $factura){

            $saldo = $factura->Abono;
            
            //if($saldo  > 0 ){

                if($valorDepos > 0 || $valorNCred > 0 || $valorEfectivo > 0 || $valorCheque > 0 || $valorTC > 0){

                    if($saldo >= $valorDepos && $valorDepos > 0 && $saldo>0){
                        $respuesta =  pagarDepo($factura->DocEntry,$factura->TrackNum,$valorDepos);
                        $saldo = $saldo - $valorDepos;
                        //echo "Se pago : ".$valorDepos;
                        $valorDepos = 0 ;
                        //$jsonResult['Depositos'] = $respuesta;
						if(!empty($respuesta)){
							array_push($cDepos,$respuesta);				
						}
                        
                    }
                    
                    if($saldo < $valorDepos && $valorDepos > 0 && $saldo > 0){
                        $respuesta =   pagarDepo($factura->DocEntry,$factura->TrackNum,$saldo);
                        $valorDepos = $valorDepos - $saldo;
                        //echo "Se pago : ".$saldo;
                        $saldo = 0;
                        //$jsonResult['Depositos'] = $respuesta;
						if(!empty($respuesta)){
							array_push($cDepos,$respuesta);				
						}
						//break;
                    }
                    
                    if($saldo >= $valorNCred && $valorNCred > 0 && $saldo > 0){
    
                        $respuesta =  pagarNCred($factura->DocEntry,$factura->TrackNum,$valorNCred);
                        $saldo = $saldo - $valorNCred;
                        $valorNCred = 0;
						
                        if(!empty($respuesta)){
							array_push($cCred,$respuesta);		
						}
                    }
    
                    if($saldo < $valorNCred && $valorNCred > 0 && $saldo > 0){
    
                        $respuesta = pagarNCred($factura->DocEntry,$factura->TrackNum,$saldo);
                        $valorNCred = $valorNCred - $saldo;
                        
						if(!empty($respuesta)){

							array_push($cCred,$respuesta);
						}
						$saldo = 0;
                      
                    }
    
                    if($saldo >= $valorEfectivo && $valorEfectivo > 0 && $saldo > 0){
    
                        $respuesta =  PagarEfectivo($factura->DocEntry,$factura->TrackNum,$valorEfectivo);
                        $saldo = $saldo - $valorEfectivo;
                        $valorEfectivo = 0 ;
                        //$jsonResult['PEF'] = $respuesta;
						if(!empty($respuesta)){
							array_push($cEfect,$respuesta);
						}
                    }
    
                    if($saldo < $valorEfectivo && $valorEfectivo > 0 && $saldo > 0){
    
                        $respuesta = PagarEfectivo($factura->DocEntry,$factura->TrackNum,$saldo);
                        $valorEfectivo = $valorEfectivo - $saldo;
                        $saldo = 0;
                      
						if(!empty($respuesta)){
							array_push($cEfect,$respuesta);
						}
						
                    }

                    if($saldo < $valorCheque && $valorCheque > 0 && $saldo > 0){
    
                        $respuesta = PagarCheque($factura->DocEntry,$factura->TrackNum,$saldo,$numChequeP);
                        $valorCheque = $valorCheque - $saldo;
                        $saldo = 0;
						if(!empty($respuesta)){

							array_push($cCheque,$respuesta);							
						}

                    }

                    if($saldo >= $valorCheque && $valorCheque > 0 && $saldo > 0){
    
                        $respuesta =  PagarCheque($factura->DocEntry,$factura->TrackNum,$valorCheque,$numChequeP);
                        $saldo = $saldo - $valorCheque;
                        $valorCheque = 0 ;
                        if(!empty($respuesta)){

							array_push($cCheque,$respuesta);							
						}
                    }

                    if($saldo < $valorTC && $valorTC > 0 && $saldo > 0){
    
                        $respuesta = PagarTC($factura->DocEntry,$factura->TrackNum,$saldo,$VoucherTC,$codTCICG,$CodTCSAP);
                        $valorTC = $valorTC - $saldo;
                        $saldo = 0;

						if(!empty($respuesta)){
							array_push($cTC,$respuesta);
							
						}

                    }

                    if($saldo >= $valorTC && $valorTC > 0 && $saldo > 0){
    
                        $respuesta =  PagarTC($factura->DocEntry,$factura->TrackNum,$valorTC,$VoucherTC,$codTCICG,$CodTCSAP);
                        $saldo = $saldo - $valorTC;
                        $valorTC = 0 ;
                        if(!empty($respuesta)){
							array_push($cTC,$respuesta);
							
						}
                    }
                        
                } 
            //}           
   
        } 
		
		if(!empty($cCred)){
			$jsonResult['NCred'] = $cCred;
		}
		if(!empty($cTC)){
			$jsonResult['PTC'] = $cTC;
		}
		if(!empty($cCheque)){
			$jsonResult['PCH'] = $cCheque;
		}
		if(!empty($cEfect)){
			$jsonResult['PEF'] = $cEfect;
		}
		if(!empty($cDepos)){
			$jsonResult['Depositos'] = $cDepos;
		}

        echo json_encode($jsonResult);
    } 

    if($metodo == 'clear'){

        session_reset();
        $json['Limpio'] = true;
        echo json_encode($json);
        
    }

    //var_dump($_SESSION);
  

}else{

    echo "Hola Mundo";
}

function number_words($valor,$desc_moneda, $sep, $desc_decimal) {
    $arr = explode(".", $valor);
    $entero = $arr[0];
    if (isset($arr[1])) {
        $decimos = strlen($arr[1]) == 1 ? $arr[1] . '0' : $arr[1];
    }

    $fmt = new \NumberFormatter('es', \NumberFormatter::SPELLOUT);
    if (is_array($arr)) {
        $num_word = ($arr[0]>=1000000) ? "{$fmt->format($entero)} de $desc_moneda" : "{$fmt->format($entero)} $desc_moneda";
        if (isset($decimos) && $decimos > 0) {
            $num_word .= " $sep  {$fmt->format($decimos)} $desc_decimal";
        }
    }
    return $num_word;
}

function pagarDepo($factura,$trackNum,$valor){

    $depositosP = $_SESSION['depositos'];
    $contador = 0 ;
    $json = array();
    foreach($depositosP as $deposito){

        if($valor > 0){

            if($deposito->Saldo >= $valor && $deposito->Saldo > 0 ){
                $SAP = PagarDeposSap($factura,$deposito->DocEntry,$trackNum,$valor);
                if($SAP['responseCode'] == 201){
                    JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,$deposito->DocEntry,$SAP['response'][0]->docentry,4,$valor,"","");
                    $data['Factura']=$factura;
                    $data['FacturaTrack']=$trackNum;
                    $data['FPago']=$deposito->DocEntry;
                    $data['FPagoTexto']='DEPOSITOS';
                    $data['Abono']=$valor;
                    $valor = 0; 
					$_SESSION['depositos'][$contador]->Saldo = $deposito->Saldo-$valor;
                    array_push($json,$data);
                }else{
					JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",1,0,"","");
                    //array_push($json,$SAP);
					break;
				}
            }

            if($deposito->Saldo < $valor && $deposito->Saldo > 0 ){
                $SAP = PagarDeposSap($factura,$deposito->DocEntry,$trackNum,$deposito->Saldo);
                if($SAP['responseCode'] == 201){
                    JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,$deposito->DocEntry,$SAP['response'][0]->docentry,4,$deposito->Saldo,"","");
                    $valor = $valor-$deposito->Saldo ;
                    $data['Factura']=$factura;
                    $data['FacturaTrack']=$trackNum;
                    $data['FPago']=$deposito->DocEntry;
                    $data['FPagoTexto']='DEPOSITOS';
                    $data['Abono']=$deposito->Saldo;
					
					$_SESSION['depositos'][$contador]->Saldo = 0;
                    array_push($json,$data);
                }else{
					JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",1,1,"","");
                    //array_push($json,$SAP);
					break;
				}
            }

            $contador += 1; 
        }else{
            break;
        }

    }

    return $json;


}

function pagarNCred($factura,$trackNum,$valor){

    $depositosP = $_SESSION['NotasCredito'];
    $contador = 0 ;
    $json = array();
    foreach($depositosP as $deposito){

            if($deposito->Saldo >= $valor && $deposito->Saldo > 0 && $valor > 0){
                $SAP = PagarNCredSap($factura,$deposito->DocEntry,$trackNum,$valor);
                if($SAP['responseCode'] == 201){
					
                    JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,$deposito->DocEntry,$SAP['response'][0]->docentry,6,$valor,"","");
                    
					$_SESSION['NotasCredito'][$contador]->Saldo = $deposito->Saldo - $valor;
                    $data['Factura']=$factura;
                    $data['FacturaTrack']=$trackNum;
                    $data['FPago']=$deposito->DocEntry;
                    $data['FPagoTexto']='NOTA DE CREDITO';
                    $data['Abono'] = $valor;

                    $valor = 0; 
					
                    array_push($json,$data);
					break;
                }else{
					JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",6,0,"","");
                    //array_push($json,$SAP);
					break;
				}
            }

            if($deposito->Saldo < $valor && $deposito->Saldo > 0 && $valor > 0){

                $SAP = PagarNCredSap($factura,$deposito->DocEntry,$trackNum,$deposito->Saldo);
                if($SAP['responseCode'] == 201){
                    JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,$deposito->DocEntry,$SAP['response'][0]->docentry,6,$deposito->Saldo,"","");
					$valor = $valor - $deposito->Saldo ;
                    $data['Factura']= $factura;
                    $data['FacturaTrack']= $trackNum;
                    $data['FPago']=$deposito->DocEntry;
                    $data['FPagoTexto']='NOTA DE CREDITO';
                    $data['Abono'] = $deposito->Saldo;
					$_SESSION['NotasCredito'][$contador]->Saldo = 0 ;
                    array_push($json,$data);
                }else{
					
					JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",6,0,"",""); 
					//array_push($json,$SAP);
				}
            }

            $contador += 1; 

    }

    return $json;


}

function PagarEfectivo($factura,$trackNum,$valor){

    $json = array();

    $SAP = PagarEfectivoSap($factura,$trackNum,$valor);

    if($SAP['responseCode'] == 201){
        JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,0,$SAP['response'][0]->docentry,1,$valor,"","");
        
        $data['Factura']=$factura;
        $data['FacturaTrack']=$trackNum;
        $data['FPago']=$SAP['response'][0]->docentry;
        $data['FPagoTexto']='EFECTIVO';
        $data['Abono']=$valor;
        array_push($json,$data);
    }else{
		JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",1,0,"","");
		//array_push($json,$SAP);
	}
    return $json;


}

function PagarCheque($factura,$trackNum,$valor,$numeroCheque){

    $json = array();

    $SAP = PagarChequeSap($factura,$trackNum,$valor,$numeroCheque);

    if($SAP['responseCode'] == 201){
        JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,0,$SAP['response'][0]->docentry,2,$valor,"",$numeroCheque);
        
        $data['Factura']=$factura;
        $data['FacturaTrack']=$trackNum;
        $data['FPago']=$SAP['response'][0]->docentry;
        $data['FPagoTexto']='CHEQUE';
        $data['Abono']=$valor;
        array_push($json,$data);
    }else{
		JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",1,1,"","");
		//array_push($json,$SAP);
	}
    return $json;


}

function PagarTC($factura,$trackNum,$valor,$CofV,$CodTCJ ,$CodTC){

    $json = array();

    $SAP = PagarTCSap($factura,$trackNum,$valor,$CofV,$CodTC);

    if($SAP['responseCode'] == 201){
        JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,0,$SAP['response'][0]->docentry,$CodTCJ,$valor,$CofV,"");
        
        $data['Factura']=$factura;
        $data['FacturaTrack']=$trackNum;
        $data['FPago']=$SAP['response'][0]->docentry;
        $data['FPagoTexto']='TARJETA';
        $data['Abono']=$valor;
        array_push($json,$data);
    }else{
		JoinPagos(json_encode($SAP['send']),$SAP['responseCode'],$SAP['responseCode'],json_encode($SAP['response']),$factura,"11","11",1,0,"","");
		//array_push($json,$SAP);
	}
    return $json;


}

function PagarDeposSap($factura,$deposito,$trackNum,$valor){

    $today = date("Y-m-d");  
	
	GetNumDocumentoPreview();
    $trackNum = $_SESSION['comprobanteICG'];
	
    $data['DocEntryFC'] = $factura;
    $data['DocEntryPR'] = $deposito;
    $data['Abono'] = 1;
    $data['CajaICG'] = $trackNum;
    $data['DocDate'] = $today;
    $data['Monto'] = floatval($valor);

    $enviar['Reconciliacion']= [];
    array_push($enviar['Reconciliacion'],$data);

    // API URL to send data
    $url = 'http://10.238.26.72:7083/api/reconciliacion';
    // curl initiate
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER , false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // SET Method as a POST
    curl_setopt($ch, CURLOPT_POST, 1);
    // Pass user data in POST command
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($enviar));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute curl and assign returned data
    $response  = curl_exec($ch);
   

    $json['response'] = json_decode($response);
    $json['send'] = $enviar;
    $json['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $json['responseCode'] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );

    curl_close($ch);

    return $json;
}

function PagarNCredSap($factura,$deposito,$trackNum,$valor){

    $today = date("Y.m.d");
	$today2 = date("YmdHis-v");
	
	GetNumDocumentoPreview();
    $trackNum = $_SESSION['comprobanteICG'];
	
    $data['fechaDocumento'] = $today;
    $data['Comentarios'] = 'ICG';
    $data['Abono'] = 1;
    $data['Total'] = floatval($valor);
    $data['CajaICG'] = $trackNum;
    $data['DocEntryFC'] = $factura;
    $data['DocEntryNC'] = $deposito;
    $data['PagoICG'] = [];
    $pagoIcg['ID'] = $today2;
    array_push($data['PagoICG'],$pagoIcg);

    $enviar['Encabezado']= [];
    array_push($enviar['Encabezado'],$data);

    // API URL to send data
    $url = 'http://10.238.26.72:7083/api/NCpago';
    // curl initiate
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER , false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // SET Method as a POST
    curl_setopt($ch, CURLOPT_POST, 1);
    // Pass user data in POST command
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($enviar));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute curl and assign returned data
    $response  = curl_exec($ch);
   

    $json['response'] = json_decode($response);
    $json['send'] = $enviar;
    $json['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $json['responseCode'] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );

    curl_close($ch);
    //echo json_encode($json);
    return $json;
}

function PagarEfectivoSap($factura,$trackNum,$valor){

    $today = date("Y-m-d");

	GetNumDocumentoPreview();
    $trackNum = $_SESSION['comprobanteICG'];
	
    $data['DocDate'] = $today;
    $data['CardCode'] = $_SESSION['CardCodeCl'];
    $data['Abono'] = 1;
    $data['Currency'] = 'QTZ';
    $data['DocEntry'] = $factura;
    $data['CajaICG'] = $trackNum;
    $data['contado'] = [];
    $pagoIcg['Monto'] =  $valor;
    array_push($data['contado'],$pagoIcg);

    $enviar['Encabezado']= [];
    array_push($enviar['Encabezado'],$data);

    // API URL to send data
    $url = 'http://10.238.26.72:8083/api/Pagos';
    // curl initiate
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER , false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // SET Method as a POST
    curl_setopt($ch, CURLOPT_POST, 1);
    // Pass user data in POST command
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute curl and assign returned data
    $response  = curl_exec($ch);
   

    $json['response'] = json_decode($response);
    $json['send'] = $data;
    $json['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $json['responseCode'] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );

    curl_close($ch);

    return $json;
    //echo json_encode($json);
}

function PagarChequeSap($factura,$trackNum,$valor,$numeroCheque){

    $today = date("Y-m-d");
    $today2 = date("Y.m.d");

	GetNumDocumentoPreview();
    $trackNum = $_SESSION['comprobanteICG'];
	
    $data['DocDate'] = $today;
    $data['CardCode'] = $_SESSION['CardCodeCl'];
    $data['Abono'] = 1;
    $data['Currency'] = 'QTZ';
    $data['DocEntry'] = $factura;
    $data['CajaICG'] = $trackNum;
    $data['cheque'] = [];
    $pagoIcg['CodigoBanco'] =  "6";
    $pagoIcg['NumeroCheque'] =  $numeroCheque;
    $pagoIcg['CuentaCheque'] =  '_SYS1111000000';
    $pagoIcg['FechaCheque'] =  $today2;
    $pagoIcg['MontoCheque'] =  $valor;
    array_push($data['cheque'],$pagoIcg);

    $enviar['Encabezado']= [];
    array_push($enviar['Encabezado'],$data);

    // API URL to send data
    $url = 'http://10.238.26.72:8083/api/Pagos';
    // curl initiate
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER , false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // SET Method as a POST
    curl_setopt($ch, CURLOPT_POST, 1);
    // Pass user data in POST command
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute curl and assign returned data
    $response  = curl_exec($ch);
   

    $json['response'] = json_decode($response);
    $json['send'] = $data;
    $json['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $json['responseCode'] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );

    curl_close($ch);

    return $json;
    //echo json_encode($json);
}

function PagarTCSap($factura,$trackNum,$valor,$voucher,$codTarjeta){

    $today = date("Y-m-d");
    $today2 = date("Y.m.d");

	GetNumDocumentoPreview();
    $trackNum = $_SESSION['comprobanteICG'];
	
    $data['DocDate'] = $today;
    $data['CardCode'] = $_SESSION['CardCodeCl'];
    $data['Abono'] = 1;
    $data['Currency'] = 'QTZ';
    $data['DocEntry'] = $factura;
    $data['CajaICG'] = $trackNum;
    $data['credito'] = [];
    $pagoIcg['NumeroDeTarjeta'] =  "1234";
    $pagoIcg['MontoTarjeta'] =  $valor;
    $pagoIcg['FechaVencimiento'] = $today2;
    $pagoIcg['Voucher'] =  $voucher;
    $pagoIcg['CodigoSAPTarjeta'] =  $codTarjeta;
    array_push($data['credito'],$pagoIcg);

    $enviar['Encabezado']= [];
    array_push($enviar['Encabezado'],$data);

    // API URL to send data
    $url = 'http://10.238.26.72:8083/api/Pagos';
    // curl initiate
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER , false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    // SET Method as a POST
    curl_setopt($ch, CURLOPT_POST, 1);
    // Pass user data in POST command
    curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Execute curl and assign returned data
    $response  = curl_exec($ch);
   

    $json['response'] = json_decode($response);
    $json['send'] = $data;
    $json['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $json['responseCode'] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE );

    curl_close($ch);

    return $json;
    //echo json_encode($json);
}

function JoinPagos($enviar, $statusWs, $STATUSTEXT_WS, $RESPONSETEXT, $DOCENTRYFV, $DOCENTRYFP, $DOCENTRYABONO, $CODTIPOPAGO, $MONTO,$VOUCHER, $NUMEROCHEQUE ){

    $serverName = "10.238.26.69";
    $connectionInfo = array( "Database"=>"AGORA_2020", "UID"=>"SA", "PWD"=>"masterkey", "CharacterSet" => "UTF-8");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    $CAJA = $_SESSION['CodCajero'];
    $SERIE = $_SESSION['SerieFront'];
    $IDTRANSATION = $_SESSION['IdSession'];
    $CODCLIENTE = $_SESSION['CardCodeCl'];

    $MONTO = floatval($MONTO);
    if( $conn === false) {
        die( print_r( sqlsrv_errors(), true));
        return false;
    }
    
    $sql = " EXECUTE JOIN_ABONOS_INSERT '".$enviar."', ".$statusWs.",'".$STATUSTEXT_WS."','".$RESPONSETEXT."', ".$CAJA.", '".$SERIE."', '".$IDTRANSATION."', ".$CODCLIENTE.", ".$DOCENTRYFV.", ".$DOCENTRYFP.", ".$DOCENTRYABONO.", ".$CODTIPOPAGO.",".$MONTO.",'".$VOUCHER."','".$NUMEROCHEQUE."'";
    
    // Initialize parameters and prepare the statement. 
    // Variables $qty and $id are bound to the statement, $stmt.
    $id = 0;
    $stmt = sqlsrv_prepare($conn, $sql, array());
    //$stmt = sqlsrv_prepare($conn, $sql, array( &$enviar, &$statusWs , &$STATUSTEXT_WS, &$RESPONSETEXT , &$CAJA, &$SERIE, &$IDTRANSATION, &$CODCLIENTE, &$DOCENTRYFV, &$DOCENTRYFP, &$DOCENTRYABONO, &$CODTIPOPAGO, &$MONTO));
    //echo $sql;
    if( sqlsrv_execute( $stmt ) === false ) {
		echo $sql;
        die( print_r( sqlsrv_errors(), true));
        return false; 
    }

    return true;
}

function GetNumDocumentoPreview(){
    $serverName = "10.238.26.69";
    $connectionInfo = array( "Database"=>"AGORA_2020", "UID"=>"SA", "PWD"=>"masterkey", "CharacterSet" => "UTF-8");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( $conn === false) {
        die( print_r( sqlsrv_errors(), true));
        return false;
    }

    $SERIE = $_SESSION['SerieFront'];
    $IDTRANSATION = $_SESSION['IdSession'];

    $sql = "EXECUTE JOIN_ABONOS_RECIBO_SAP '".$SERIE."','".$IDTRANSATION."'";
    $idDocumentoIcg = 0;
    $stmt = sqlsrv_prepare( $conn, $sql, array());

    if( sqlsrv_execute( $stmt ) === false ) {
        die( print_r( sqlsrv_errors(), true));
        return false; 
    }

    while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {

        //array_push($json,$row);
        $_SESSION['comprobanteICG'] = $row['CAJAICG'];
        //echo json_encode($row);
    }

    //echo ("EXECUTE JOIN_ABONOS_RECIBO_SAP '".$SERIE."','".$IDTRANSATION);
    
}

function GetNumDocumentoICG($idTransaccion){

    $serverName = "serverName\sqlexpress";
    $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( $conn === false) {
        die( print_r( sqlsrv_errors(), true));
        return false;
    }
    
    $sql = " EXECUTE JOIN_ABONOS_INSERT '?', ?,'?','?', ?, '?', '?', ?, ?, ?, ?, ?, ?";
    
    // Initialize parameters and prepare the statement. 
    // Variables $qty and $id are bound to the statement, $stmt.
    $id = 0;
    $stmt = sqlsrv_prepare( $conn, $sql, array( &$enviar, &$statusWs , &$STATUSTEXT_WS, &$RESPONSETEXT , &$CAJA, &$SERIE, &$IDTRANSATION, &$CODCLIENTE, &$DOCENTRYFV, &$DOCENTRYFP, &$DOCENTRYABONO, &$CODTIPOPAGO, &$MONTO));

    if( sqlsrv_execute( $stmt ) === false ) {
        die( print_r( sqlsrv_errors(), true));
        return false; 
    }

    $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);

    return $row;
}