<?php require "php/cabecera3.inc";
	
	function msg($val){echo "<SCRIPT>alert('$val')</SCRIPT>";}	

	echo "<center><h6 STYLE='FONT-SIZE:18PX; color: ".$st['C-TEXTO2'].";'>Redireccionando</h6></center>";
	echo "<br><br><center><a href='index.php?IDS=".$_POST['IDS']."'><button class='btn'>Regresar</button><a></center><br><br>";
	$conexion = mysqli_connect($serv,$dbu,$dbp,$db);
	mysqli_set_charset($conexion, "utf8");
	$MSG="";
	$VAL=true;
	for($i = 0;$i< $_SESSION['contador'];$i++){
		$peticion = "SELECT tabla_altaproducto. * , (SELECT SUM( tabla_inventario.CANTIDAD ) FROM tabla_inventario WHERE tabla_altaproducto.SKU = tabla_inventario.SKU AND tabla_inventario.CVE_CUENTA = tabla_altaproducto.CUENTA AND tabla_inventario.EDO_CALIDAD =  'D' AND STR_TO_DATE( tabla_inventario.CADUCIDAD,  '%Y/%m/%d' ) > CURDATE( ) ) AS EXISTENCIAS FROM tabla_altaproducto WHERE CUENTA=".$_POST['IDS']." AND SKU='".$_SESSION['producto'][$i]."'";
		$resultado = mysqli_query($conexion, $peticion);
		if($resultado){
			$fila = mysqli_fetch_array($resultado);
			if($_SESSION['numb'][$i]>$fila['EXISTENCIAS']){
				$MSG+= "La cantidad seleccionada del producto: ".$fila['DESCRIPCION'].". Ya no se encuentra disponible.";
				$VAL=false;
				unset($_SESSION['producto'][$i]);
				$temp = array_values($_SESSION['producto']);
				$_SESSION['producto'] = $temp;
				unset($_SESSION['numb'][$i]);
				$temp = array_values($_SESSION['numb']);
				$_SESSION['numb'] = $temp;
				$_SESSION['contador']-=1;
			}
			}else{
			echo "<script type='text/javascript'>alert('Error al conectar a la base de datos,por favor reintentelo.');</script>";
		echo "<META HTTP-EQUIV=Refresh CONTENT='0; URL=myc.php?IDS=".$_POST['IDS']."'>";}
	}
	
	if(!$VAL){
		echo "<script type='text/javascript'>alert('$MSG');</script>";
	echo "<META HTTP-EQUIV=Refresh CONTENT='0; URL=myc.php?IDS=".$_POST['IDS']."'>";}
	else{
		require "paypal.inc";
		
		for($i = 0;$i< $_SESSION['contador'];$i++){
			$ta += $_SESSION['numb'][$i];
			$peticion = "SELECT * FROM tabla_altaproducto WHERE CUENTA='".$_POST['IDS']."' AND SKU='".$_SESSION['producto'][$i]."'";
			$resultado = mysqli_query($conexion, $peticion);
			while($fila = mysqli_fetch_array($resultado)) {
				$total = $fila['COSTOECOM']*$_SESSION['numb'][$i];
				$suma += $total;
			}}
			
			$rd = mysqli_query($conexion, "SELECT * FROM ecomm_cuenta WHERE CVE_CUENTA='$_POST[IDS]'");
			$pay = mysqli_fetch_array($rd);
			
			
			//ENVÍO
			$return= 'col='.urlencode($_POST['col']).'&cal='.urlencode($_POST['cal']).'&nex='.urlencode($_POST['nex']).'&cp='.urlencode($_POST['cp']).'&ref='.urlencode($_POST['ref']).'&mun='.urlencode($_POST['mun']).'&est='.urlencode($_POST['est']).'&nom='.urlencode($_POST['nom']).'&tel='.urlencode($_POST['tel']).'&ema='.urlencode($_POST['ema']).'&pais='.urlencode($_POST['pais']);
			
			# Sandbox
			if ($pay['TIPO']==0){$host = 'https://api.sandbox.paypal.com';}else{$host = 'https://api.paypal.com';}
			$clientId = $pay['CLIENTID'];
			$clientSecret = $pay['SECRET'];
			$token = '';
			$url = $host.'/v1/oauth2/token';
			$postArgs = 'grant_type=client_credentials';
			$token = get_access_token($url,$postArgs);
			$url = $host.'/v1/payments/payment';
			$payment = array('intent' => 'sale',
			'payer' => array('payment_method' => 'paypal'),
			'transactions' => array (array('amount' => array('total' => $suma,'currency' => 'MXN'),'description' => $st['EMPRESA'].' '.$ta.' Articulo(s) ($'.$suma.')')),
			'redirect_urls' => array (
			
			'return_url' => 'http://localhost/WMS/WMS/ECOMM2/load.php?IDS='.$_POST['IDS'].'&sk='.$token.'&'.$return,
			'cancel_url' => 'http://localhost/WMS/WMS/ECOMM2/index.php?IDS='.$_POST['IDS']));
			
			//'return_url' => 'http://192.168.1.80/WMS/WMS/ECOMM2/load.php?IDS='.$_POST['IDS'].'&sk='.$token.'&'.$return,
			//'cancel_url' => 'http://192.168.1.80/WMS/WMS/ECOMM2/index.php?IDS='.$_POST['IDS']));
			
			
			//urlip
			//$externalContent = file_get_contents('http://ipecho.net/plain');
			//'return_url' => 'http://$externalContent:$_SERVER[SERVER_PORT]/WMS/WMS/ECOMM2/ok.php?IDS='.$_POST['IDS'].'&sk='.$token.'&'.$return,
			//'cancel_url' => 'http://$externalContent:$_SERVER[SERVER_PORT]/WMS/WMS/ECOMM2/index.php?IDS='.$_POST['IDS']));
			
			if($token == NULL){echo "<Script>alert('No es posible establecer conexión con el servidor PayPal, por favor inténtelo de nuevo más tarde.')</Script>";}else{
			$json = json_encode($payment);
			$json_resp = make_post_call($url, $json);
			foreach ($json_resp['links'] as $link) {
				if($link['rel'] == 'execute'){
					$payment_execute_url = $link['href'];
					$payment_execute_method = $link['method'];
					} else 	if($link['rel'] == 'approval_url'){
					$payment_approval_url = $link['href'];
					$payment_approval_method = $link['method'];
				}
			}
	}
			echo "<META HTTP-EQUIV=Refresh CONTENT='0; URL=".$payment_approval_url."'>";
			exit();
	}
	mysqli_close($conexion);
	
require "php/pie.inc" ?>