<?php
session_start();
date_default_timezone_set('America/Guayaquil');
require '../Conexion/class.sql.inc.php';
require_once('../General/mail/class.phpmailer.php');
$db = new EyeMySQLAdap();
/////para enviar los email

function sendMail($to,$toName,$Message,$now,$responsibleID){
	$mail             = new PHPMailer();
	$source			  = "pchavezch@gmail.com";
	$body             = $Message . "<br><br>ACCEDA AL SISTEMA PARA VER LOS DETALLES!";

	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->Host       = "smtp.gmail.com"; // SMTP server
	$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
	// 1 = errors and messages
	// 2 = messages only
	$mail->SMTPAuth   = true;                  // enable SMTP authentication
	$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
	$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
	$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
	$mail->Username   = $source;  // GMAIL username
	$mail->Password   = "igual1queayer";            // GMAIL password

	$mail->SetFrom($source, "Administrador Hidricos");

	$mail->AddReplyTo($source,"Admin Sistema");

	$mail->Subject    = "Boletin de Alarmas de Mantenimiento Fecha: " .  $now;
	
	$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
	$mail->body 	  = $body;
	$mail->MsgHTML($body);

	$address = $to;
	$mail->AddAddress($address, $toName);


	if(!$mail->Send()) {
		echo "Mailer Error: " . $mail->ErrorInfo;
	} else {
		echo "Message sent!";
	}
}

function sendMails($respName,$respEmail,$partsToMessage,$parts,$dateInit,$responsibleID,$sigMan,$db){
	//$currentMail = $respEmail[0];
	$message="<b>El sistema de mantenimiento le informa los próximos Mantenimientos:</b><br>";
	$counter = 0;
	//for($i=0;$i<count($respEmail);$i++){		
		//if($respEmail[$i]==$currentMail){
			///message
			//$tmpMessage = "ID: ". $partsToMessage[$i]. "-" .$parts[$i] ." <b>     Fecha Siguiente Mant: </b>" . $dateEnd[$i] ."";;
			$tmpMessage = "ID: ". $partsToMessage. "-" . $parts ." <b> Siguiente Mantenimiento: </b> " . $sigMan ." Hrs";
			$sql1 = "INSERT INTO message(Description,UserId,CreateDate,Type,Criticity,Status) Values('" . mysql_real_escape_string($tmpMessage)."'," . $responsibleID . ", now(),1,2,1 )"  ;
			$result=$db->query($sql1);

			///sendmail
			//$message = $message . (($counter++) +1). ".- ID: ". $partsToMessage[$i]. "-" .$parts[$i] ." <b>     Fecha Siguiente Mant: </b>" . $dateEnd[$i] ."<br>";
	$message = $message . ".- ID: ". $partsToMessage. "-" .$parts ." <b>Siguiente Mantenimiento: </b>". $sigMan ." Hrs<br>";
		//}
		//if(($i+1) == count($respEmail) || $respEmail[$i+1] !=$currentMail ){
			sendMail($respEmail,$respName,$message,$dateInit,$responsibleID);
			//sendMail($respEmail[$i],$respName[$i],$message,$dateInit[$i],$createUser[$i]);
			//$currentMail=$respEmail[$i];
			//$counter=0;
			//$message="<b>El sistema de mantenimiento le informa los próximos Mantenimientos:</b><br>";
		//}
	//}
}

//////

function createMantProg($idPart,$dateInitMessage,$descriptionMant,$responsable,$emailRes,$idresponsable,$nextMant, $db){
	///Verificar si existe mantenimiento para el $idPart en el periodo, si no existe lo crea, si existe no hace nada
	$strSQL ="SELECT * from maintenance WHERE PartID=" . $idPart . " AND HourInitMessage<= '" . $dateInitMessage ."' AND HourEndMessage >='" . $dateInitMessage ."' AND StatusMaintenanceID = 1";
	//echo "<br>" . $strSQL;
	$resultTemp=$db->query($strSQL);
	$objTemp =mysql_fetch_object($resultTemp);
	if($objTemp ==null){
		$sqlInsert = "INSERT INTO maintenance(PartID,StatusMaintenanceID,TypeMaintenanceID,Description,InitDate,CreateUserID,CreateDate,UpdateUserId,UpdateDate,HourInitMessage,HourEndMessage)" .
			" values(".$idPart.",1,2,'MANTENIMIENTO PROGRAMADO:" .  $descriptionMant . "',NOW(),1,NOW(),1,NOW()," . $dateInitMessage . "," . $dateInitMessage .")" ;	
		//echo "<br>".$sqlInsert ;
		$resultInsert = $db->query($sqlInsert);
		sendMails($responsable,$emailRes,$idPart,$descriptionMant,$dateInitMessage,$idresponsable,$nextMant,$db);
	}
	else{
		sendMails($responsable,$emailRes,$idPart,$descriptionMant,$dateInitMessage,$idresponsable,$nextMant,$db);	
	}
}


