<?php
if (file_exists("../bd/MySqlConnection.php")) {
	require_once("../bd/MySqlConnection.php");
} else {
	if (file_exists("./bd/MySqlConnection.php")) {
		require_once("./bd/MySqlConnection.php");
	} else if (file_exists("../bd/MySqlConnection.php")) {
		require_once("../bd/MySqlConnection.php");
	} else if (file_exists("../../bd/MySqlConnection.php")) {
		require_once("../../bd/MySqlConnection.php");
	}
}

class cotizaciones extends MySqlConnection{
	function iniciarSesion($usuario,$clave){
		$query = "SELECT c.*, o.NombreOrganizacion
		from cat_clientemuebles as c
		inner join cat_organizacion as o on o.OrganizacionID = c.OrganizacionID_FK
		where c.Usuario = BINARY '$usuario' and c.Password = BINARY '$clave'";
		$consulta = $this->ExecuteReader($query);
		if (sizeof($consulta) > 0) {
			setcookie("ClienteID",$consulta[0]["ClienteID"], time() + (86400*30), "/");
			setcookie("Nombre1",$consulta[0]["Nombre1"], time() + (86400*30), "/");
			setcookie("Apellido1",$consulta[0]["Apellido1"], time() + (86400*30), "/");
			setcookie("OrganizacionID",$consulta[0]["OrganizacionID_FK"], time() + (86400*30), "/");
			setcookie("Organizacion",$consulta[0]["NombreOrganizacion"], time() + (86400*30), "/");
			setcookie("sesion","activa", time() + (86400*30), "/");
			return "1";
		}
		else{
			return "Usuario y/o contraseña incorrectos";
		}
	}

