<?php
include '../db/db.php';
session_start();

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {     
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";
	 
} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date = date("Y-m-d");
		
		/*************************** Insert ***************************/

		if(isset($_FILES["file_name1"]["name"])) {
			$title_1 = htmlspecialchars(strip_tags(trim($_POST['title_1'])), ENT_QUOTES, 'UTF-8');
			$title_2 = htmlspecialchars(strip_tags(trim($_POST['title_2'])), ENT_QUOTES, 'UTF-8');
			$bimg = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name1"]["name"])), ENT_QUOTES, 'UTF-8'));
						
			if (empty($bimg)) {
				echo 'empty';
			
			} else {
				// get uploaded file's extension
				$ext = strtolower(pathinfo($_FILES["file_name1"]["name"], PATHINFO_EXTENSION));
				$img = 'buddhistbooks-sri-lanka-'.rand(1000, 9999).'.'.$ext;
				
				$valid_extensions = array('png','jpg','jpeg'); // valid extensions
				$path = '../../image/bg-images/'; // upload directory
				$tmp = $_FILES['file_name1']['tmp_name'];
				
				// check valid format
				if(in_array($ext, $valid_extensions)) {
					$path = $path.$img;	
						
					if (file_exists($path)) {			
						echo 'exist'; // File Exists
					
					} else {		
						if(move_uploaded_file($tmp,$path)) {
							$sql = "INSERT INTO main_banner SET title_1='$title_1', title_2='$title_2', img='$img'";
							$stmt_log = mysqli_query($conn, $sql);

							if( $stmt_log === false ) {
								echo 'error';
							
							} else {
								echo 'success';
							}
						
						} else {				
							echo 'error2'; // Uploading Error
						}
					}
				} 
				else {
					 echo 'error3'; // Invaild File
				}
			}
		}
		
		/************************ Load Form Data ************************/
	    
		if (array_key_exists('get_dataset', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');

			$sql = mysqli_query($conn, "SELECT * FROM main_banner WHERE id=$id"); 
			$row = mysqli_fetch_array($sql);

			echo json_encode($row);
	    }
		
		/*************************** Update ***************************/

		if(isset($_FILES["file_name2"]["name"])) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id_up'])), ENT_QUOTES, 'UTF-8');
			$title_1 = htmlspecialchars(strip_tags(trim($_POST['title1_up'])), ENT_QUOTES, 'UTF-8');
			$title_2 = htmlspecialchars(strip_tags(trim($_POST['title2_up'])), ENT_QUOTES, 'UTF-8');
			$bimg = strtolower(htmlspecialchars(strip_tags(trim($_FILES["file_name2"]["name"])), ENT_QUOTES, 'UTF-8'));
						
			$sql_bn = mysqli_fetch_assoc(mysqli_query($conn, "SELECT img FROM main_banner WHERE id=$id"));
			$old_img = $sql_bn['img'];
			
			if (empty($bimg)) {
				$sql = "UPDATE main_banner SET title_1='$title_1', title_2='$title_2' WHERE id=$id";
				$stmt_log = mysqli_query($conn, $sql);

				if( $stmt_log === false ) {
					echo 'error';
				
				} else {
					echo 'success';
				}
			
			} else {
				// get uploaded file's extension
				$ext = strtolower(pathinfo($_FILES["file_name2"]["name"], PATHINFO_EXTENSION));
				$img = 'buddhistbooks-sri-lanka-'.rand(1000, 9999).'.'.$ext;
				
				$valid_extensions = array('png','jpg','jpeg'); // valid extensions
				$path = '../../image/bg-images/'; // upload directory
				$tmp = $_FILES['file_name2']['tmp_name'];
				
				// check valid format
				if(in_array($ext, $valid_extensions)) {
					$path = $path.$img;	
						
					if (file_exists($path)) {			
						echo 'exist'; // File Exists
					
					} else {		
						if(move_uploaded_file($tmp,$path)) {
							$sql = "UPDATE main_banner SET title_1='$title_1', title_2='$title_2', img='$img' WHERE id=$id";
							$stmt_log = mysqli_query($conn, $sql);

							if( $stmt_log === false ) {
								echo 'error';
							
							} else {
								if(!empty($old_img)) {
									$path_old = "../../image/bg-images/".$old_img;
									$files = glob($path_old);
									foreach($files as $file) {
										unlink($file);
									}
								}
								echo 'success';
							}
						
						} else {
							echo 'error2'; // Uploading Error
						}
					}
				}
				else {
					 echo 'error3'; // Invaild File
				}
			}
		}
		
		/***************************** Remove ***************************/
		
	    if (array_key_exists('remove_data', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			
			$sql_bn = mysqli_fetch_assoc(mysqli_query($conn, "SELECT img FROM main_banner WHERE id=$id"));
			$old_img = $sql_bn['img'];
			
			$sql = "DELETE FROM main_banner WHERE id=$id";
			$stmt_log = mysqli_query($conn, $sql);
			
			if( $stmt_log === false ) {
				echo json_encode(array("msgType" => 2, "msg" => "Sorry ! not deleted"));
			
			} else {
				if(!empty($old_img)) {
					$path_old = "../../image/bg-images/".$old_img;
					$files = glob($path_old);
					foreach($files as $file) {
						unlink($file);
					}
				}
				echo json_encode(array("msgType" => 1, "msg" => "Successfully Removed"));
			}
	    }
		
		/*******************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>