<?php
 
session_start();

$makeConn1 = true;
$makeConn2 = true;

include_once "../dbconectionbdlab.php";
include_once "../errorhandler.php";
include_once "../funciones.php";

class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

    public function __call($method, $arguments) {
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

function getLiberados($intCase, $strFechaArg, $strConvenioArg){
	global $conn;
	
	//$query = "SELECT t1.FAC_FEC, count(t2.EST_EST) as intLiberados FROM exax2000 t1  INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM)  INNER JOIN anav5000 t3 ON (t1.FAC_CRE=t3.CON_CVE)  WHERE 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0 AND t2.EST_EST LIKE '%covid%' AND t2.EST_STA=85 ";

	$query = "SELECT t2.FEC_INT, count(t2.EST_EST) as intLiberados 
	FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) 
	INNER JOIN anav5000 t3 ON (t1.FAC_CRE=t3.CON_CVE)  
	WHERE 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0 AND t2.EST_STA=85 AND t2.EST_EST IN ('covid','covic','covfl') ";  //t2.EST_EST LIKE '%covid%'

	//$query .= " AND t2.EST_ENV='". $strFechaArg ."'";
	//$query .= " AND t1.FAC_FEC='". $strFechaArg ."'";
	$query .= " AND t2.FEC_INT='". $strFechaArg ."'";
	
	
	if($intCase==2){
		$query .= " AND t1.FAC_CRE='". $strConvenioArg ."'";
	}

	//$query .= " GROUP BY t1.FAC_FEC ORDER BY t1.FAC_FEC ASC";
	$query .= " GROUP BY t2.FEC_INT ORDER BY t2.FEC_INT ASC";
	
	//$query .= " AND ( (t2.EST_ENV > CONVERT(datetime, '". $strFec1 ." 00:00:00.000') AND t2.EST_ENV < CONVERT(datetime, '". $strFec2 ." 23:59:00.000')) OR (t2.FEC_INT>='". $strFec3 ."' AND t2.FEC_INT<='". $strFec4 ."') ) ";
	//exit("getLiberados / query: ". $query);

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$intLiberados = 0;

   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
 
		$intLiberados = $row['intLiberados'];			

	}

	sqlsrv_free_stmt( $getResults );

	return $intLiberados;

}

function getArrFechas($strMethodArg, $strFechasArg){
	
	$strWhereFechas = "";
	$strWhereFechas0 = "";

	if( $strMethodArg == "getVentas" ){
		$strCampo = "t1.FAC_FEC";
	}elseif($strMethodArg == "getProduccion" ){
		$strCampo = "t2.FEC_INT";
	}elseif($strMethodArg == "getEstudiosProduccion" ){
		$strCampo = "t2.FEC_INT";
	}elseif($strMethodArg == "getCotizaciones" ){
		$strCampo = "t1.datFechaAlta";
	}

	$arrFechas = explode(" - ", $strFechasArg);
	$strFec1 = $arrFechas[0];

	if(count($arrFechas)>1){ //PERIODO DE 2 FECHAS

		//   26/02/2020 - 04/03/2020
		$strFec1 = str_replace("/", "-", $arrFechas[0]);
		$strFec2 = str_replace("/", "-", $arrFechas[1]);
		
		$arrFec1 = explode("/", $arrFechas[0]);
		$strFec3 = $arrFec1[2]. $arrFec1[1] .$arrFec1[0];  //20201006  YYYYMMDD

		$arrFec2 = explode("/", $arrFechas[1]);
		$strFec4 = $arrFec2[2]. $arrFec2[1] .$arrFec2[0];
		
		$strWhereFechas = " ". $strCampo .">='". $strFec3 ."' AND ". $strCampo ."<='". $strFec4 ."' ";

		$dateTime1anioAtras = date_create($strFec3); //YYYYMMDD
	    $datFecha1anioAtras = date_sub($dateTime1anioAtras, date_interval_create_from_date_string('1 year'));
		$strFecha1anioAtras = date_format($datFecha1anioAtras, 'Ymd');

		$dateTime2anioAtras = date_create($strFec4); //YYYYMMDD
	    $datFecha2anioAtras = date_sub($dateTime2anioAtras, date_interval_create_from_date_string('1 year'));
		$strFecha2anioAtras = date_format($datFecha2anioAtras, 'Ymd');

		$strWhereFechas0 = " ". $strCampo .">='". $strFecha1anioAtras ."' AND ". $strCampo ."<='". $strFecha2anioAtras ."' ";
		//exit("strWhereFechas: ". $strWhereFechas);

	}else{ //1 FECHA

		$strFec1 = str_replace("/", "-", $arrFechas[0]);

		$arrFec1 = explode("/", $arrFechas[0]);
		$strFec1FormatoAnt = $arrFec1[2].$arrFec1[1].$arrFec1[0];
		
		$dateTime1anioAtras = date_create($strFec1FormatoAnt);
	    $datFecha1anioAtras = date_sub($dateTime1anioAtras, date_interval_create_from_date_string('1 year'));
		$strFecha1anioAtras = date_format($datFecha1anioAtras, 'Ymd');

		$strWhereFechas = " ". $strCampo ."='". $strFec1FormatoAnt ."' ";			
		$strWhereFechas0 = " ". $strCampo ."='". $strFecha1anioAtras ."' ";

	}

	return [$strWhereFechas, $strWhereFechas0];
	
}

/*----------------------------------------------------------------------------*/

//header('Content-type: text/html; charset=utf-8');
//header('Content-Type: text/html; charset=iso-8859-1');
//header('Content-Type: text/plain; charset=iso-8859-1');

header('Content-Type: text/plain; charset=UTF-8');

$method = $_REQUEST['method'];


/*______________________________________________________________________________*/


$sJSON = '{"Items":[';