	function traerCotizaciones($fecha_ini,$fecha_fin){
		$ClienteID = $_COOKIE["ClienteID"];
		$OrganizacionID = $_COOKIE["OrganizacionID"];
		$query = "(SELECT LPAD(cot.CotizacionID, 5, '0') as Folio,
		from_unixtime(cot.Fecha, '%d/%m/%Y') as Fecha, CotizacionID,
		cot.Cotizacion, st.StatusCot, cot.StatusCotID_FK,
		(select coalesce(sum(d.PrecioUni * d.Cantidad),0) from tbl_objcompcot as d
		where d.CotizacionID_FK = cot.CotizacionID) as Importe,
		from_unixtime(cot.FechaProceso, '%d/%m/%Y') as FechaProceso
		FROM tbl_cotizacion as cot
		inner join cat_clientemuebles as cl on cl.ClienteID = cot.ClienteID_FK
		inner join cat_statuscot as st on st.StatusCotID = cot.StatusCotID_FK
		where from_unixtime(cot.Fecha, '%Y-%m-%d') between '$fecha_ini' and '$fecha_fin'
		and cl.OrganizacionID_FK = '$OrganizacionID' and cot.FechaProceso is null)
		union all
		(SELECT LPAD(cot.CotizacionID, 5, '0') as Folio,
		from_unixtime(cot.Fecha, '%d/%m/%Y') as Fecha, CotizacionID,
		cot.Cotizacion, st.StatusCot, cot.StatusCotID_FK,
		(select coalesce(sum(d.PrecioUni * d.Cantidad),0) from tbl_objcompcot as d
		where d.CotizacionID_FK = cot.CotizacionID) as Importe,
		from_unixtime(cot.FechaProceso, '%d/%m/%Y') as FechaProceso
		FROM tbl_cotizacion as cot
		inner join cat_clientemuebles as cl on cl.ClienteID = cot.ClienteID_FK
		inner join cat_statuscot as st on st.StatusCotID = cot.StatusCotID_FK
		where from_unixtime(cot.FechaProceso, '%Y-%m-%d') between '$fecha_ini' and '$fecha_fin'
		and cl.OrganizacionID_FK = '$OrganizacionID' and cot.FechaProceso is not null)
		order by CotizacionID desc";
		return json_encode($this->ExecuteReader($query));
	}

	function insertaTemporalNuevo($ObjCompID,$Cantidad,$Referencia){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "INSERT into temptbl_objcomp(ObjCompID_FK,Cantidad,Referencia,ClienteID_FK)
		values(?,?,?,?)";
		$mysql = new MySqlConnection();
		return $mysql->getLastID($query, array($ObjCompID,$Cantidad,$Referencia,$ClienteID));
	}

	function eliminaTemporal($TempObjCompCotID,$Cantidad,$Referencia){
		/*$query = "DELETE from temptbl_objcomp where TempObjCompCotID = ?";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($TempObjCompCotID));*/
		$query = "UPDATE temptbl_objcomp set Cantidad = ?, Referencia = ?
		where TempObjCompCotID = ?";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($Cantidad,$Referencia,$TempObjCompCotID));
		$query = "DELETE from tempjnc_objcomp_objcomppar where TempObjCompCotID_FK = ?";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($TempObjCompCotID));
	}

	function insertaTemporal($CotizacionID){
		$ClienteID = $_COOKIE["ClienteID"];
		//$query = "call sp_InsertaTemporal(?)";
		$query = "call sp_InsertaTemporal(?,?)";
		//$this->ExecuteQuery($query, array($CotizacionID));
		$this->ExecuteQuery($query, array($CotizacionID,$ClienteID));
	}

	function insertaTemporalObjCom($TempObjCompCotID,$JncObjCompParID,$Valor){
		$mysql = new MySqlConnection();
		$query = "INSERT INTO tempjnc_objcomp_objcomppar(TempObjCompCotID_FK, JncObjCompParID_FK, Valor)
		values(?,?,?)";
		$mysql->ExecuteQuery($query, array($TempObjCompCotID,$JncObjCompParID,$Valor));
	}

	function cancelarCotizacion($id_cotizacion){
		$query = "UPDATE tbl_cotizacion set StatusCotID_FK = 5 where CotizacionID = ?";
		$this->ExecuteQuery($query, array($id_cotizacion));
	}

	function modificarCotizacion($Cotizacion,$CotizacionID,$cupon){
		$ClienteID = $_COOKIE["ClienteID"];
		if (empty($cupon)) {
			$cupon = null;
		}
		//$query = "call sp_modificaCotizacion(?,?)";
		$query = "call sp_modificaCotizacion(?,?,?,?)";
		//$this->ExecuteQuery($query, array($Cotizacion,$CotizacionID));
		$this->ExecuteQuery($query, array($Cotizacion,$CotizacionID,$ClienteID,$cupon));
	}

	function insertarCotizacion($Cotizacion, $cupon) {
		date_default_timezone_set("America/Mexico_City");
		$fecha = date("Y-m-d");
		$ClienteID = $_COOKIE["ClienteID"];
		// Verifica si el cupon está vacío y lo asigna a null si es el caso
		if (empty($cupon)) {
			$cupon = null;
		}	
		$query = "call sp_InsertaCotizacion(?,?,?,?);";
		$this->ExecuteQuery($query, array($Cotizacion, $ClienteID, $fecha, $cupon));
	}
	
	function procesarCotizacion($id_cotizacion,$cupon){
		date_default_timezone_set("America/Mexico_City");
		$fecha = date("Y-m-d");
		if (empty($cupon)) {
			$cupon = null;
		}	
		$query = "UPDATE tbl_cotizacion set StatusCotID_FK = 2,
		FechaProceso = UNIX_TIMESTAMP('$fecha')
		where CotizacionID = ?";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($id_cotizacion));
		$query = "SELECT Cotizacion from tbl_cotizacion where CotizacionID = '$id_cotizacion'";
		$mysql = new MySqlConnection();
		$Cotizacion = $mysql->ExecuteReader($query)[0]["Cotizacion"];
		$ClienteID = $_COOKIE["ClienteID"];
		//$query = "call sp_modificaCotizacion(?,?)";
		$query = "call sp_modificaCotizacion(?,?,?,?)";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($Cotizacion,$id_cotizacion,$ClienteID,$cupon));
	}

	function duplicarCotizacion($id_cotizacion,$cotizacion){
		date_default_timezone_set("America/Mexico_City");
		// date_default_timezone_set("Europe/Madrid");
		$fecha = date("Y-m-d");
		$query = "call sp_DuplicaCotizacion(?,?,?)";
		$this->ExecuteQuery($query, array($id_cotizacion,$cotizacion,$fecha));
	}

	function verCotizacion($id_cotizacion){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "(SELECT tbcot.Cotizacion, tbcot.StatusCotID_FK,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.PrecioUni, (tdet.PrecioUni * tdet.Cantidad) as Importe,
		from_unixtime(tbcot.Fecha, '%d/%m/%Y') as Fecha, tdet.ObjCompCotID,
		LPAD(tbcot.CotizacionID, 5, '0') as FolioCotizacion, tdet.TempObjCompCotID, tbcot.CuponID_FK
		FROM temptbl_objcomp as tdet
		inner join tbl_cotizacion as tbcot on tbcot.CotizacionID = tdet.CotizacionID_FK
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.CotizacionID_FK = '$id_cotizacion' and tdet.ClienteID_FK = '$ClienteID'
		and tdet.Activo = 1 and tdet.Nuevo = 0)
		UNION ALL
		(SELECT '' Cotizacion, '' StatusCotID_FK,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.PrecioUni, (tdet.PrecioUni * tdet.Cantidad) as Importe,
		date_format(current_date(), '%d/%m/%Y') as Fecha, tdet.ObjCompCotID,
		'Nuevo' as FolioCotizacion, tdet.TempObjCompCotID, NULL as CuponID_FK
		FROM temptbl_objcomp as tdet
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.ClienteID_FK = '$ClienteID' and tdet.Activo = 1
		and tdet.Nuevo = 1)";
		return json_encode($this->ExecuteReader($query));
	}

	function verCotizacionInfo($id_cotizacion){
		$query = "SELECT tbcot.Cotizacion, tbcot.StatusCotID_FK,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.PrecioUni, (tdet.PrecioUni * tdet.Cantidad) as Importe,
		from_unixtime(tbcot.Fecha, '%d/%m/%Y') as Fecha, tdet.ObjCompCotID,
		LPAD(tbcot.CotizacionID, 5, '0') as FolioCotizacion
		FROM tbl_objcompcot as tdet
		inner join tbl_cotizacion as tbcot on tbcot.CotizacionID = tdet.CotizacionID_FK
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.CotizacionID_FK = '$id_cotizacion'";
		return json_encode($this->ExecuteReader($query));
	}

	function verCotizacion2($id_cotizacion){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT tbcot.Cotizacion, tbcot.StatusCotID_FK,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.PrecioUni, (tdet.PrecioUni * tdet.Cantidad) as Importe,
		from_unixtime(tbcot.Fecha, '%d/%m/%Y') as Fecha, tdet.ObjCompCotID,
		LPAD(tbcot.CotizacionID, 5, '0') as FolioCotizacion
		FROM temptbl_objcomp as tdet
		inner join tbl_cotizacion as tbcot on tbcot.CotizacionID = tdet.CotizacionID_FK
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.CotizacionID_FK = '$id_cotizacion' and tdet.ClienteID_FK = '$ClienteID'
		and tdet.Activo = 1 and tdet.Nuevo = 0;";
		return $this->ExecuteReader($query);
	}

	function verCotizacionInfo2($id_cotizacion){
		$query = "SELECT tbcot.Cotizacion, tbcot.StatusCotID_FK,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.PrecioUni, (tdet.PrecioUni * tdet.Cantidad) as Importe,
		from_unixtime(tbcot.Fecha, '%d/%m/%Y') as Fecha, tdet.ObjCompCotID,
		LPAD(tbcot.CotizacionID, 5, '0') as FolioCotizacion
		FROM tbl_objcompcot as tdet
		inner join tbl_cotizacion as tbcot on tbcot.CotizacionID = tdet.CotizacionID_FK
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.CotizacionID_FK = '$id_cotizacion'";
		return $this->ExecuteReader($query);
	}

	function verCotizacionTemporal(){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.TempObjCompCotID as ObjCompCotID
		FROM temptbl_objcomp as tdet
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.ClienteID_FK = '$ClienteID' and tdet.Activo = 1
		and tdet.Nuevo = 1;";
		return json_encode($this->ExecuteReader($query));
	}

	function verCotizacionTemporal2(){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, ctobj.UniObjComp as Unidad,
		tdet.TempObjCompCotID as ObjCompCotID
		FROM temptbl_objcomp as tdet
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.ClienteID_FK = '$ClienteID' and tdet.Activo = 1
		and tdet.Nuevo = 1;";
		return $this->ExecuteReader($query);
	}

	function eliminaCotizacionTemporal(){
		$ClienteID = $_COOKIE["ClienteID"];
		$mysql = new MySqlConnection();
		$query = "DELETE tempdet1, tempdet2 from temptbl_objcomp as tempdet1
		left join tempjnc_objcomp_objcomppar as tempdet2
		on tempdet2.TempObjCompCotID_FK = tempdet1.TempObjCompCotID
		where tempdet1.ClienteID_FK = ?;";
		$mysql->ExecuteQuery($query, array($ClienteID));
		$mysql = new MySqlConnection();
		$query = "DELETE FROM temp_parcot where ClienteID_FK = ?;";
		$mysql->ExecuteQuery($query, array($ClienteID));
	}

	function getDistinctPar(){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT jobpardet.JncObjCompParID_FK, par.UniParametro,
		coalesce(jobpar.NameOverride, par.Parametro) as Parametro, det.ObjCompID_FK
		FROM temptbl_objcomp as det
		INNER JOIN tempjnc_objcomp_objcomppar as jobpardet ON det.TempObjCompCotID = jobpardet.TempObjCompCotID_FK
		INNER JOIN jnc_objcomp_par as jobpar on jobpar.JncObjCompParID = jobpardet.JncObjCompParID_FK
		INNER JOIN cat_parametro as par on par.ParametroID = jobpar.ParametroID_FK
		WHERE det.ClienteID_FK = '$ClienteID' and jobpar.Activo = 1
		and jobpar.ValorFijo = 0 and det.Activo = 1
		group by jobpar.ParametroID_FK, coalesce(jobpar.NameOverride, par.Parametro)
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return json_encode($this->ExecuteReader($query));
	}

	function eliminarObjetoCompuesto($ObjCompCotID){
		$query = "UPDATE temptbl_objcomp set Activo = 0 WHERE TempObjCompCotID = ?;";
		$this->ExecuteQuery($query, array($ObjCompCotID));
	}

	function obtenerAreaObj(){
		$OrganizacionID = $_COOKIE["OrganizacionID"];
		$query = "SELECT area.* FROM cat_areaobj as area
		inner join jnc_organizacion_areaobj as areacliente on areacliente.AreaObjID_FK = area.AreaObjID
		where areacliente.OrganizacionID_FK = '$OrganizacionID'";
		return json_encode($this->ExecuteReader($query));
	}

	function obtenerMueblesXArea($AreaObjID){
		$query = "SELECT * FROM cat_objcomp WHERE AreaObjID_FK = '$AreaObjID'";
		return json_encode($this->ExecuteReader($query));
	}

	function obtenerParametrosXMueble($ObjCompID){
		$query = "SELECT jobpar.*,
		coalesce(jobpar.NameOverride,cpar.Parametro) as Parametro, cpar.UniParametro,
		cpar.Opciones, cpar.Query, cobj.ClaveObjComp, cobj.Activo as objActivo, cobj.ObjComp as CatNombre FROM jnc_objcomp_par as jobpar
		inner join cat_parametro as cpar on cpar.ParametroID = jobpar.ParametroID_FK
		inner join cat_objcomp as cobj on jobpar.ObjCompID_FK = cobj.ObjCompID
		where jobpar.ObjCompID_FK = '$ObjCompID' and jobpar.Activo = 1
		order by jobpar.ValorFijo, coalesce(cpar.OrdenEtiquetas, 999999999)";
		return json_encode($this->ExecuteReader($query));
	}

	function ejecutarConsulta($consulta){
		return $this->ExecuteReader($consulta);
	}

	function insertaParametroTemporal($ParametroID,$NameOverride,$Valor){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT * from temp_parcot where ParametroID = '$ParametroID' and
		NameOverride = '$NameOverride' and ClienteID_FK = '$ClienteID'";
		$mysql = new MySqlConnection();
		$consulta = $mysql->ExecuteReader($query);
		if (sizeof($consulta) > 0) {
			$query = "UPDATE temp_parcot set Valor = ? where ParametroID = ? and
			NameOverride = ? and ClienteID_FK = ?";
			$mysql = new MySqlConnection();
			$mysql->ExecuteQuery($query, array($Valor,$ParametroID,$NameOverride,$ClienteID));
		}
		else{
			$query = "INSERT into temp_parcot(ParametroID,NameOverride,Valor,ClienteID_FK)
			values(?,?,?,?);";
			$mysql = new MySqlConnection();
			$mysql->ExecuteQuery($query, array($ParametroID,$NameOverride,$Valor,$ClienteID));
		}
	}

	function obtenerParametrosCotizacion2($ObjCompCotID){
		$query = "SELECT det.ObjCompCotID, jobpardet.JncObjCompParID_FK,
		jobpardet.Valor, jobpar.NameOverride, par.Parametro, par.UniParametro,
		par.Opciones, par.Query
		FROM temptbl_objcomp as det
		INNER JOIN tempjnc_objcomp_objcomppar as jobpardet ON det.TempObjCompCotID = jobpardet.TempObjCompCotID_FK
		INNER JOIN jnc_objcomp_par as jobpar on jobpar.JncObjCompParID = jobpardet.JncObjCompParID_FK
		INNER JOIN cat_parametro as par on par.ParametroID = jobpar.ParametroID_FK
		WHERE det.ObjCompCotID = '$ObjCompCotID' and jobpar.Activo = 1
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return $this->ExecuteReader($query);
	}

	function obtenerParametrosCotizacionInfo2($ObjCompCotID){
		$query = "SELECT det.ObjCompCotID, jobpardet.JncObjCompParID_FK,
		jobpardet.Valor, jobpar.NameOverride, par.Parametro, par.UniParametro,
		par.Opciones, par.Query
		FROM tbl_objcompcot as det
		INNER JOIN jnc_objcompcot_objcomppar as jobpardet ON det.ObjCompCotID = jobpardet.ObjCompCotID_FK
		INNER JOIN jnc_objcomp_par as jobpar on jobpar.JncObjCompParID = jobpardet.JncObjCompParID_FK
		INNER JOIN cat_parametro as par on par.ParametroID = jobpar.ParametroID_FK
		WHERE det.ObjCompCotID = '$ObjCompCotID' and jobpar.Activo = 1
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return $this->ExecuteReader($query);
	}

	function obtenerParametrosCotizacionTemp($ObjCompCotID){
		$query = "SELECT jobpardet.TempObjCompCotID_FK, jobpardet.JncObjCompParID_FK,
		jobpardet.Valor, jobpar.NameOverride, par.Parametro, par.UniParametro,
		par.Opciones, par.Query
		FROM temptbl_objcomp as det
		INNER JOIN tempjnc_objcomp_objcomppar as jobpardet ON det.TempObjCompCotID = jobpardet.TempObjCompCotID_FK
		INNER JOIN jnc_objcomp_par as jobpar on jobpar.JncObjCompParID = jobpardet.JncObjCompParID_FK
		INNER JOIN cat_parametro as par on par.ParametroID = jobpar.ParametroID_FK
		WHERE jobpardet.TempObjCompCotID_FK = '$ObjCompCotID' and jobpar.Activo = 1
		and det.Activo = 1 and det.Nuevo = 1
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return $this->ExecuteReader($query);
	}

	function obtenerParametrosCotizacion($ObjCompCotID){
		$query = "SELECT det.ObjCompCotID, jobpardet.JncObjCompParID_FK,
		jobpardet.Valor, jobpar.NameOverride, par.Parametro, par.UniParametro,
		par.Opciones, par.Query
		FROM temptbl_objcomp as det
		INNER JOIN tempjnc_objcomp_objcomppar as jobpardet ON det.TempObjCompCotID = jobpardet.TempObjCompCotID_FK
		INNER JOIN jnc_objcomp_par as jobpar on jobpar.JncObjCompParID = jobpardet.JncObjCompParID_FK
		INNER JOIN cat_parametro as par on par.ParametroID = jobpar.ParametroID_FK
		WHERE det.ObjCompCotID = '$ObjCompCotID' and jobpar.Activo = 1
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return json_encode($this->ExecuteReader($query));
	}

	function obtenerMaterial($MatID){
		$query = "SELECT * FROM cat_mat where MatID = '$MatID'";
		return $this->ExecuteReader($query);
	}

	function obtenerConceptoParametroName($ObjCompCotID,$Parametro){
		$query = "SELECT obpardet.Valor, par.Opciones, obpar.ValorMin, obpar.ValorMax,
		par.Query, par.UniParametro, obpardet.JncObjCompParID_FK
		FROM tempjnc_objcomp_objcomppar as obpardet
		inner join jnc_objcomp_par as obpar on obpar.JncObjCompParID = obpardet.JncObjCompParID_FK
		inner join cat_parametro as par on par.ParametroID = obpar.ParametroID_FK
		where obpardet.TempObjCompCotID_FK = '$ObjCompCotID' and
		coalesce(obpar.NameOverride, par.Parametro) = '$Parametro'
		and obpar.ValorFijo = 0 and obpar.Activo = 1";
		return $this->ExecuteReader($query);
	}

	function actualizaParametro($ObjCompCotID,$JncObjCompParID,$Valor){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "UPDATE tempjnc_objcomp_objcomppar as tempobjpar
		inner join temptbl_objcomp as tempdet on
		tempdet.TempObjCompCotID = tempobjpar.TempObjCompCotID_FK
		set tempobjpar.Valor = ? where tempdet.TempObjCompCotID = ?
		and tempobjpar.JncObjCompParID_FK = ?";
		$mysql = new MySqlConnection();
		$mysql->ExecuteQuery($query, array($Valor,$ObjCompCotID,$JncObjCompParID));
	}

	function obtenerObjetoParametro($JncObjCompParID){
		$query = "SELECT objpar.ParametroID_FK, coalesce(objpar.NameOverride, par.Parametro) as NameOverride
		FROM jnc_objcomp_par as objpar
		INNER JOIN cat_parametro as par on par.ParametroID = objpar.ParametroID_FK
		where objpar.JncObjCompParID = '$JncObjCompParID' and objpar.ValorFijo = 0
		and objpar.ValorPred is null";
		$mysql = new MySqlConnection();
		return $mysql->ExecuteReader($query);
	}

	function obtenerValorParTemporal($ParametroID,$NameOverride){
		$ClienteID = $_COOKIE["ClienteID"];
		$query = "SELECT Valor from temp_parcot where ParametroID = '$ParametroID'
		and NameOverride = '$NameOverride' and ClienteID_FK = '$ClienteID'";
		$mysql = new MySqlConnection();
		$consulta = $mysql->ExecuteReader($query);
		return sizeof($consulta) == 0 ? null : $consulta[0]["Valor"];
	}

	function verDetalleObjeto($ObjCompCotID){
		$query = "SELECT ctarea.AreaObj as Area, ctobj.ObjComp as Mueble,
		tdet.Referencia, tdet.Cantidad, tdet.ObjCompCotID
		FROM tbl_objcompcot as tdet
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.ObjCompCotID = '$ObjCompCotID'";
		return json_encode($this->ExecuteReader($query));
	}

	function verDetalleObjetoTemp($ObjCompCotID){
		$query = "SELECT tdet.ObjCompID_FK,ctobj.AreaObjID_FK,
		tdet.Referencia, tdet.Cantidad, tdet.ObjCompCotID,
		ctarea.AreaObj as Area, ctobj.ObjComp as Mueble
		FROM temptbl_objcomp as tdet
		inner join cat_objcomp as ctobj on ctobj.ObjCompID = tdet.ObjCompID_FK
		inner join cat_areaobj as ctarea on ctarea.AreaObjID = ctobj.AreaObjID_FK
		where tdet.TempObjCompCotID = '$ObjCompCotID'";
		return json_encode($this->ExecuteReader($query));
	}

	function verParametrosObjeto($ObjCompCotID){
		$query = "SELECT coalesce(obj.NameOverride, par.Parametro) as Parametro, par.Query, par.Opciones,
		if(par.Query is not null, (select m.Material from cat_mat as m where m.MatID = objpar.Valor limit 1), null) as ValorQuery, objpar.Valor
			FROM jnc_objcompcot_objcomppar as objpar
		inner join jnc_objcomp_par as obj on obj.JncObjCompParID = objpar.JncObjCompParID_FK
		inner join cat_parametro as par on par.ParametroID = obj.ParametroID_FK
		where objpar.ObjCompCotID_FK = '$ObjCompCotID';";
		return json_encode($this->ExecuteReader($query));
	}

	function verParametrosObjetoTemp($ObjCompCotID){
		$query = "SELECT coalesce(obj.NameOverride, par.Parametro) as Parametro,
		par.Query, par.Opciones, objpar.Valor, objpar.JncObjCompParID_FK,
		if(par.Query is not null, (select m.Material from cat_mat as m where m.MatID = objpar.Valor limit 1), null) as ValorQuery
			FROM tempjnc_objcomp_objcomppar as objpar
		inner join jnc_objcomp_par as obj on obj.JncObjCompParID = objpar.JncObjCompParID_FK
		inner join cat_parametro as par on par.ParametroID = obj.ParametroID_FK
		where objpar.TempObjCompCotID_FK = '$ObjCompCotID'
		order by coalesce(par.OrdenEtiquetas, 999999999)";
		return json_encode($this->ExecuteReader($query));
	}

	function ValorParObjTemp($ObjCompCotID,$JncObjCompParID){
		$query = "SELECT a.Valor FROM tempjnc_objcomp_objcomppar as a
		where a.JncObjCompParID_FK = '$JncObjCompParID' and a.TempObjCompCotID_FK = '$ObjCompCotID'";
		$result = $this->ExecuteReader($query);		
		if (!empty($result)) {
			return $result[0]["Valor"];
		} else {
			// Manejar el caso en que no se encuentren resultados, tal vez devolver un valor predeterminado o lanzar una excepción
			return 0; // O algún otro valor predeterminado
		}
	}

	function insertarBitacora($parametros) {
		$parametros = json_decode($parametros, true);
	
		if (json_last_error() !== JSON_ERROR_NONE) {
			return json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
		}
	
		$fechaActual = date('Y-m-d');
		$ClienteID = isset($_COOKIE["ClienteID"]) ? $_COOKIE["ClienteID"] : '';
	
		if (empty($ClienteID)) {
			return json_encode(['status' => 'error', 'message' => 'ClienteID cookie missing']);
		}
	
		$query = "INSERT INTO bitacora (Objeto, Referencia, Parametro, Valor, Mueble, Fecha, Usuario, Estatus)
				  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
	
		$mysql = new MySqlConnection();
	
		$successCount = 0;
		$errorCount = 0;
		$errorMessages = [];
	
		foreach ($parametros as $parametro) {
			// Verifica que todos los campos requeridos estén presentes
			$nombre = isset($parametro['Nombre']) ? $parametro['Nombre'] : '';
			$objCompID = isset($parametro['ObjCompID']) ? $parametro['ObjCompID'] : 'Sin Referencia';
			$parametroVal = isset($parametro['Parametro']) ? $parametro['Parametro'] : 0;
			$valor = isset($parametro['Valor']) ? $parametro['Valor'] : 'Sin valor';
			$usuario = isset($_COOKIE["Usuario"]) ? $_COOKIE["Usuario"] : '';
	
			// Verifica que todos los campos obligatorios no estén vacíos
			if (empty($nombre)) {
				$errorCount++;
				$errorMessages[] = "Missing required fields for record with Nombre: $nombre";
				continue;
			}
			if (empty($objCompID)) {
				$errorCount++;
				$errorMessages[] = "Missing required fields for record with objCompID: $objCompID";
				continue;
			}
			if ($parametroVal<0) {
				$errorCount++;
				$errorMessages[] = "Missing required fields for record with parametroVal: $parametroVal";
				continue;
			}
			if (empty($valor)) {
				$errorCount++;
				$errorMessages[] = "Missing required fields for record with Valor: $Valor";
				continue;
			}
	
			try {
				$result = $mysql->ExecuteQueryB($query, array(
					$nombre,
					$objCompID,
					$parametroVal,
					$valor,
					$nombre,
					$fechaActual,
					$ClienteID,
					1 // Estatus
				));
	
				if ($result === "ok") {
					$successCount++;
				} else {
					$errorCount++;
					$errorMessages[] = "Failed to insert record with Nombre: $nombre, Error: $result";
				}
			} catch (Exception $e) {
				$errorCount++;
				$errorMessages[] = "Exception for record with Nombre: $nombre, Error: " . $e->getMessage();
			}
		}
	
		return json_encode([
			'status' => 'success',
			'message' => "$successCount records inserted successfully, $errorCount errors",
			'errors' => $errorMessages
		]);
	}
	
	function traerBitacora($fecha_ini, $fecha_fin, $status) {
		$query = "SELECT b.*, cl.Nombre1 as nombre, cl.Apellido1 as apellido 
				  FROM bitacora as b, cat_clientemuebles as cl
				  WHERE Fecha BETWEEN '$fecha_ini' AND '$fecha_fin' AND Estatus=$status AND b.usuario=cl.ClienteID";
		return json_encode($this->ExecuteReader($query));
	}

	function verificarCupon($password) {
		$query = "SELECT cp.*, cot.CuponID_FK 
				  FROM cat_proy as cp, tbl_cotizacion as cot
				  WHERE cp.Password='$password' AND cp.Activo=1 ";
		return json_encode($this->ExecuteReader($query));
	}

	function bitacoraCorregir($id_bitacora){
		$query = "UPDATE bitacora set Estatus = 0 where id = ?";
		$this->ExecuteQuery($query, array($id_bitacora));
	}
}
?>