<?php
	ob_start();
	session_start();
	if (empty($_SESSION['usuarioNome'])) {
		echo "Acesso negado!";
		exit;
	}else{
		include("conexao.php");
	}
	include("valida_datas.php");
?>
<html>
<head>
    <title></title>
    <meta charset="utf-8">

</head>
<body>
<?php
	$acao = $_GET['acao'];
	
	if (!$conn) {
		die("Connection failed: " . mysqli_connect_error());
	}

	switch ($acao) {

		case 'cadastrar':{
			
			$id            = $_SESSION['usuarioId'];
			$tipo          = $_POST['TIPO'];
			$categoria     = $_POST['CATEGORIA'];
			$urgencia      = $_POST['URGENCIA'];
			$observadores  = $_POST['observadores'];
			$titulo        = $_POST['titulo'];
			$descricao     = mysqli_real_escape_string($conn, $_POST['descricao']); 
						
			$data = date('Y-m-d H:i:s');
			$empresa_id = $_SESSION['codCliente'];

			$query = "SELECT entities_id FROM glpi_users WHERE id = {$id}";
			$res = mysqli_query($conn, $query);
			$row = mysqli_fetch_assoc($res);
			$entities_id = $row['entities_id'];	

			$buscaaceitacao = "SELECT * FROM glpi_slas WHERE entities_id = {$entities_id} AND type = 1";
			$slasaceit_res = mysqli_query($conn, $buscaaceitacao);
			$rowaceit = mysqli_fetch_assoc($slasaceit_res); 
			$slas_id_tto = $rowaceit['id']; 
			$tempo = $rowaceit['number_time'];
			$definicao_tempo = $rowaceit['definition_time'];
			$time_to_own = calculaSla($data, $tempo, $definicao_tempo);

			echo $urgencia;
			if($urgencia==5){
					if($entities_id == 1){
						$slas_id_ttr = 4;
						$tempo = 4;
						$definicao_tempo = 'hour';
						$time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
					} elseif ($entities_id == 2){
						$slas_id_ttr = 9;
						$tempo = 1;
						$definicao_tempo = 'hour';
						$time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 3){
                                                $slas_id_ttr = 14;
                                                $tempo = 1;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 4){
                                                $slas_id_ttr = 19;
                                                $tempo = 1;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
					} else {
						$slas_id_ttr = 2;
						$tempo = 30;
						$definicao_tempo = 'day';
						$time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
					} echo 'PRimeiro';
			}elseif($urgencia==4){
                                        if($entities_id == 1){
                                                $slas_id_ttr = 5;
                                                $tempo = 8;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 2){
                                                $slas_id_ttr = 10;
                                                $tempo = 4;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 3){
                                                $slas_id_ttr = 15;
                                                $tempo = 4;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 4){
                                                $slas_id_ttr = 20;
                                                $tempo = 4;
                                                $definicao_tempo = 'hour';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } else {
                                                $slas_id_ttr = 2;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } echo 'Segundo';
                        }elseif($urgencia==3){
                                        if($entities_id == 1){
                                                $slas_id_ttr = 6;
                                                $tempo = 15;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 2){
                                                $slas_id_ttr = 11;
                                                $tempo = 15;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 3){
                                                $slas_id_ttr = 16;
                                                $tempo = 15;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 4){
                                                $slas_id_ttr = 21;
                                                $tempo = 15;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);

				        } else {
                                                $slas_id_ttr = 2;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } echo 'TErceiro';
                        }elseif($urgencia==2){
                                        if($entities_id == 1){
                                                $slas_id_ttr = 7;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 2){
                                                $slas_id_ttr = 12;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 3){
                                                $slas_id_ttr = 17;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 4){
                                                $slas_id_ttr = 22;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } else {
                                                $slas_id_ttr = 2;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } echo 'Quarto';
                        }elseif($urgencia==1){
                                        if($entities_id == 1){
                                                $slas_id_ttr = 7;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 2){
                                                $slas_id_ttr = 12;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 3){
                                                $slas_id_ttr = 17;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } elseif ($entities_id == 4){
                                                $slas_id_ttr = 22;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } else {
                                                $slas_id_ttr = 2;
                                                $tempo = 30;
                                                $definicao_tempo = 'day';
                                                $time_to_resolve = calculaSla($data, $tempo, $definicao_tempo);
                                        } echo 'Quinto';
                        }






			
			$sql = "INSERT INTO glpi_tickets (entities_id, name, date, status, users_id_recipient, requesttypes_id, content, urgency,  itilcategories_id, type, slas_id_ttr, slas_id_tto, time_to_resolve, time_to_own, locations_id, date_creation, empresa_id)";
			$sql .= "VALUES ('{$entities_id}','{$titulo}', '{$data}', 1, '{$id}' , '{$tipo}', '{$descricao}', '{$urgencia}', '{$categoria}', {$tipo}, {$slas_id_ttr},{$slas_id_tto}, '{$time_to_resolve}','{$time_to_own}', 1,'{$data}', '{$empresa_id}')"; 

			if (mysqli_query($conn, $sql)) { 	
					/*echo json_encode($ret, JSON_PRETTY_PRINT);*/
					$insert_id = mysqli_insert_id($conn);
					$sql1  = "INSERT INTO glpi_tickets_users (tickets_id, users_id, type, use_notification, alternative_email)";
					$sql1 .= "VALUES ('{$insert_id}', '{$id}','1','1', '')";
					mysqli_query($conn, $sql1);
					
					
						// Nas versões do PHP que antecedem a versão 4.1.0, é preciso usar o $HTTP_POST_FILES em vez do $_FILES.
	
//					print_r($_FILES);

						foreach ($_FILES["arquivos"]["error"] as $key => $error) {
							$caminho = "../../glpi/files/". $insert_id;
							if 	($error != UPLOAD_ERR_NO_FILE){
								if ($error == UPLOAD_ERR_OK) {									
									mkdir($caminho);
									$tmp_name = $_FILES["arquivos"]["tmp_name"][$key];
									// basename() may prevent filesystem traversal attacks;
									// further validation/sanitation of the filename may be appropriate
									$tipo = $_FILES["arquivos"]["type"][$key];
									$ext = strtolower(end(explode('.', $_FILES["arquivos"]["name"][$key])));							
									$name = basename($_FILES["arquivos"]["name"][$key]);
									$filepath = $insert_id."/".$name;			
									move_uploaded_file($tmp_name, "$caminho/$name");
									//$sqldoc = "INSERT INTO glpi_documents (entities_id, name, filename, filepath, mime, date_mod,  users_id, tickets_id, sha1sum, tag ,date_creation)";
									$sqldoc = "INSERT INTO glpi_documents (entities_id, is_recursive, name, filename, filepath, mime, date_mod,  users_id, tickets_id, date_creation)";
									$sqldoc .= "VALUES ('{$entities_id}','0','Documento: Chamado - {$titulo}', '{$name}', '{$filepath}'  ,'{$tipo}', '{$data}', '{$id}', '{$insert_id}', '{$data}')"; 
									echo $sqldoc;
									if (mysqli_query($conn, $sqldoc)){
										$doc_id = mysqli_insert_id($conn);
										$sqldoc1 = "INSERT INTO glpi_documents_items (documents_id, items_id,itemtype, entities_id, is_recursive, date_mod,  users_id, timeline_position)";
										$sqldoc1 .= "VALUES ('{$doc_id}', '{$insert_id}', 'Ticket', '{$entities_id}'  ,'{$entities_id}', '{$data}', '{$id}', '1')"; 
				
										mysqli_query($conn, $sqldoc1);
									}	
									
								}
							}	
						}												
					?>
					<script language="JavaScript" type="text/javascript"> alert ("Atendimento cadastrado com sucesso.")</script>
					<script language="JavaScript">window.location.href="../atendimentos.php";</script><?php	
			} else {
				echo "Error: " . $sql . "<br>" . mysqli_error($conn);?>
				<script language="JavaScript">window.location.href="../atendimentos.php";</script><?php
			}

		break;	
		}	
		case 'editar':{
			$id            = $_POST['id_atend'];
			$tipo          = $_POST['TIPO'];
			$categoria     = $_POST['CATEGORIA'];
			$urgencia      = $_POST['URGENCIA'];
//			$observadores  = $_POST['observadores'];
			$titulo        = $_POST['titulo'];
			$descricao     = mysqli_real_escape_string($conn, $_POST['descricao']); 
			$data = date('Y-m-d H:i:s');				
			
	//		$empresa_id = $_SESSION['empresa_id'];
			//$empresa_id = 1;	
			$sql = "UPDATE glpi_tickets SET name = '{$titulo}',  content = '{$descricao}' , date_mod = '{$data}'   WHERE id = '{$id}' "; 
			if (mysqli_query($conn, $sql)) { ?>	
					<script language="JavaScript" type="text/javascript"> alert ("Chamado atualizado com sucesso.")</script>
					<script language="JavaScript">window.location.href="../atendimentos.php";</script><?php
			
			} else {
				echo "Error: " . $sql . "<br>" . mysqli_error($conn);?>
				<script language="JavaScript">window.location.href="../atendimentos.php";</script><?php
			}
			break;
		}
		case 'cadacomp':{
			$id_ticket = $_POST['id_ticket'];
			$id_usuario  = $_POST['ID_USUARIO'];
			$descricao   = $_POST['descricao'];
			$data = date('Y-m-d H:i:s');
				
			$sql = "INSERT INTO glpi_itilfollowups (itemtype, items_id, date, users_id, content, date_mod, date_creation, timeline_position)";
			$sql .= "VALUES ('Ticket', '{$id_ticket}', '{$data}', '{$id_usuario}', '{$descricao}', '{$data}', '{$data}', '4')"; 
			if (mysqli_query($conn, $sql)) { ?>	
					<script language="JavaScript" type="text/javascript"> alert ("Acompanhamento incluído com sucesso.")</script>
					<script language="JavaScript">window.location.href="../acompanhar.php";</script><?php
			
			} else {
				echo "Error: " . $sql . "<br>" . mysqli_error($conn);?>
				<script language="JavaScript">window.location.href="../acompanhar.php";</script><?php
			}
			break;	
		}
		case 'envarq':{
			$id_ticket  = $_POST['id_ticket'];
			$id_usuario = $_POST['ID_USUARIO'];
                        $query = "SELECT entities_id FROM glpi_users WHERE id = {$id}";
                        $res = mysqli_query($conn, $query);
                        $row = mysqli_fetch_assoc($res);
                        $entities_id = $row['entities_id'];
//			print_r($_FILES);
			foreach ($_FILES["arquivos"]["error"] as $key => $error) {
				$caminho = "../../glpi/files/". $insert_id;
				if 	($error != UPLOAD_ERR_NO_FILE){
					if ($error == UPLOAD_ERR_OK) {									
						mkdir($caminho);
						$tmp_name = $_FILES["arquivos"]["tmp_name"][$key];
						// basename() may prevent filesystem traversal attacks;
						// further validation/sanitation of the filename may be appropriate
						$tipo = $_FILES["arquivos"]["type"][$key];
						$ext = strtolower(end(explode('.', $_FILES["arquivos"]["name"][$key])));							
						$name = basename($_FILES["arquivos"]["name"][$key]);
						$filepath = $insert_id."/".$name;			
						move_uploaded_file($tmp_name, "$caminho/$name");
						$sql = "SELECT * FROM glpi_tickets WHERE id = '$id_ticket'"; 
						$res = mysqli_query($conn, $sql) or die('Query Error');
						$result = mysqli_fetch_array($res);	
						$data = date('Y-m-d H:i:s');	
						$titulo = $_result['titulo'];
						//$sqldoc = "INSERT INTO glpi_documents (entities_id, name, filename, filepath, mime, date_mod,  users_id, tickets_id, sha1sum, tag ,date_creation)";
						$sqldoc = "INSERT INTO glpi_documents (entities_id, is_recursive, name, filename, filepath, mime, date_mod,  users_id, tickets_id, date_creation)";
						$sqldoc .= "VALUES ('{$entities_id}','0','Documento: Chamado - {$titulo}', '{$name}', '{$filepath}'  ,'{$tipo}', '{$data}', '{$id_usuario}', '{$id_ticket}', '{$data}')"; 
						echo $sqldoc;
						if (mysqli_query($conn, $sqldoc)){
							$doc_id = mysqli_insert_id($conn);
							$sqldoc1 = "INSERT INTO glpi_documents_items (documents_id, items_id,itemtype, entities_id, is_recursive, date_mod,  users_id, timeline_position)";
							$sqldoc1 .= "VALUES ('{$doc_id}', '{$insert_id}', 'Ticket', '{$entities_id}', '0', '{$data}', '{$id}', '1')"; 
				
							mysqli_query($conn, $sqldoc1);
						}	
									
					}
				}	
			}												
						
			break;	
		}
		case 'cadfech':{
			$id_ticket = $_GET['id_ticket'];
			$id_usuario  = $_POST['ID_USUARIO'];
			$descricao   = $_POST['descricao'];
			$data = date('Y-m-d H:i:s');
			$sql = "INSERT INTO glpi_itilfollowups (itemtype, items_id, date, users_id , user_id_editor, content, is_private,requesttypes_id, date_mod, date_creation, timeline_position, sourceitems_id, sourceof_items_id)";
			$sql .= "VALUES ('Ticket', '{$id_ticket}', '{$data}', '{$data}','{$id_usuario}',0,{$descricao},0,1,{$data},{$data},1,0,0)"; 
			if (mysqli_query($conn, $sql)) { 
				
				$sql1 = "UPDATE glpi_itilsolutions SET date_approvall = '{$date}', user_id_approval = '{$id_usuario}', status = 3 WHERE items_id = '{$id_ticket}'"; 
					if (mysqli_query($conn, $sql1)) { ?>						
						<script language="JavaScript" type="text/javascript"> alert ("Fechamento incluído com sucesso.")</script>
						<script language="JavaScript">window.location.href="../acompanhar.php";</script><?php
					}
			} else {
				echo "Error: " . $sql . "<br>" . mysqli_error($conn);?>
				<script language="JavaScript">window.location.href="../acompanhar.php";</script><?php
			}
			break;	
		}			
	}
	mysqli_close($conn);
	ob_end_flush(); 
?>
</body>
</html>