if( $method == "getCovid" ){ 
	
	/*

	$intEmpresa = $_REQUEST["intEmpresa"];

	////////////////   1ERA PARTE    /////////////////

	$query = "SELECT t2.FEC_INT, count(t2.EST_EST) as intEstudios 
	FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) 
	INNER JOIN anav5000 t3 ON (t1.FAC_CRE=t3.CON_CVE)  
	WHERE 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0 AND t2.EST_EST IN ('covid','covic','covfl','covar') ";  //t2.EST_EST LIKE '%covid%'

	//***************** ARREGLAR SEGUN FEC_INT
	if(isset($_REQUEST['strFechas'])){

		$strFechas = $_REQUEST['strFechas'];
		//$strFechas = decode($strFechas);
		$strFechas = $strFechas;

		$arrFechas = explode(" - ", $strFechas);
		$strFec1 = $arrFechas[0];

		if(count($arrFechas)>1){

			$strFec2 = $arrFechas[1];

			//      26/02/2020 - 04/03/2020
			$strFec1 = str_replace("/", "-", $arrFechas[0]);
			$strFec2 = str_replace("/", "-", $arrFechas[1]);
			
			$arrFec1 = explode("/", $arrFechas[0]);
			$strFec3 = $arrFec1[2].$arrFec1[1].$arrFec1[0];

			$arrFec2 = explode("/", $arrFechas[1]);
			$strFec4 = $arrFec2[2].$arrFec2[1].$arrFec2[0];
			
			$query .= " AND ( (t2.EST_ENV > CONVERT(datetime, '". $strFec1 ." 00:00:00.000') AND t2.EST_ENV < CONVERT(datetime, '". $strFec2 ." 23:59:00.000')) OR (t2.FEC_INT>='". $strFec3 ."' AND t2.FEC_INT<='". $strFec4 ."') ) ";

		}else{
			$strFec1 = str_replace("/", "-", $arrFechas[0]);

			$arrFec1 = explode("/", $arrFechas[0]);
			$strFec1FormatoAnt = $arrFec1[2].$arrFec1[1].$arrFec1[0];

			$query .= " AND ( (t2.EST_ENV > CONVERT(datetime, '". $strFec1 ." 00:00:00.000') AND t2.EST_ENV < CONVERT(datetime, '". $strFec1 ." 23:59:00.000')) OR (t2.FEC_INT='". $strFec1FormatoAnt ."') ) ";

		}

	}

	//$query .= " AND t2.FEC_INT>='20200701'";

  	$dateTimeNow0 = date_create("now");
	$strFechaHoy = date_format($dateTimeNow0, 'Y-m-d');
	$dateTimeNow = date_create($strFechaHoy);
    $datFecha60DiasAtras = date_sub($dateTimeNow, date_interval_create_from_date_string('60 days'));
    $strFecha60DiasAtras = date_format($datFecha60DiasAtras, 'Ymd');

	$query .= " AND t2.FEC_INT>='". $strFecha60DiasAtras ."'";

	$query .= " GROUP BY t2.FEC_INT ORDER BY convert(datetime, t2.FEC_INT, 103) DESC";
 
	//exit("sql: ". $query);
	
	$getResults= sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$i=0;

	$strClaveEmpresa = "000";
	$strEmpresa = "Totales";

	$sJSON .= "{";
		$sJSON .= '"strClaveEmpresa":"'. $strClaveEmpresa .'"';
		$sJSON .= ',"strEmpresa":"'. $strEmpresa .'"';

		$sJSON .= ',"arrFechas":[';

		while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
	 
			$strFecha = $row['FEC_INT'];
			$intEstudios = $row['intEstudios'];	
	
			//$intLiberados = rand(1,$intEstudios);
			$intLiberados = getLiberados(1, $strFecha, '');
			usleep(10);
	
			$intEnproceso = $intEstudios - $intLiberados;
	
			$sJSON .= "{";
				$sJSON .= '"strFecha":"'. $strFecha .'"';
				$sJSON .= ',"intEstudios":'. $intEstudios .'';
				$sJSON .= ',"intLiberados":'. $intLiberados .'';
				$sJSON .= ',"intEnproceso":'. $intEnproceso .'';
			$sJSON .= "},";
	
			$i++;
	
		}
	
		if($i>0){
			$sJSON = substr($sJSON, 0, -1);
		}

	$sJSON .= "]},"; //CIERRA NODO EMPRESA

	//$sJSON .= "]}"; //CIERRA arr Items

	sqlsrv_free_stmt( $getResults );


	////////////////   2DA PARTE    ////////////	//// AHORA RECOJO DATOS DE EMPRESAS
	
	//$query = "SELECT t1.FAC_FEC, t1.FAC_CRE, t3.CON_DES, count(t2.EST_EST) as intEstudios FROM exax2000 t1  INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM)  INNER JOIN anav5000 t3 ON (t1.FAC_CRE=t3.CON_CVE)  WHERE 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0 AND t2.EST_EST LIKE '%covid%' AND t1.FAC_CRE <> '002' GROUP BY t1.FAC_FEC, t1.FAC_CRE, t3.CON_DES ORDER BY t1.FAC_CRE ASC";
	
	$query = "SELECT t2.FEC_INT, t1.FAC_CRE, t3.CON_DES, count(t2.EST_EST) as intEstudios 
	FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) 
	INNER JOIN anav5000 t3 ON (t1.FAC_CRE=t3.CON_CVE) 
	WHERE 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0 AND t1.FAC_CRE <> '002' AND t2.EST_EST IN ('covid','covic','covfl','covar') ";  //t2.EST_EST LIKE '%covid%'
	
	//***************** ARREGLAR SEGUN FEC_INT
	if(isset($_REQUEST['strFechas'])){

		$strFechas = $_REQUEST['strFechas'];
		//$strFechas = decode($strFechas);
		$strFechas = $strFechas;

		$arrFechas = explode(" - ", $strFechas);
		$strFec1 = $arrFechas[0];

		if(count($arrFechas)>1){

			$strFec2 = $arrFechas[1];

			//      26/02/2020 - 04/03/2020
			$strFec1 = str_replace("/", "-", $arrFechas[0]);
			$strFec2 = str_replace("/", "-", $arrFechas[1]);
			
			$arrFec1 = explode("/", $arrFechas[0]);
			$strFec3 = $arrFec1[2].$arrFec1[1].$arrFec1[0];

			$arrFec2 = explode("/", $arrFechas[1]);
			$strFec4 = $arrFec2[2].$arrFec2[1].$arrFec2[0];
			
			$query .= " AND ( (t2.EST_ENV > CONVERT(datetime, '". $strFec1 ." 00:00:00.000') AND t2.EST_ENV < CONVERT(datetime, '". $strFec2 ." 23:59:00.000')) OR (t2.FEC_INT>='". $strFec3 ."' AND t2.FEC_INT<='". $strFec4 ."') ) ";

		}else{
			$strFec1 = str_replace("/", "-", $arrFechas[0]);

			$arrFec1 = explode("/", $arrFechas[0]);
			$strFec1FormatoAnt = $arrFec1[2].$arrFec1[1].$arrFec1[0];

			$query .= " AND ( (t2.EST_ENV > CONVERT(datetime, '". $strFec1 ." 00:00:00.000') AND t2.EST_ENV < CONVERT(datetime, '". $strFec1 ." 23:59:00.000')) OR (t2.FEC_INT='". $strFec1FormatoAnt ."') ) ";

		}
		
	}
	
	//$query .= " AND t2.FEC_INT>='20200701'";
	$query .= " AND t2.FEC_INT>='". $strFecha60DiasAtras ."'";
	$query .= " GROUP BY t2.FEC_INT, t1.FAC_CRE, t3.CON_DES ORDER BY t1.FAC_CRE ASC, convert(datetime, t2.FEC_INT, 103) DESC";
	
	//$query .= " GROUP BY t2.FEC_INT ORDER BY convert(datetime, t2.FEC_INT, 103)  ASC";

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults= sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
 
		//$strFecha = $row['FAC_FEC'];
		$strFecha = $row['FEC_INT'];
		$strClaveEmpresa = $row['FAC_CRE'];
		$strEmpresa = $row['CON_DES'];

		$intEstudios = $row['intEstudios'];

		if($strClaveEmpresaAnt!==$strClaveEmpresa){
	
			if($i>0){
				$sJSON = substr($sJSON, 0, -1);
				$sJSON .= "]},";
			}

			$sJSON .= "{";
			$sJSON .= '"strClaveEmpresa":"'. $strClaveEmpresa .'"';
			$sJSON .= ',"strEmpresa":"'. $strEmpresa .'"';

			$sJSON .= ',"arrFechas":[';

			$strClaveEmpresaAnt = $strClaveEmpresa;

		}

		//$intLiberados = rand(1,$intEstudios);
		$intLiberados = getLiberados(2, $strFecha, $strClaveEmpresa);
		usleep(10);

		$intEnproceso = $intEstudios - $intLiberados;

		$sJSON .= "{";
			$sJSON .= '"strFecha":"'. $strFecha .'"';
			$sJSON .= ',"intEstudios":'. $intEstudios .'';
			$sJSON .= ',"intLiberados":'. $intLiberados .'';
			$sJSON .= ',"intEnproceso":'. $intEnproceso .'';
		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]}"; //CIERRA NODO EMPRESA

	$sJSON .= "]}"; //CIERRA arr Items

	sqlsrv_free_stmt( $getResults );
	*/

}else if( $method == "getVentas" ){        /////////////// RESUMEN VENTAS  /////////////////

	//$intEmpresa = $_REQUEST["intEmpresa"];
	$intEmpresa = '001';
	
	$FAC_CRE = "";

	//-----------------------------        CONSTRUCCION DEL WHERE         -------------------------------'
	$strWHERE = " t1.FAC_CAN=0 ";
	
	
	if(1==12){ //--------------- POR TIPO FACTURA/REMISION
		$selectFmt = $_REQUEST["selectFmt"];

		if($selectFmt=="cortesias"){ // POR CORTESIAS
			$strWHERE .= " AND t1.FAC_TOT = '0.00' AND t1.FAC_DES='100' ";
		//'}else{ 
		//'	$strWHERE .= " AND FAC_TOT > 0.00 ";
		}
	}

	if(1==1 && isset($_REQUEST["selectTipo"])){ //--------------- POR TIPO FACTURA/REMISION
		$selectTipo = $_REQUEST["selectTipo"];

		if($selectTipo!=="FR" && $selectTipo!==""){
			$strWHERE .= " AND t1.FAC_TPO='". $selectTipo ."'";
		}
	}

	if(1==1 && isset($_REQUEST["txtEdadIni"])){ 	//--------------- POR EDADES
		$txtEdad1 = trim($_REQUEST["txtEdadIni"]);
		$txtEdad2 = trim($_REQUEST["txtEdadFin"]);

		if($txtEdad1!=="" && $txtEdad2!==""){
		    //'SELECT * FROM EXAX2000 WHERE FAC_CAN=0 AND FAC_TPO='F'  AND FAC_SUC='66'  AND FAC_FEC >='20140509' AND FAC_FEC<='20140509'   
			//'AND FAC_EDA >= CASE WHEN CHARINDEX('m', fac_eda)<1 AND (FAC_EDA between 19 and 20)  THEN FAC_EDA ELSE NULL END  AND FAC_EDA <= CASE WHEN CHARINDEX('m', fac_eda)<1 AND (FAC_EDA between 19 and 20)  THEN FAC_EDA ELSE NULL END 

			//'strWHERE = strWHERE & " AND FAC_EDA >= "& EDAD1 &" AND FAC_EDA <= " & EDAD2
			//'strWHERE = strWHERE & " AND (FAC_EDA between "& EDAD1 &" and "& EDAD2 &" ) "
			if($txtEdad1=="0"){
				//'strWHERE = strWHERE & " AND FAC_EDA <= " & EDAD2
				$strWHERE .= " AND ( ISNUMERIC ( t1.FAC_EDA )=0 OR t1.FAC_EDA <= (CASE WHEN ISNUMERIC ( t1.FAC_EDA )=1 AND (t1.FAC_EDA <= ". $txtEdad2 .") THEN t1.FAC_EDA ELSE NULL END) ) ";
			}else{
				$strWHERE .= " AND t1.FAC_EDA >= (CASE WHEN ISNUMERIC ( t1.FAC_EDA )=1 AND (t1.FAC_EDA between ". $txtEdad1 ." and ". $txtEdad2 .") THEN t1.FAC_EDA ELSE NULL END) AND t1. FAC_EDA <= (CASE WHEN ISNUMERIC ( t1.FAC_EDA )=1 AND (t1.FAC_EDA between ". $txtEdad1 ." and ". $txtEdad2 .") THEN t1.FAC_EDA ELSE NULL END) ";
			}	
		}
	}

	if(1==1 && isset($_REQUEST["selectSexo"])){	//--------------- POR SEXO
		$selectSexo = $_REQUEST["selectSexo"];
		if($selectSexo!=="FM" && $selectSexo!==""){
			$strWHERE .= " AND t1.FAC_SEX = '". $selectSexo ."'";
		}
	}

	if(1==1 && isset($_REQUEST["txtHoraIni"])){	//--------------- POR HORAS
		$txtHora1 = trim($_REQUEST["txtHoraIni"]);
		$txtHora2 = trim($_REQUEST["txtHoraFin"]);
		if(strlen($txtHora1)==1){
			$txtHora1 = "0". $txtHora1;
		}
		if(strlen($txtHora2)==1){
			$txtHora2 = "0". $txtHora2;
		}

		if($txtHora1!=="" && $txtHora2!==""){
			$strWHERE .= " AND SUBSTRING(t1.FAC_HOR,1,". strlen($txtHora1) .")>='". $txtHora1 ."' AND SUBSTRING(t1.FAC_HOR,1,". strlen($txtHora2) .")<'". $txtHora2 ."'";
		}
	}
	
	//---------------------------    FIN  CONSTRUCCION DEL WHERE     -------------------------'

	$arrFechas = getArrFechas($method, $_REQUEST['strFechas']);
	$strWhereFechas = $arrFechas[0];
	$strWhereFechas0 = $arrFechas[1];

	$query = "SELECT t1.FAC_SUC AS CLAVE, ( SELECT t2.SUC_PAS FROM anav6000 t2 WHERE t2.SUC_CVE=t1.FAC_SUC ) as SUCURSAL, ";
	$query .=  " COUNT(CASE WHEN ". $strWhereFechas ." THEN t1.FAC_NUM ELSE NULL END) AS 'intPacientes1',";
	//IF selectFMT="PorCortesias" THEN ' POR CORTESIAS
	//	$query .=  " SUM(CASE WHEN "& caseWhen1 &" THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,FAC_TOT)/1.16) ELSE NULL END) AS 'SUMAS1',"
	//ELSE 
		$query .=  " SUM(CASE WHEN ". $strWhereFechas ." THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,t1.FAC_TOT)/1.16) ELSE NULL END) AS 'intSumas1',";
	//END IF
	$query .=  " COUNT(CASE WHEN ". $strWhereFechas0 ." THEN t1.FAC_NUM ELSE NULL END) AS 'intPacientes2',";
	//IF selectFMT="PorCortesias" THEN ' POR CORTESIAS
	//	$query .=  " SUM(CASE WHEN "& caseWhen2 &" THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,FAC_TOT)/1.16) ELSE NULL END) AS 'SUMAS2'";
	//ELSE 
		$query .=  " SUM(CASE WHEN ". $strWhereFechas0 ." THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,t1.FAC_TOT)/1.16) ELSE NULL END) AS 'intSumas2'";
	//END IF
	$query .=  " FROM EXAX2000 t1 ";
	$query .=  " WHERE ". $strWHERE ;
	$query .=  " GROUP BY t1.FAC_SUC ORDER BY t1.FAC_SUC ASC" ;

	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$sJSON = '{"Items":[';

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strClave = $row['CLAVE'];
		$strSucursal = $row['SUCURSAL'];

		$intPacientes1 = $row['intPacientes1'];
		if($intPacientes1==null){
			$intPacientes1 = 0;
		}
		
		$intPacientes2 = $row['intPacientes2'];
		if($intPacientes2==null){
			$intPacientes2 = 0;
		}

		$intSumas1 = $row['intSumas1'];
		if($intSumas1==null){
			$intSumas1 = 0;
		}
		if(is_numeric($intSumas1)){
			if($intSumas1==.000){
				$intSumas1 = 0;
			}
		}

		$intSumas2 = $row['intSumas2'];
		if($intSumas2==null){
			$intSumas2 = 0;
		}
		if(is_numeric($intSumas2)){
			if($intSumas2==.000){
				$intSumas2 = 0;
			}
		}

		$sJSON .= "{";
			//$sJSON .= '"strFecha":"'. $strFecha .'"';
			$sJSON .= '"strClave":"'. $strClave .'"';
			$sJSON .= ',"strSucursal":"'. $strSucursal .'"';

			$pctPacientes = "";
			if($intPacientes1!=0 && $intPacientes2!=0){
				$pctPacientes0 = ( intval($intPacientes1)*100 ) / ( intval($intPacientes2) );
				$pctPacientes = ($pctPacientes0) - 100;
				if($pctPacientes==0){ 
					$pctPacientes = "";
				}else{
					$pctPacientes = number_format($pctPacientes,2);
				}
			}

			$sJSON .= ',"pctPacientes":"'. $pctPacientes .'"';
			
			$sJSON .= ',"intPacientes1":'. $intPacientes1 .'';
			$sJSON .= ',"intPacientes2":'. $intPacientes2 .'';

			$sJSON .= ',"intSumas1":'. $intSumas1 .'';
			$sJSON .= ',"intSumas2":'. $intSumas2 .'';

			//$sJSON .= ',"intLiberados":'. $intLiberados .'';
			//$sJSON .= ',"intEnproceso":'. $intEnproceso .'';

		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);

		//$sJSON .= "]}"; //CIERRA NODO EMPRESA
	}

	$sJSON .= "]"; //CIERRA arrItems

	sqlsrv_free_stmt( $getResults );

