<?php
include("../connect.php");
include("../session.php");
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
date_default_timezone_set("America/Puerto_Rico");
$isAdmin = $_SESSION['isAdmin'];
if (!$isAdmin) {
	header("Location: logout.php");
}
mysqli_query($con,"SET time_zone = '-4:00';");

//die("rte");
$function = $_REQUEST['f'];
if($function == "createNewTicket"){
	createNewTicket($_REQUEST['subject'], $_REQUEST['contents'], $_REQUEST['priority']);
	
}elseif($function == "createNewTicketItem"){
	
	createNewTicketItem($_REQUEST['tid'], $_REQUEST['comment']);
	
}elseif($function == "getTicketInfo"){
	$ticket = new Ticket($_REQUEST['tid']);
	echo json_encode($ticket);
}elseif($function == "changePriority"){
	$ticket = new Ticket($_REQUEST['tid']);
	$ticket->Priority = $_REQUEST['value'];
	if($ticket->save()){
		unset($ticket);
		$ticket = new Ticket($_REQUEST['tid']);
		createNewTicketItem($ticket->TicketID, "Changed Priority to " . $ticket->PriorityText);
		//echo json_encode($ticket);	
	}
	
}elseif($function == "changeStatus"){
	$ticket = new Ticket($_REQUEST['tid']);
	$ticket->Status = intval($_REQUEST['value']);
	if($ticket->Status == 2 || $ticket->Status == -1){
		$ticket->DateClosed = date("Y-m-d H:i:s");
	}
	if($ticket->save()){
		unset($ticket);
		$ticket = new Ticket($_REQUEST['tid']);
		createNewTicketItem($ticket->TicketID, "Changed Status to " . $ticket->StatusText);
		//echo json_encode($ticket);	
	}
	
}
elseif($function == "deleteTicketItem"){
	$query = "DELETE FROM TICKET_ITEM WHERE id = " . $_REQUEST['tiid'];
	if(mysqli_query($con, $query)){
		echo "true";
	}else{
		echo "false";
	}
	
	
}else{
    die( "Invalid function");
}

function createNewTicket($subject, $contents, $priority){
	global $con;
	$query = "INSERT INTO TICKET_HEAD (TicketID, TicketDate, Username) VALUES (0, NOW(), ?)";
	$stmt = $con->prepare($query);
	$stmt->bind_param("s", $_SESSION['Username']);
	$stmt->execute();
	$id = $stmt->insert_id;
	$ticket = new Ticket($id);
	$ticket->Subject = $subject;
	$ticket->Contents = $contents;
	$ticket->Priority = intval($priority);
	$return = new stdClass();
	
	if($ticket->save()){
		$return->Result = true;
		$return->Ticket = $ticket;
		echo json_encode($return);
	}else{
		$return->Result = false;
		$return->Ticket = $ticket;
		echo json_encode($return);
	}
}

function createNewTicketItem($ticketID, $comment){
	global $con;
	
	$query = "INSERT INTO TICKET_ITEM (TicketID, Username, PostDate, Comment) VALUES (?, ?, NOW(), ?);";
	
	
	$stmt = $con->prepare($query);
	
	$stmt->bind_param("iss", $ticketID, $_SESSION['Username'], $comment);
	//die(var_dump($stmt));
	if($stmt->execute()){
		echo "true";	
	}else{
		echo "false";
	}
	//$id = $stmt->insert_id;
	//$ticketItem = new TicketItem($id);
}

?>