try{
	
	$Opcion				= $_POST['Opcion'];
	$userid  			= $_SESSION['UserID'];
	
	$lastCode=-1;
	$Mensaje="";
	switch ($Opcion) 
	{		
		case "GRABAR":{			
				$EstacionID = $_POST['EstacionID'];
				$Estacion = mysql_real_escape_string($_POST['Estacion']);
				$Ubicacion = mysql_real_escape_string($_POST['Ubicacion']);
				$Descripcion = mysql_real_escape_string($_POST['Descripcion']);
				$Responsable = ($_POST['Responsable']!=''?$_POST['Responsable']:0);
				$Longitud = ($_POST['Longitud']!=''?$_POST['Longitud']:0);
				$Latitud = ($_POST['Latitud']!=''?$_POST['Latitud']:0);
				$Zona = ($_POST['Zona']!=''?$_POST['Zona']:0);
				if($EstacionID=='-1'){
					$array = array("Station"=>"'$Estacion'",
						"Location"=>"'$Ubicacion'",
						"Description"=>"'$Descripcion'",
						"ResponsibleID"=>$Responsable,
						"Latitude"=>"$Latitud",
						"Longitude"=>"$Longitud",
						"Zone"=>$Zona,
						"CreateUserID"=>$userid,
						"CreateDate"=>"NOW()",
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->insert($array,"structure");
					$lastCode= mysql_insert_id();
					
					for($i=1;$i<4;$i++){
						$array1 = array("StructureID"=>$lastCode,
							"ReadingTypeID"=>$i,
							"AmountData"=>0,
							"CreateUserID"=>$userid,
							"CreateDate"=>"NOW()",
							"UpdateUserID"=>$userid,
							"UpdateDate"=>"NOW()");
						$result1=$db->insert($array1,"readingstructure");
						}					
				}
				else{
					$array = array("Station"=>"'$Estacion'",
						"Location"=>"'$Ubicacion'",
						"Description"=>"'$Descripcion'",
						"ResponsibleID"=>$Responsable,
						"Latitude"=>"$Latitud",
						"Longitude"=>"$Longitud",
						"Zone"=>$Zona,						
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->update($array,"structure","StructureID = " . $EstacionID);
					}				
			}
			break;
		case 'GRABARC':{
				$ComponenteID = $_POST['ComponenteID'];
				$EstacionID = $_POST['EstacionID'];				
				$Descripcion = mysql_real_escape_string($_POST['Descripcion']);	
				
				if($ComponenteID == '-1'){
					$array = array("StructureID"=>$EstacionID,						
						"Description"=>"'$Descripcion'",						
						"CreateUserID"=>$userid,
						"CreateDate"=>"NOW()",
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->insert($array,"component");
					$lastCode= mysql_insert_id();
					}
				else{
					$array = array("Description"=>"'$Descripcion'",											
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->update($array,"component","ComponentID = " . $ComponenteID);
					}
			}
			break;
		case 'GRABARP':{
				$ParteID = $_POST['ParteID'];
				$ComponenteID = $_POST['ComponenteID'];
				$TipoParte = $_POST['TipoParteID'];
				$ValorHorometroI = ($_POST['ValorHorometroI']!=''?$_POST['ValorHorometroI']:0);
				$HorasMantenimiento = ($_POST['HorasMantenimiento']!=''?$_POST['HorasMantenimiento']:0);
				$FrecuenciaID = ($_POST['FrecuenciaID']!=''?$_POST['FrecuenciaID']:0);
				$Descripcion = mysql_real_escape_string($_POST['Descripcion']);
				$UltimoMantenimiento = ($_POST['UltimoMantenimiento']!=''?$_POST['UltimoMantenimiento']:'1900-01-01');
				$SiguienteMantenimiento = ($_POST['SiguienteMantenimiento']!=''?$_POST['SiguienteMantenimiento']:'1900-01-01');
				$Aviso = ($_POST['Aviso']!=''?$_POST['Aviso']:0);
				$FrecuenciaAviso =  ($_POST['FrecuenciaAviso']!=''?$_POST['FrecuenciaAviso']:0);
				$Programacion = $_POST['Programacion'];
				if($ParteID == '-1'){
					if($FrecuenciaID == 0){
						$varFecha = $SiguienteMantenimiento;
						}
					else{
						$sqlF = "select TotalDays from period where PeriodID = " . $FrecuenciaID;
						$resultF = $db->query($sqlF);
						$objF = mysql_fetch_object($resultF);
						$varFecha = date("Y-m-d", strtotime("$UltimoMantenimiento + $objF->TotalDays day"));
						}
					
					$array = array("ComponentID"=>$ComponenteID,
						"PartTypeID"=>$TipoParte,
						"HorometroValueInit"=>"$ValorHorometroI",
						"HoursMaintenance"=>"$HorasMantenimiento",
						"FrequencyID"=>$FrecuenciaID,
						"Description"=>"'$Descripcion'",
						"LastMaintenance"=>"'$UltimoMantenimiento'",
						"NextMaintenance"=>"'$varFecha'",
						//"NextMaintenance"=>"'$SiguienteMantenimiento'",
						"Notice"=>$Aviso,
						"FrequencyNotice"=>$FrecuenciaAviso,
						"Programming"=>($Programacion=="false"?0:1),
						"CreateUserID"=>$userid,
						"CreateDate"=>"NOW()",
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->insert($array,"part");
					$lastCode= mysql_insert_id();
				}
				else{
					$array = array("PartTypeID"=>$TipoParte,
						"HorometroValueInit"=>"$ValorHorometroI",
						"HoursMaintenance"=>"$HorasMantenimiento",
						"FrequencyID"=>$FrecuenciaID,						
						"Description"=>"'$Descripcion'",
						"LastMaintenance"=>"'$UltimoMantenimiento'",
						"NextMaintenance"=>"'$SiguienteMantenimiento'",
						"Notice"=>$Aviso,
						"FrequencyNotice"=>$FrecuenciaAviso,
						"Programming"=>($Programacion=="false"?0:1),						
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->update($array,"part","PartID = " . $ParteID);
				}
			}
			break;
		case "GRABARM":{			
				$MantenimientoID = $_POST['MantenimientoID'];
				$ParteID = $_POST['Parte'];
				$Descripcion = mysql_real_escape_string($_POST['Descripcion']);
				$Estado = ($_POST['Estado']!=''?$_POST['Estado']:0);
				$Tipo = ($_POST['Tipo']!=''?$_POST['Tipo']:0);
				$FechaInicio = ($_POST['FechaInicio']!=''?$_POST['FechaInicio']:'1900-01-01');
				$FechaFin = ($_POST['FechaFin']!=''?$_POST['FechaFin']:'1900-01-01');
				$Comentario = mysql_real_escape_string($_POST['Comentario']);
				$Resultado = mysql_real_escape_string($_POST['Resultado']);
				$InspeccionID = ($_POST['InspeccionID']!=''?$_POST['InspeccionID']:0);
				$CostoCivil = ($_POST['CostoCivil']!=''?$_POST['CostoCivil']:0); 
				$CostoMecanico = ($_POST['CostoMecanico']!=''?$_POST['CostoMecanico']:0); 
				$CostoElectrico = ($_POST['CostoElectrico']!=''?$_POST['CostoElectrico']:0); 
				$CostoGasolina = ($_POST['CostoGasolina']!=''?$_POST['CostoGasolina']:0);
				$CostoInsumos = ($_POST['CostoInsumos']!=''?$_POST['CostoInsumos']:0); 
				$OtrosCostos = ($_POST['OtrosCostos']!=''?$_POST['OtrosCostos']:0); 
				$CostoTotal = ($_POST['CostoTotal']!=''?$_POST['CostoTotal']:0); 
				if($MantenimientoID=='-1'){
					$array = array("PartID"=>$ParteID,
						"Description"=>"'$Descripcion'",
						"StatusMaintenanceID"=>$Estado,
						"TypeMaintenanceID"=>$Tipo,
						"InitDate"=>"'$FechaInicio'",
						"EndDate"=>"'$FechaFin'",
						"Comment"=>"'$Comentario'",
						"Result"=>"'$Resultado'",
						"InspectionID"=>$InspeccionID,
						"CivilCost"=>"$CostoCivil",
						"MechanicalCost"=>"$CostoMecanico",
						"ElectricalCost"=>"$CostoElectrico",
						"GasolineCost"=>"$CostoGasolina",
						"InputsCost"=>"$CostoInsumos",
						"OtherCost"=>"$OtrosCostos",
						"TotalCost"=>"$CostoTotal",			
						"CreateUserID"=>$userid,
						"CreateDate"=>"NOW()",
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->insert($array,"maintenance");
					$lastCode= mysql_insert_id();
				}
				else{
					$SQLTemp = "select m.StatusMaintenanceID, m.PartID, m.TypeMaintenanceID, p.PartTypeID, p.FrequencyID, p.Programming, m.DateInitMessage, m.DateEndMessage, m.HourInitMessage, m.HourEndMessage from maintenance m, part p where p.PartID = m.PartID AND m.MaintenanceID = " . $MantenimientoID;
					$resultmp=$db->query($SQLTemp);
					$objTemp = mysql_fetch_object($resultmp);
					if ($objTemp->StatusMaintenanceID == 1 && $Estado == 2 && $objTemp->TypeMaintenanceID == 2){
						if($objTemp->PartTypeID != 1){
							$sqlF = "select TotalDays from period where PeriodID = " . $objTemp->FrequencyID;
							$resultF = $db->query($sqlF);
							$objF = mysql_fetch_object($resultF);
							$newLastMan = $objTemp->DateEndMessage;
							$newNextMan = date('Y-m-d', strtotime($objTemp->DateEndMessage . " + $objF->TotalDays day"));
							$arrayP = array("LastMaintenance"=>"'$newLastMan'",
								"NextMaintenance"=>"'$newNextMan'");
							$resultP=$db->update($arrayP,"part","PartID = " . $objTemp->PartID);
						}
						else{
							$sqlTV = "select max(vp.Value)ValorInicial from valuepart vp, part p where vp.PartID = p.PartID AND p.PartID = " . $objTemp->PartID;
							$resulTV = $db->query($sqlTV);
							$objTV = mysql_fetch_object($resulTV);
							$arrayP = array("HorometroValueInit"=>$objTV->ValorInicial);
							$resultP=$db->update($arrayP,"part","PartID = " . $objTemp->PartID);
						}
					}elseif($objTemp->StatusMaintenanceID == 1 && $Estado == 2 && $objTemp->TypeMaintenanceID == 1){
						if($objTemp->Programming == 1){
							if($objTemp->PartTypeID != 1){
								$sqlF = "select TotalDays from period where PeriodID = " . $objTemp->FrequencyID;
								$resultF = $db->query($sqlF);
								$objF = mysql_fetch_object($resultF);
								$varFecha = date("Y-m-d", strtotime(date("Y-m-d") . " + $objF->TotalDays day"));
								$arrayP = array("LastMaintenance"=>"NOW()",
									"NextMaintenance"=>"'$varFecha'");
								$resultP=$db->update($arrayP,"part","PartID = " . $objTemp->PartID);
							}
							else{
								$sqlTV = "select max(vp.Value)ValorInicial from valuepart vp, part p where vp.PartID = p.PartID AND p.PartID = " . $objTemp->PartID;
								$resulTV = $db->query($sqlTV);
								$objTV = mysql_fetch_object($resulTV);
								$arrayP = array("HorometroValueInit"=>$objTV->ValorInicial);
								$resultP=$db->update($arrayP,"part","PartID = " . $objTemp->PartID);
							}
						}
					}
					$array = array("Description"=>"'$Descripcion'",
						"StatusMaintenanceID"=>$Estado,
						"TypeMaintenanceID"=>$Tipo,
						"InitDate"=>"'$FechaInicio'",
						"EndDate"=>"'$FechaFin'",
						"Comment"=>"'$Comentario'",
						"Result"=>"'$Resultado'",
						"InspectionID"=>$InspeccionID,
						"CivilCost"=>"$CostoCivil",
						"MechanicalCost"=>"$CostoMecanico",
						"ElectricalCost"=>"$CostoElectrico",
						"GasolineCost"=>"$CostoGasolina",
						"InputsCost"=>"$CostoInsumos",
						"OtherCost"=>"$OtrosCostos",
						"TotalCost"=>"$CostoTotal",						
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->update($array,"maintenance","MaintenanceID = " . $MantenimientoID);
				}
				
			}
			break;
		case 'GRABARRECURSO':{				
				$EstacionID = $_POST['EstacionID'];
				$Recurso = $_POST['Recurso'];
				$Cargo = ($_POST['Cargo']!=''?$_POST['Cargo']:0);
				$Estado = $_POST['Estado'];				
				
				$array = array("StructureID"=>$EstacionID,
					"Nombre"=>"'$Recurso'",
					"ChargeID"=>$Cargo,
					"Status"=>($Estado=="false"?0:1),
					"CreateUserID"=>$userid,						
					"CreateDate"=>"NOW()",
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->insert($array,"resource");
				$lastCode= mysql_insert_id();
			}
			break;
		case "GRABARINCIDENCIA":{
				$IncidenciaID = $_POST['IncidenciaID'];			
				$EstacionID = $_POST['EstacionID'];
				$Descripcion = mysql_real_escape_string($_POST['Descripcion']);
				$Reportado = $_POST['Reportado'];
				$Fecha = ($_POST['Fecha']!=''?$_POST['Fecha']:'1900-01-01');
				$Detalle = mysql_real_escape_string($_POST['Detalle']);
				$Solucion = mysql_real_escape_string($_POST['Solucion']);
				$Estado = ($_POST['Estado']!=''?$_POST['Estado']:0);			
				if($IncidenciaID=='-1'){
					$array = array("StructureID"=>$EstacionID,						
						"Description"=>"'$Descripcion'",
						"Reported"=>"'$Reportado'",
						"Date"=>"'$Fecha'",
						"Detail"=>"'$Detalle'",
						"Solution"=>"'$Solucion'",
						"StatusID"=>$Estado,
						"CreateUserID"=>$userid,
						"CreateDate"=>"NOW()",
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->insert($array,"incidence");
					$lastCode= mysql_insert_id();
				}
				else{
					$array = array("StructureID"=>$EstacionID,						
						"Description"=>"'$Descripcion'",
						"Reported"=>"'$Reportado'",
						"Date"=>"'$Fecha'",
						"Detail"=>"'$Detalle'",
						"Solution"=>"'$Solucion'",
						"StatusID"=>$Estado,			
						"UpdateUserID"=>$userid,
						"UpdateDate"=>"NOW()");
					$result=$db->update($array,"incidence","IncidenceID = " . $IncidenciaID);
				}				
			}
			break;
		case 'DELETERESOURCE':{
			$ResourceID = $_POST['ResourceID'];
				$result = $db->delete('resource',"ResourceID = " . $ResourceID);
			}
			break;
		case 'EDITRECURSO':{
				$ResourceID = $_POST['ResourceID'];
				$Nombre = mysql_real_escape_string($_POST['Nombre']);
				$CargoID = ($_POST['CargoID']!='' || $_POST['CargoID']!='-1' ? $_POST['CargoID']:0);
				$Estado = $_POST['Estado'];
				$array = array("Nombre"=>"'$Nombre'",
					"ChargeID"=>$CargoID,
					"Status"=>($Estado=="false"?0:1),					
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->update($array,"resource","ResourceID = " . $ResourceID);
			}
			break;
		case 'AGREGARPERSONAL':{
				$ResourceID = $_POST['RecursoID'];
				$MaintenanceID = $_POST['MantenimientoID'];
				$array = array("ResourceID"=>$ResourceID,
					"MaintenanceID"=>$MaintenanceID,					
					"CreateUserID"=>$userid,						
					"CreateDate"=>"NOW()",
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->insert($array,"maintenanceresource");
				$lastCode= mysql_insert_id();
			}
			break;
		case 'ELIMINARPERSONAL':{
				$MaintenanceResourceID = $_POST['MantenimientoRecursoID'];
				$result = $db->delete('maintenanceresource',"MaintenanceResourceID = " . $MaintenanceResourceID);
			}
			break;
		case 'EDITTIPOLECTURA':{
				$TipoLecturaID = $_POST['TipoLecturaID'];
				$Cantidad = ($_POST['Cantidad']!=''?$_POST['Cantidad']:0);				
				$array = array("AmountData"=>$Cantidad,									
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->update($array,"readingstructure","ReadingStructureID = " . $TipoLecturaID);
			}
			break;
		case'GRABARTOMAVALORES':{
				$EstacionID = $_POST['EstacionID'];
				$TipoLecturaID = $_POST['TipoLecturaID'];
				//$ParteID = $_POST['ParteID'];
				$Fecha = $_POST['Fecha'];
				//$sql1 = "select ValuesTakeID, StructureID, ReadingTypeID from valuestake WHERE StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID . " AND Date > '" . $Fecha . "' AND Date <= '" . $Fecha ."'";
				$sql1 = "select ValuesTakeID, StructureID, ReadingTypeID from valuestake WHERE StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID . " AND Date = '" . $Fecha . "'";
				$result1 = $db->query($sql1);
				$rows=$db->countRows($result1);
				if($rows>0){
					$obj1 = mysql_fetch_object($result1);					
					$delete2 = "DELETE FROM valuesamount WHERE ValuesTakeID = " . $obj1->ValuesTakeID;
					$resultD2=$db->query($delete2);
					///////saber la cantidad de registros a ingresar
					$sqlamount = "select AmountData from readingstructure where StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID;
					$resultamount = $db->query($sqlamount);
					$objamount = mysql_fetch_object($resultamount);
					if($objamount->AmountData > 0){
						for($i=1;$i<=$objamount->AmountData;$i++){
							$array = array("StructureID"=>$EstacionID,
								"ValuesTakeID"=>$obj1->ValuesTakeID,
								"ReadingTypeID"=>$TipoLecturaID,			
								"Value"=>0,
								"CreateUserID"=>$userid,						
								"CreateDate"=>"NOW()",
								"UpdateUserID"=>$userid,
								"UpdateDate"=>"NOW()");
							$result=$db->insert($array,"valuesamount");
						}
					}else{
						Echo '({success:true,Datos:'.json_encode("NOK").',LastCode:' .$lastCode . ',Mensaje:"' . $Mensaje .'" })';
						exit();
						}
					$lastCode = $obj1->ValuesTakeID;
					}
				else{
					$sqlamount = "select AmountData from readingstructure where StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID;
					$resultamount = $db->query($sqlamount);
					$objamount = mysql_fetch_object($resultamount);
					if($objamount->AmountData > 0){
						$array = array("StructureID"=>$EstacionID,
							"ReadingTypeID"=>$TipoLecturaID,
							"Date"=>"'$Fecha'",				
							"CreateUserID"=>$userid,						
							"CreateDate"=>"NOW()",
							"UpdateUserID"=>$userid,
							"UpdateDate"=>"NOW()");
						$result=$db->insert($array,"valuestake");
						$lastCode= mysql_insert_id();
						for($i=1;$i<=$objamount->AmountData;$i++){
							$array2 = array("StructureID"=>$EstacionID,
								"ValuesTakeID"=>$lastCode,
								"ReadingTypeID"=>$TipoLecturaID,
								"Value"=>0,
								"CreateUserID"=>$userid,						
								"CreateDate"=>"NOW()",
								"UpdateUserID"=>$userid,
								"UpdateDate"=>"NOW()");
							$result4=$db->insert($array2,"valuesamount");
						}
					}
					else{
						Echo '({success:true,Datos:'.json_encode("NOK").',LastCode:' .$lastCode . ',Mensaje:"' . $Mensaje .'" })';
						exit();
						}
				}
			}
			break;
		case'CONSULTARVALORES':{
				$EstacionID = $_POST['EstacionID'];
				$TipoLecturaID = $_POST['TipoLecturaID'];
				//$ParteID = $_POST['ParteID'];
				$Fecha = $_POST['Fecha'];
				//$sql = "select ValuesTakeID from valuestake WHERE StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID . " AND Date > '" . $Fecha . "' AND Date <= '" . $Fecha ."'";
				$sql = "select ValuesTakeID from valuestake WHERE StructureID = " . $EstacionID . " AND ReadingTypeID = " . $TipoLecturaID . " AND Date = '" . $Fecha . "'";
				$result = $db->query($sql);
				$rows=$db->countRows($result);
				if($rows>0){
					Echo '({success:true,Datos:'.json_encode("NOK").',LastCode:' . $lastCode . ',Mensaje:"' . $Mensaje .'"})';
					exit();
					}
				else{
					Echo '({success:true,Datos:'.json_encode("OK").',LastCode:' .$lastCode . ',Mensaje:"' . $Mensaje .'" })';
					exit();
					}
			}
			break;
		case'EDITTOMAVALORES':{
				$ID = $_POST['ID'];
				$Value = ($_POST['Value']!=''?$_POST['Value']:0);
				$array = array("Value"=>"$Value",									
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->update($array,"valuesamount","ValuesAmountID = " . $ID);
			}
			break;
		case'GRABARTOMAVALORESPARTE':{
				$ParteID = $_POST['ParteID'];
				$Valor = ($_POST['Valor']!=''?$_POST['Valor']:0);
				$Fecha = ($_POST['Fecha']!=''?$_POST['Fecha']:'1900-01-01');
				$array = array("PartID"=>$ParteID,
					"Value"=>"$Valor",
					"Date"=>"'$Fecha'",				
					"CreateUserID"=>$userid,						
					"CreateDate"=>"NOW()",
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->insert($array,"valuepart");
				$lastCode= mysql_insert_id();
				
				$SQLTemp = "select p.PartID, s.Description Estructura, c.Description Componente, concat_ws('->',s.Station,c.Description, p.Description) Parte,  p.Notice, p.FrequencyNotice, p.HorometroValueInit, p.HoursMaintenance, (p.HorometroValueInit + p.HoursMaintenance - p.Notice)Alarm, (p.HorometroValueInit + p.HoursMaintenance)nextMant, vp.Value, concat_ws(' ',u.Name,u.FirstLastName,u.SecondLastName) RespName, u.Email RespEmail, s.ResponsibleID
							from part p, component c, structure s, valuepart vp, user u
							where u.UserID = s.ResponsibleID AND c.ComponentID=p.ComponentID AND s.StructureID=c.StructureID AND p.PartID = vp.PartID AND vp.Value > (p.HorometroValueInit + p.HoursMaintenance - p.Notice) AND p.PartID = " . $ParteID;
							
				$resultTemp=$db->query($SQLTemp);
				$objTemp =mysql_fetch_object($resultTemp);
				//$partsToMessage = array();
				//$HourInit = array();
				//$HourEnd = array();
				if($objTemp != null){					
					$respName	= $objTemp->RespName;
					$respEmail = $objTemp->RespEmail;
					$partsToMessage = $objTemp->PartID;
					$partes =$objTemp->Parte;
					$responsibleID = $objTemp->ResponsibleID;
					$dateInit=$objTemp->Alarm;
					$nextMant = $objTemp->nextMant;
					//$dateEnd[]=$objTemp->NextMaintenance;
					//createMantProg($objTemp->PartID, $objTemp->Alarm, $objTemp->Parte, $db);
					createMantProg($partsToMessage, $dateInit, $partes,$respName,$respEmail,$responsibleID,$nextMant, $db);
					}
				
			}
			break;
		case'EDITTOMAVALORESPARTE':{
				$ID = $_POST['ID'];
				$Value = ($_POST['Value']!=''?$_POST['Value']:0);
				$array = array("Value"=>"$Value",									
					"UpdateUserID"=>$userid,
					"UpdateDate"=>"NOW()");
				$result=$db->update($array,"valuepart","ValuePartID = " . $ID);
			}
			break;
		case'DELETEVALORPARTE':{
				$ValuePartID = $_POST['ValuePartID'];
				$result = $db->delete('valuepart',"ValuePartID = " . $ValuePartID);
			}
			break;
		case'MODIFICARFECHAMAN':{				
				$ParteID = $_POST['PartID'];
				$FrecuenciaID = $_POST['FrecuenciaID'];
				$sqlF = "select TotalDays from period where PeriodID = " . $FrecuenciaID;
				$resultF = $db->query($sqlF);
				$objF = mysql_fetch_object($resultF);				
				$varFecha = date("Y-m-d", strtotime(date("Y-m-d") . " + $objF->TotalDays day"));
				$array = array("LastMaintenance"=>"NOW()",
					"NextMaintenance"=>"'$varFecha'");
				$result=$db->update($array,"part","PartID = " . $ParteID);
			}
			break;
	}
	if($result==false){
		//Echo '({success:true})';
		Echo '({success:false,Datos:'.json_encode("NOK").',LastCode:' .$lastCode . ',Mensaje:"' . $Mensaje .'" })';	
	}
	else{
		//Echo '({success:true})';
		Echo '({success:true,Datos:'.json_encode("OK").',LastCode:' . $lastCode . ',Mensaje:"' . $Mensaje .'"})';	
	}
}
catch(Exception $e)
{
	Echo '({success:false,Datos:'.json_encode($e->getMessage()).'})';		
}
?>