/*-----------------  AGRUPADO X DIA  ---------------------*/

	$sJSON .= ',"ItemsxDia":[';

	$query = "SELECT t1.FAC_FEC as DIA, t1.FAC_SUC AS CLAVE, ( SELECT t2.SUC_PAS FROM anav6000 t2 WHERE t2.SUC_CVE=t1.FAC_SUC ) as SUCURSAL, ";
	$query .=  " COUNT(CASE WHEN ". $strWhereFechas ." THEN t1.FAC_NUM ELSE NULL END) AS 'intPacientes1',";
	//IF selectFMT="PorCortesias" THEN ' POR CORTESIAS
	//	$query .=  " SUM(CASE WHEN "& caseWhen1 &" THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,FAC_TOT)/1.16) ELSE NULL END) AS 'SUMAS1',"
	//ELSE 
		$query .=  " SUM(CASE WHEN ". $strWhereFechas ." THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,t1.FAC_TOT)/1.16) ELSE NULL END) AS 'intSumas1' ";
	//END IF
	
	//////////////$query .=  " COUNT(CASE WHEN ". $strWhereFechas0 ." THEN t1.FAC_NUM ELSE NULL END) AS 'intPacientes2',";
	//IF selectFMT="PorCortesias" THEN ' POR CORTESIAS
	//	$query .=  " SUM(CASE WHEN "& caseWhen2 &" THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,FAC_TOT)/1.16) ELSE NULL END) AS 'SUMAS2'";
	//ELSE 
		///////////$query .=  " SUM(CASE WHEN ". $strWhereFechas0 ." THEN CONVERT(DECIMAL(9,3),CONVERT(MONEY,t1.FAC_TOT)/1.16) ELSE NULL END) AS 'intSumas2'";
	//END IF
	$query .=  " FROM EXAX2000 t1 ";
	$query .=  " WHERE ". $strWHERE ." AND ". $strWhereFechas ;
	$query .=  " GROUP BY t1.FAC_FEC, t1.FAC_SUC ORDER BY t1.FAC_FEC ASC, t1.FAC_SUC ASC" ;

	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strFecha = $row['DIA'];
		$strMes = substr($strFecha, 4, 2);
		$strDia = substr($strFecha, 6, 2);
		$strDia = $shortMonth[$strMes] ." ". $strDia;
		
		$strClave = $row['CLAVE'];
		$strSucursal = $row['SUCURSAL'];

		$intPacientes1 = $row['intPacientes1'];
		if($intPacientes1==null){
			$intPacientes1 = 0;
		}
		
		/*$intPacientes2 = $row['intPacientes2'];
		if($intPacientes2==null){
			$intPacientes2 = 0;
		}*/

		$intSumas1 = $row['intSumas1'];
		if($intSumas1==null){
			$intSumas1 = 0;
		}

		if(is_numeric($intSumas1)){
			if($intSumas1==.000){
				$intSumas1 = 0;
			}
		}else{

		}
		/*
		$intSumas2 = $row['intSumas2'];
		if($intSumas2==null){
			$intSumas2 = 0;
		}*/

		$sJSON .= "{";
			//$sJSON .= '"strFecha":"'. $strFecha .'"';
			//$sJSON .= '"strDia":"Día '. $strDia .'"';
			$sJSON .= '"strDia":"'. $strDia .'"';
			$sJSON .= ',"strClave":"'. $strClave .'"';
			$sJSON .= ',"strSucursal":"'. $strSucursal .'"';

			/*
			$pctPacientes = "";
			if($intPacientes1!=0 && $intPacientes2!=0){
				$pctPacientes0 = ( intval($intPacientes1)*100 ) / ( intval($intPacientes2) );
				$pctPacientes = ($pctPacientes0) - 100;
				if($pctPacientes==0){ 
					$pctPacientes = "";
				}else{
					$pctPacientes = number_format($pctPacientes,2);
				}
			}
			*/

			//$sJSON .= ',"pctPacientes":"'. $pctPacientes .'"';
			
			$sJSON .= ',"intPacientes1":'. $intPacientes1 .'';
			//$sJSON .= ',"intPacientes2":'. $intPacientes2 .'';

			$sJSON .= ',"intSumas1":'. $intSumas1 .'';
			//$sJSON .= ',"intSumas2":'. $intSumas2 .'';


		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]}"; 

	sqlsrv_free_stmt( $getResults );

}else if( $method == "getProduccion" ){        /////////////// RESUMEN PRODUCCION /////////////////

	//$intEmpresa = $_REQUEST["intEmpresa"];
	$intEmpresa = '001';
	
	$FAC_CRE = "";

	$strWHERE = " 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0";
	
	if(1==12){ //----------- POR TIPO FACTURA/REMISION
		$selectFmt = $_REQUEST["selectFmt"];

		if($selectFmt=="cortesias"){ // POR CORTESIAS
			$strWHERE .= " AND t1.FAC_TOT = '0.00' AND t1.FAC_DES='100' ";
		}
	}

	/*
	if(1==1 && isset($_REQUEST["selectTipo"])){ //--------------- POR TIPO FACTURA/REMISION
		$selectTipo = $_REQUEST["selectTipo"];

		if($selectTipo!=="FR" && $selectTipo!==""){
			$strWHERE .= " AND t1.FAC_TPO='". $selectTipo ."'";
		}
	}
	*/

	//exit("555555555");

	$arrFechas = getArrFechas($method, $_REQUEST['strFechas']);
	$strWhereFechas = $arrFechas[0];
	$strWhereFechas0 = $arrFechas[1];

	$query = "SELECT t2.EST_EST, t2.EST_DES ";
	
	if(1===1){
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) AS intEstudios1 ";
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas0 ." THEN t2.EST_EST ELSE NULL END) AS intEstudios2 ";
	}else{
		$query .= ", COUNT(t2.EST_EST) as intEstudios1 ";
	}
	
	$query .= " FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) ";
	//$query .= " WHERE 1=1 AND  t1.FAC_CAN=0 AND t2.EST_CAN=0 ";
	$query .=  " WHERE ". $strWHERE ." AND ". $strWhereFechas ;

