<?php
include_once('../../../php/sessionStart.php');
include_once('../../../php/db/dbExec.php');
include_once('../../../php/functions.php');
include_once('../../../php/timezone.php');
include_once('../../../php/privileges.php');
include_once('../../../php/maxExecTime.php');
include_once('../ws/COFIDI/wsExec.php');
include_once('../ws/COFIDI/wsFormatsXML.php');

$bitForm = "fel1010";
$bitMod = "fel";
$empCod = $_SESSION['empCod'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);
$tipoPol='010';

echo anular();

function anular() {
	global $empCod, $usuNom, $bitMod, $bitForm, $tipoPol;

	$priv = new privileges();
	if (!$priv->modify($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorModify());
	}

	$func = new functions();
/*
	$IDInternoIni = 2220;
	$IDInternoFin = 2229;*/

	/*$IDInternoIni = 6202;
	$IDInternoFin = 6265;*/
	$IDInternoIni = 6266;
	$IDInternoFin = 6317;
	//6202-6317
	$arrayError = array();

	# QUERYS PARA UN REGISTRO
	$sFacturas = "SELECT * FROM facturas WHERE fact_idinterno>='$IDInternoIni' AND fact_idinterno<='$IDInternoFin'";

	function uFacturas($serie, $num, $anu, $motAnu, $FechaHoraAnulacion){
		global $empCod;
		return "UPDATE facturas SET fact_nom='$anu',fact_dir='$anu',fact_tot=0,fact_pcomi=0,fact_motanu='$motAnu', fact_fechoranu='$FechaHoraAnulacion' WHERE fact_emp='$empCod' AND fact_tipo='$serie' AND fact_num='$num'";
	}

	function uFact_det($serie, $num, $anu){
		global $empCod;
		return "UPDATE fact_det SET factd_cant=0,factd_preu=0,factd_cosu=0,factd_sub=0,factd_descu=0,factd_descuv=0,factd_tot=0 WHERE factd_emp='$empCod' AND factd_tipo='$serie' AND factd_num='$num'";
	}

	function uDoctoscc($serie, $num, $anu){
		global $empCod;
		return "UPDATE doctoscc SET dc_clien='$anu',dc_bien=0,dc_serv=0,dc_peque=0,dc_exp=0,dc_tot=0,dc_sub=0,dc_subb=0,dc_subs=0,dc_iva=0,dc_sube=0,dc_retsn='N',dc_retisn='N',dc_abo=0,dc_sal=0,dc_abot=0 WHERE dc_emp='$empCod' AND dc_tipo='$serie' AND dc_num='$num'";
	}

	function uIva_ven($serie, $num, $anu){
		global $empCod;
		return "UPDATE iva_ven SET ivav_clin='$anu',ivav_bien=0,ivav_serv=0,ivav_exp=0,ivav_tot=0,ivav_sub=0,ivav_subb=0,ivav_subs=0,ivav_iva=0,ivav_sube=0,ivav_retsn='N',ivav_retisn='N',ivav_ret=0,ivav_reti=0,ivav_exen=0 WHERE ivav_emp='$empCod' AND ivav_tipo='$serie' AND ivav_num='$num'";
	}

	function dPolizas($serie, $num, $anu){
		global $empCod, $tipoPol;
		return "DELETE FROM polizas WHERE pol_emp='$empCod' AND pol_tipo='$tipoPol' AND pol_tipoi='$serie' AND pol_num='$num'";
	}

	function dPoli_det($serie, $num, $anu){
		global $empCod, $tipoPol;
		return "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_tipo='$tipoPol' AND pold_tipoi='$serie' AND pold_num='$num'";
	}

	# EJECUCION DE QUERYS
	$db = new dbExec();

	$arrayFac = $db->sFetchAll($sFacturas);

	$i=1;
	$anu = "*** ANULADO ***";
	foreach ($arrayFac as $rec) {
		$serie = $rec['fact_tipo'];
		$num = $rec['fact_num'];
		$motAnu = utf8_decode('PORQUE SE GENERÓ CON ERROR');//utf8_decode($_POST['motAnu']);
		$DocumentGUID = $rec['fact_documentguid'];
		$nit = $rec['fact_nit'];

		echo "$i --> $serie - $num - $DocumentGUID - $nit<br>";
		$i++;

		$FechaHoraAnulacion = date('Y-m-d\TH:i:s', STRTOTIME(date('h:i:sa')));

		$wsCOFIDI = new wsCOFIDIExec();
		foreach ($wsCOFIDI->sExDocumentGUID($DocumentGUID) as $Body) {
			// Si existe la factura en la SAT (Result = TRUE o FALSE) entonces anularla en la SAT
			$result = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Result;
		    $IssuedTimeStamp = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Identifier->IssuedTimeStamp;

			$wsFormatsXML = new wsFormatsXML();

			// Datos Anulación
			$arrayDatosAnulacion = array(
				array('NumeroDocumentoAAnular'=>$DocumentGUID, 'IDReceptor'=>$nit, 'FechaEmisionDocumentoAnular'=>$IssuedTimeStamp, 'FechaHoraAnulacion'=>$FechaHoraAnulacion, 'MotivoAnulacion'=>$motAnu)
			);

			$FEL = $wsFormatsXML->GTAnulacionDocumento($arrayDatosAnulacion);
			$base64FEL = base64_encode($FEL);
			//echo $FEL." ------ base64 ---- ".$base64FEL;

		    if ($func->stringToBool((string)$result)) {
				foreach ($wsCOFIDI->uExAnulacion($base64FEL) as $Body) {
					// Si se anuló la factura en la SAT (Result = TRUE o FALSE) entonces anular en nuestra DB
					$result = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Result;
					if ($func->stringToBool((string)$result)) {
						$resp = $db->anEx(uFacturas($serie, $num, $anu, $motAnu, $FechaHoraAnulacion));
						$db->anEx(uFact_det($serie, $num, $anu));
						$db->anEx(uIva_ven($serie, $num, $anu));
						$db->anEx(uDoctoscc($serie, $num, $anu));
						$db->dEx(dPolizas($serie, $num, $anu));
						$db->dEx(dPoli_det($serie, $num, $anu));
					} else {
						$Code = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Code;
						$Description = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Description;
						array_push($arrayError, array("Code"=>''.$Code, "Description"=>''.$Description));
					}
				}
			} else {
				$Code = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Code;
				$Description = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Description;
				array_push($arrayError, array("Code"=>''.$Code, "Description"=>''.$Description));
			}
		}
	}

	var_dump($arrayError);
	// Por si no se pudo anular la factura
	/*$sizeError = sizeof($arrayError);
	if ($sizeError != 0) {
		$title = $arrayError[0]["Code"];
		$text = $arrayError[0]["Description"];
		$resp = $db->rErrorPublic($title, $text);
	}

	$db->close();

	return json_encode($resp);*/
}
?>