<?php
header('Content-type: application/json');
include '../db/db.php';
session_start();
$log = htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
$log_lang = htmlspecialchars(trim($_SESSION['lang']), ENT_QUOTES, 'UTF-8');

$menu = htmlspecialchars(trim($_SESSION['menu']), ENT_QUOTES, 'UTF-8');
$emp_id = htmlspecialchars(trim($_SESSION['emp_id']), ENT_QUOTES, 'UTF-8');

if (empty($log)) {
	$redirectUrl = "index.php";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";

} else {

	$sqlu = "SELECT * FROM user_priv_q WHERE emp_id='$emp_id' AND user='$log' AND menu_id='$menu'";
	$resultu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($resultu);

	if($countu == 1){
		$rowc = mysqli_fetch_assoc($resultu);
		$user_id = $rowc['user_id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date_today = date("Y-m-d");

		/****************************** Insert *************************************/

		if(isset($_FILES['upload_pdf'])) {	
			if($_FILES["upload_pdf"]["name"] != '') {
				$type = htmlspecialchars(strip_tags(trim($_POST['type'])), ENT_QUOTES, 'UTF-8');
				$division = htmlspecialchars(strip_tags(trim($_POST['division'])), ENT_QUOTES, 'UTF-8');

				$valid_extensions = array('pdf'); // valid extensions
				$path = '../upload/PDF/evaluation_reports/'; // upload directory	

				// get uploaded file's extension
				$ext = strtolower(pathinfo($_FILES["upload_pdf"]["name"], PATHINFO_EXTENSION));
				$tmp = $_FILES['upload_pdf']['tmp_name'];

				// check valid format
				if(in_array($ext, $valid_extensions)) 
				{
					$pdf_name = $date_today.'_'.rand(100000, 999999).'.'.$ext;
					$path = $path.$pdf_name;	

						
					if (file_exists($path))
					{			
						$response['status'] = '2'; // File Exists
					
					} else {
						
						if($log_lang == 1) {
							$sqlg = mysqli_query($conn, "SELECT * FROM evaluation_reports WHERE type='$type' AND division='$division' and del=0");
							if(mysqli_num_rows($sqlg) == 0) {								
								if(move_uploaded_file($tmp,$path)) 
								{
									$sql = "INSERT INTO evaluation_reports VALUES (NULL ,'$date_today', '$pdf_name', '$type', '$division', '$user_id', '0')";
		
									if(mysqli_query($conn, $sql)) {
										$response['status'] = '1'; // Success
									
									} else {
										$response['status'] = '3'; // Sql Error
									}
										
								
								} else{				
								  //exit("Error While uploading image on the server");
								  $response['status'] = '4'; // Uploading Error
								}
							} else {
								$response['status'] = '6'; //Data Already Inserted
							}
						}
					}
				} 
				else 
				{
					$response['status'] = '5'; // Invaild File
				}
			 
			}
			echo json_encode($response);	
		}
		
		/****************************** Remove *************************************/
		
		if (array_key_exists('remove_reports', $_POST)) {

			if($log_lang == 1) {
			
				$group_id = htmlspecialchars(strip_tags(trim($_POST['gid'])), ENT_QUOTES, 'UTF-8');		
				$sql = "UPDATE evaluation_reports SET del=1 WHERE id='$group_id'";
				
				if(!empty($group_id)) {
				
					if(mysqli_query($conn, $sql)) {
						echo json_encode(array("msgType" => 1, "msg" => "Successfully Removed"));
					
					} else {
						echo json_encode(array("msgType" => 2, "msg" => "Sorry ! not deleted"));
					}
				
				} else {
					echo json_encode(array("msgType" => 2, "msg" => "Sorry ! empty id"));
				}
			
			}

		}		
		
		/****************************** Load Form Data *************************************/
		
		if (array_key_exists('get_dataset', $_POST)) {

			$group_id = htmlspecialchars(strip_tags(trim($_POST['gid'])), ENT_QUOTES, 'UTF-8');
			
			$data = array();
			$sql = mysqli_query($conn, "SELECT type,division FROM evaluation_reports WHERE id=$group_id and del=0");

			while ($row = mysqli_fetch_assoc($sql)) {
				$data[] = $row;
			}
			echo json_encode($data);
		}
		
		/****************************** Update *************************************/

		if(isset($_FILES['pdf_update'])) {	
			if($_FILES["pdf_update"]["name"] != '') {
				$group_id = htmlspecialchars(strip_tags(trim($_POST['group_id'])), ENT_QUOTES, 'UTF-8');
			
				$valid_extensions = array('pdf'); // valid extensions
				$path = '../upload/PDF/evaluation_reports/'; // upload directory	

				// get uploaded file's extension
				$ext = strtolower(pathinfo($_FILES["pdf_update"]["name"], PATHINFO_EXTENSION));
				$tmp = $_FILES['pdf_update']['tmp_name'];

				// check valid format
				if(in_array($ext, $valid_extensions)) 
				{
					$pdf_name = $date_today.'_'.rand(100000, 999999).'.'.$ext;
					$path = $path.$pdf_name;	
						
					if (file_exists($path))
					{			
						$response['status'] = '2'; // File Exists
					
					} else {
						
						$sql_eng = mysqli_fetch_assoc(mysqli_query($conn, "SELECT pdf FROM evaluation_reports WHERE id='$group_id'"));	

						if(!empty($sql_eng['pdf'])) {
							$path_old = "../upload/PDF/evaluation_reports/".$sql_eng['pdf'];
							$files = glob($path_old);
							
							foreach($files as $file) {
								unlink($file);
							}
						}
						
						if(move_uploaded_file($tmp,$path)) 
						{  
							if($log_lang == 1) {					
								$sql = "UPDATE evaluation_reports SET pdf='$pdf_name', user='$user_id' WHERE id='$group_id'";
								
								if(mysqli_query($conn, $sql)) {
									$response['status'] = '1'; // Success
								
								} else {
									$response['status'] = '3'; // Sql Error
								}
							}
						
						} else{				
						  //exit("Error While uploading image on the server");
						  $response['status'] = '4'; // Uploading Error
						}
					}
				} 
				else 
				{
					$response['status'] = '5'; // Invaild File
				}
			 
			}
			echo json_encode($response);	
		}		

		/******************************************************************/		

	} else{
		$redirectUrl = "index.php";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";	
	}
}
?>