/*
	if(isset($_REQUEST['selectConvenio'])){
		$strConvenio = $_REQUEST['selectConvenio'];
		$query .= " AND t1.FAC_CRE = ". $strConvenio;
	}else{
		$query .= " AND t1.FAC_CRE <> '002' ";		
	}
*/	

	$query .= " GROUP BY t2.EST_EST, t2.EST_DES ";
	$query .= " HAVING COUNT(CASE WHEN  ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) >= 1 ";
	$query .= " OR COUNT(CASE WHEN  ". $strWhereFechas0 ." THEN t2.EST_EST ELSE NULL END) >= 1 ";
	$query .= " ORDER BY COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) DESC ";
	
	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$sJSON = '{"Items":[';

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
 
		//$strFecha = $row['FAC_FEC'];
		//$strFecha = $row['FEC_INT'];
		
		//$strClaveEmpresa = $row['FAC_CRE'];
		//$strEmpresa = $row['CON_DES'];
		
		$strClaEst = $row['EST_EST'];
		$strEstudio = $row['EST_DES'];

		$intEstudios1 = $row['intEstudios1'];
		$intEstudios2 = $row['intEstudios2'];

		$sJSON .= "{";
			//$sJSON .= '"strFecha":"'. $strFecha .'"';
			$sJSON .= '"strClaEst":"'. $strClaEst .'"';
			$sJSON .= ',"strEstudio":"'. $strEstudio .'"';

			$pctEstudios = "";
			if($intEstudios1!=0 && $intEstudios2!=0){
				$pctEstudios0 = ( intval($intEstudios1)*100 ) / ( intval($intEstudios2) );
				$pctEstudios = ($pctEstudios0) - 100;
				if($pctEstudios==0){ 
					$pctEstudios = "";
				}else{
					$pctEstudios = number_format ($pctEstudios,2);
				}
			}

			$sJSON .= ',"pctEstudios":"'. $pctEstudios .'"';
			
			$sJSON .= ',"intEstudios1":'. $intEstudios1 .'';
			$sJSON .= ',"intEstudios2":'. $intEstudios2 .'';

		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]"; //CIERRA Items

	sqlsrv_free_stmt( $getResults );


/*-----------------  AGRUPADO X DIA  ---------------------*/

	$sJSON .= ',"ItemsxDia":[';

	//$query = "SELECT t1.FAC_FEC as DIA, t2.EST_EST, t2.EST_DES ";
	$query = "SELECT t1.FAC_FEC as DIA ";
	
	//if(1===1){
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) AS intEstudios1 ";
	//}else{
	//	$query .= ", COUNT(t2.EST_EST) as intEstudios1 ";
	//}
	
	$query .= " FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) ";
	//$query .= " WHERE 1=1 AND  t1.FAC_CAN=0 AND t2.EST_CAN=0 ";
	$query .=  " WHERE ". $strWHERE ." AND ". $strWhereFechas ;

	/*
	if(isset($_REQUEST['selectConvenio'])){
		$strConvenio = $_REQUEST['selectConvenio'];
		$query .= " AND t1.FAC_CRE = ". $strConvenio;
	}else{
		$query .= " AND t1.FAC_CRE <> '002' ";		
	}
	*/
	
	if(isset($_REQUEST['strItems'])){
		$strItems = str_replace(",", "','", $_REQUEST['strItems']);
		$query .= " AND t2.EST_EST IN ('". $strItems ."')";
	}

	//$query .= " GROUP BY t1.FAC_FEC, t2.EST_EST, t2.EST_DES ";
	$query .= " GROUP BY t1.FAC_FEC  ";
	$query .= " ORDER BY t1.FAC_FEC ASC ";

	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strFecha = $row['DIA']; //YYYYMMDD
		$strMes = substr($strFecha, 4, 2);
		$strDia = substr($strFecha, 6, 2);
		$strDia = $shortMonth[$strMes] ." ". $strDia;
		
		//$strClave = $row['EST_EST'];
		//$strEstudio = $row['EST_DES'];

		$intEstudios1 = $row['intEstudios1'];
		if($intEstudios1==null){
			$intEstudios1 = 0;
		}

		/*$intSumas1 = $row['intSumas1'];
		if($intSumas1==null){
			$intSumas1 = 0;
		}

		if(is_numeric($intSumas1)){
			if($intSumas1==.000){
				$intSumas1 = 0;
			}
		}
		*/

		$sJSON .= "{";
			$sJSON .= '"strDia":"'. $strDia .'"';
			//$sJSON .= ',"strClave":"'. $strClave .'"';
			//$sJSON .= ',"strEstudio":"'. $strEstudio .'"';
			$sJSON .= ',"intEstudios":'. $intEstudios1 .'';
			//$sJSON .= ',"intSumas1":'. $intSumas1 .'';

		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]}"; //CIERRA ItemsxDia

	sqlsrv_free_stmt( $getResults );

}else if( $method == "getEstudiosProduccion" ){        /////////////// RESUMEN PRODUCCION /////////////////

	$intEmpresa = '001';
	
	$FAC_CRE = "";

	$strWHERE = " 1=1 AND t1.FAC_CAN=0 AND t2.EST_CAN=0";
	
	if(1==12){ //--------------- POR TIPO FACTURA/REMISION
		$selectFmt = $_REQUEST["selectFmt"];

		if($selectFmt=="cortesias"){ // POR CORTESIAS
			$strWHERE .= " AND t1.FAC_TOT = '0.00' AND t1.FAC_DES='100' ";
		}
	}

	//exit("5");

	$arrFechas = getArrFechas($method, $_REQUEST['strFechas']);
	$strWhereFechas = $arrFechas[0];
	$strWhereFechas0 = $arrFechas[1];

	/*
	$query = "SELECT t2.EST_EST, t2.EST_DES ";
	
	if(1===1){
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) AS intEstudios1 ";
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas0 ." THEN t2.EST_EST ELSE NULL END) AS intEstudios2 ";
	}else{
		$query .= ", COUNT(t2.EST_EST) as intEstudios1 ";
	}
	
	$query .= " FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) ";
	//$query .= " WHERE 1=1 AND  t1.FAC_CAN=0 AND t2.EST_CAN=0 ";
	$query .=  " WHERE ". $strWHERE ." AND ". $strWhereFechas ;
	$query .= " GROUP BY t2.EST_EST, t2.EST_DES ";
	$query .= " HAVING COUNT(CASE WHEN  ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) >= 1 ";
	$query .= " OR COUNT(CASE WHEN  ". $strWhereFechas0 ." THEN t2.EST_EST ELSE NULL END) >= 1 ";
	$query .= " ORDER BY COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) DESC ";
	
	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}
	*/

	$sJSON = '{"Items":[';

/*
	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
 		
		$strClaEst = $row['EST_EST'];
		$strEstudio = $row['EST_DES'];

		$intEstudios1 = $row['intEstudios1'];
		$intEstudios2 = $row['intEstudios2'];

		$sJSON .= "{";
			//$sJSON .= '"strFecha":"'. $strFecha .'"';
			$sJSON .= '"strClaEst":"'. $strClaEst .'"';
			$sJSON .= ',"strEstudio":"'. $strEstudio .'"';

			$pctEstudios = "";
			if($intEstudios1!=0 && $intEstudios2!=0){
				$pctEstudios0 = ( intval($intEstudios1)*100 ) / ( intval($intEstudios2) );
				$pctEstudios = ($pctEstudios0) - 100;
				if($pctEstudios==0){ 
					$pctEstudios = "";
				}else{
					$pctEstudios = number_format ($pctEstudios,2);
				}
			}

			$sJSON .= ',"pctEstudios":"'. $pctEstudios .'"';
			
			$sJSON .= ',"intEstudios1":'. $intEstudios1 .'';
			$sJSON .= ',"intEstudios2":'. $intEstudios2 .'';

		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]"; //CIERRA Items

	sqlsrv_free_stmt( $getResults );

*/

	$sJSON .= "]"; //CIERRA Items

/*-----------------  AGRUPADO X DIA  ---------------------*/


	$sJSON .= ',"ItemsxDia":[';

	//$query = "SELECT t1.FAC_FEC as DIA, t2.EST_EST, t2.EST_DES ";
	$query = "SELECT t1.FAC_FEC as DIA, t2.EST_EST ";
	
	//if(1===1){
		$query .= ", COUNT(CASE WHEN ". $strWhereFechas ." THEN t2.EST_EST ELSE NULL END) AS intEstudios1 ";
	//}else{
	//	$query .= ", COUNT(t2.EST_EST) as intEstudios1 ";
	//}
	
	$query .= " FROM exax2000 t1 INNER JOIN exax2010 t2 ON (t1.FAC_SUC=t2.EST_SUC AND t1.FAC_TPO=t2.EST_TPO AND t1.FAC_NUM=t2.EST_NUM) ";
	//$query .= " WHERE 1=1 AND  t1.FAC_CAN=0 AND t2.EST_CAN=0 ";
	$query .=  " WHERE ". $strWHERE ." AND ". $strWhereFechas ;
	
	if(isset($_REQUEST['strItems'])){
		$strItems = str_replace(",", "','", $_REQUEST['strItems']);
		$strItems = "'". $strItems ."'";
		$query .= " AND t2.EST_EST IN (". $strItems .")";
	}

	//$query .= " GROUP BY t1.FAC_FEC, t2.EST_EST, t2.EST_DES ";
	$query .= " GROUP BY t1.FAC_FEC, t2.EST_EST  ";
	$query .= " ORDER BY t1.FAC_FEC ASC, t2.EST_EST ASC ";
	
	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$strClaveEmpresaAnt = "";
	$i=0;
	//$arrValores = ["dia"=> "", "clave1"=>"0", "clave2"=>"0", "claveN"=>"0"];
	//$arrValores = ["dia"=> "", "clave1"=>"0", "clave2"=>"0", "claveN"=>"0"];
	
	$arrValores = [];

	$strItemsDia = "DIA,". $_REQUEST['strItems'];
	//exit("$strItemsDia");

	$arrClavesEstudios = explode(",", $strItemsDia);
	//array_push($arrValores, $arrClavesEstudios);

	//for($j=0; $j<$arrClavesEstudios; $j++){
	//}
	//var_dump($arrClavesEstudios);

	$strFechaOld = "";
	$strClaveOld = "";

	$i=0;
	$arrFecha = [];
	$strData = "";

   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strFecha = $row['DIA']; //YYYYMMDD

		$strMes = substr($strFecha, 4, 2);
		$strDia = substr($strFecha, 6, 2);
		$strDia = $shortMonth[$strMes] ." ". $strDia;
		
		$strClave = $row['EST_EST'];
		//$strEstudio = $row['EST_DES'];

		$intEstudios = $row['intEstudios1'];
		if($intEstudios==null){
			$intEstudios = 0;
		}

		
		//$objFecha = [ 0 => $strDia, $nCelda => $intEstudios1 ];
		//array_push($arrValores, $objFecha);

		if($strFechaOld != $strFecha){	

			if($i>0){
				array_push($arrValores, $strData);
			}

			$strData = "";

			/*$obj = new stdObject();
			$obj->dia = $strDia;

			$obj->val_1 = "Doe";
			$obj->val_2 = 20;
			$obj->val_3 = null;*/

			$strData .= "DIA-". $strDia ."/";
			$strData .= $strClave ."-". $intEstudios ."/";

			//$arrFecha = [ 0 => $strDia, $nCelda => $intEstudios1 ];
			//array_push($arrFecha, $nCelda => $intEstudios1);

			$strFechaOld = $strFecha;
			
		}else{
			
			$strData .= $strClave ."-". $intEstudios ."/";

			//$arrFecha = [ 0 => $strDia, $nCelda => $intEstudios1 ];
			//array_push($arrFecha, $nCelda => $intEstudios1);

		}

		/*
		$sJSON .= "{";
			$sJSON .= '"strDia":"'. $strDia .'"';

			if($strClaveOld != $strClave){

				$sJSON .= ',"strClave":"'. $strClave .'"';
				//$sJSON .= ',"strEstudio":"'. $strEstudio .'"';
				$sJSON .= ',"intEstudios":'. $intEstudios1 .'';

			}

		$sJSON .= "},";
		*/

		$i++;

	}
	
	array_push($arrValores, $strData);

	//var_dump($arrValores);
	
	//print("\n_____________________\n");

	$strDataGral = "";
	for($j=0; $j < count($arrValores); $j++){
		//print("\nRegistro: ". $arrValores[$j] ."\n");
		$strData = "";

		for($n=0; $n < count($arrClavesEstudios); $n++){
			$xKEY = $arrClavesEstudios[$n];
			$xVALOR = 0;
			//print("\n--->".$xCellDataArr1. "\n");

			$xRow = $arrValores[$j];
			$arrRow = explode("/", substr($xRow, 0, -1));
			for($nn=0; $nn < count($arrRow); $nn++){
				$xCell = $arrRow[$nn];
				$arrCell = explode("-", $arrRow[$nn]);

				$key = $arrCell[0];
				$valor = $arrCell[1];
				//print("\nxKEY:". $xKEY. " | xCell:". $xCell. " | key: ". $key . " | valor: ". $valor ."\n");
				
				if($xKEY==$key){
					//print("\n     IMPRIME key: ". $key . " valor: ". $valor ."\n");
					$xVALOR = $valor;
				}else{
					//print("\n     IMPRIME key: ". $key . " valor: 0\n");
				}

			}
			//print("\n     IMPRIME xKEY: ". $xKEY . " xVALOR: ". $xVALOR ."\n");

			$strData .= "$xKEY-$xVALOR/";

			//print("\n- - - - - - - - - - - - - - - \n");

		}
		
		//print("\n$strData\n");
		$strDataGral .= substr($strData , 0, -1).";";

		//print("\n__________________________________\n");

	}

	//print("\n$strDataGral\n");
	$arrDataGral = explode( ";", substr($strDataGral, 0, -1) );
	//var_dump($arrDataGral);
	//exit();

	for($n=0; $n < count($arrDataGral); $n++){

		/*if($n==0){
			$sJSON .= "{";

				$arrRow = explode("/", $arrDataGral[$n]);

				for($g=0; $g < count($arrRow); $g++){
					$arrCellRow = explode("-", $arrRow[$g]);

					$key = $arrCellRow[0];
					$valor = $arrCellRow[1];

					$sJSON .= '"'. $key .'":"'. $valor .'",';

				}
				$sJSON = substr($sJSON, 0, -1);

			$sJSON .= "},";
		}*/

		$sJSON .= "{";

			$arrRow = explode("/", $arrDataGral[$n]);

			for($g=0; $g < count($arrRow); $g++){
				$arrCellRow = explode("-", $arrRow[$g]);

				$key = $arrCellRow[0];
				$valor = $arrCellRow[1];
				
				if($key=="DIA"){
					$sJSON .= '"'. $key .'":"'. $valor .'",';
				}else{
					$sJSON .= '"'. $key .'":'. $valor .',';
				}

			}
			$sJSON = substr($sJSON, 0, -1);

		$sJSON .= "},";
	}

	//exit();

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]"; //CIERRA ItemsxDia

	$sJSON .= ',"query":"'. $query .'"';

	$sJSON .= "}"; //CIERRA ItemsxDia


	sqlsrv_free_stmt( $getResults );


}else if( $method == "getCotizaciones" ){        /////////////// RESUMEN COTIZACIONES /////////////////

	$arrFechas = explode(" - ", $_REQUEST['strFechas']);
	$strFecha1 = $arrFechas[0];
	if(count($arrFechas)>1){
		$strFecha2 = $arrFechas[1];
	}

	//$query = "SELECT strOrigen, count(strOrigen) as intCotizaciones from tblcotizaciones ";
	$query = "SELECT CONVERT(varchar(11), datFechaAlta, 111) as DIA, count(strOrigen) as intCotizaciones from tblcotizaciones ";
	$query .= "WHERE ";
	if(count($arrFechas)>1){
		//$query .= "datFechaAlta between '". $strFecha1 ." 00:00:00' and '". $strFecha2 ." 23:59:59'";
		$query .= "datFechaAlta >= '". $strFecha1 ." 00:00:00' and datFechaAlta <= '". $strFecha2 ." 23:59:59'";
	}else{
		//$query .= "datFechaAlta between '". $strFecha1 ." 00:00:00' and '". $strFecha1 ." 23:59:59'";
		$query .= "datFechaAlta >= '". $strFecha1 ." 00:00:00' and datFechaAlta <= '". $strFecha1 ." 23:59:59'";
	}
	
	//$query .= "group by strOrigen order by count(strOrigen) desc";
	$query .= "GROUP BY CONVERT(varchar(11), datFechaAlta, 111) ORDER BY CONVERT(varchar(11), datFechaAlta, 111) asc";

	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn2, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$sJSON = '{"Items":[';

	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strFecha = $row['DIA']; //2022/04/06
		$strMes = substr($strFecha, 5, 2);
		$strDia = substr($strFecha, 8, 2);

		$strDia = $shortMonth[$strMes] ." ". $strDia;

		//$strOrigen = $row['strOrigen'];
		$intCotizaciones = $row['intCotizaciones'];

		if($intCotizaciones==null){
			$intCotizaciones = 0;
		}

		$sJSON .= "{";
			$sJSON .= '"strDia":"'. $strDia .'"';
			//$sJSON .= '"strOrigen":"'. $strOrigen .'"';
			$sJSON .= ',"intCotizaciones":'. $intCotizaciones .'';
		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]"; //CIERRA Items

	sqlsrv_free_stmt( $getResults );


/*-----------------  AGRUPADO X DIA  ---------------------*/


	$sJSON .= ',"ItemsxDia":[';

	$query = "SELECT CONVERT(varchar(11), datFechaAlta, 111) as DIA, strOrigen, count(strOrigen) as intCotizaciones from tblcotizaciones ";
	$query .= "WHERE ";
	if(count($arrFechas)>1){
		$query .= "datFechaAlta between '". $strFecha1 ." 00:00:00' and '". $strFecha2 ." 23:59:59'";
	}else{
		$query .= "datFechaAlta between '". $strFecha1 ." 00:00:00' and '". $strFecha1 ." 23:59:59'";
	}

	$query .= "GROUP BY CONVERT(varchar(11), datFechaAlta, 111), strOrigen ORDER BY CONVERT(varchar(11), datFechaAlta, 111) asc";

	/*select CONVERT(varchar(11), datFechaAlta, 111)   as DIA, strOrigen, count(strOrigen) as cuantos from tblcotizaciones where datFechaAlta between '06/04/2022 00:00:00' and '18/04/2022 23:59:59' group by CONVERT(varchar(11), datFechaAlta, 111) , strOrigen order by CONVERT(varchar(11), datFechaAlta, 111) asc
	*/

	//exit($query);

	if( isset($_REQUEST["debug"]) ){
		exit($query);
	}

	$getResults = sqlsrv_query( $conn2, $query );

	//Controlamos los errores
	if ( $getResults == FALSE ){
	    die( FormatErrors( sqlsrv_errors()));
	}

	$strClaveEmpresaAnt = "";
	$i=0;
   	while ( $row = sqlsrv_fetch_array( $getResults, SQLSRV_FETCH_ASSOC )) {
		
		$strFecha = $row['DIA']; //2022/04/06
		$strMes = substr($strFecha, 5, 2);
		$strDia = substr($strFecha, 8, 2);

		$strDia = $shortMonth[$strMes] ." ". $strDia;
		
		$strOrigen = $row['strOrigen'];
		$intCotizaciones = $row['intCotizaciones'];
		if($intCotizaciones==null){
			$intCotizaciones = 0;
		}

		$sJSON .= "{";
			$sJSON .= '"strDia":"'. $strDia .'"';
			$sJSON .= ',"strOrigen":"'. $strOrigen .'"';
			$sJSON .= ',"intCotizaciones":'. $intCotizaciones .'';

		$sJSON .= "},";
			
		$i++;

	}

	if($i>0){
		$sJSON = substr($sJSON, 0, -1);
	}

	$sJSON .= "]}"; //CIERRA ItemsxDia

	sqlsrv_free_stmt( $getResults );


}else if( $method == "agregarcomenres" ){ 

	$strNumPro = $_REQUEST['strNumPro'];
	$suc = substr($strNumPro, 0, 2);
	$tpo = substr($strNumPro, 2, 1);
	$num = substr($strNumPro, -6);

	$strClave = $_REQUEST['strClave'];
	$caso = $_REQUEST['caso'];
	$strComentarios = $_REQUEST['strComentarios'];
	if($strComentarios!=""){
		//$strComentarios = urldecode($strComentarios);
		$strComentarios = url_decode($strComentarios);
		
	}
	$intUsuario = $_REQUEST['intUsuario'];

	//$sJSON = setComentarios($suc, $tpo, $num, $strClave, $caso, $strComentarios, $intUsuario);

}

print($sJSON);

?>