<?php
// Include DB file for credentials and database connection 
include("db.php");

error_reporting(E_ALL);

/* Validate Request */
include("auth_api.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	

	
	$data = json_decode(file_get_contents('php://input'), true);
	if(isset($data['cat_name']))
	$return = array('success' => false, 'message' => $data['cat_name']);
	else
	$return = array('success' => false, 'message' => '');
	
	
	if(isset($data['cat_name']) && $data['cat_name'] == 'pd'):
	
		$table1 = 'tbl_videos_paradox';
		$table2 = 'tbl_videos_paradox_cat';	
	
		if(isset($data['type']) && $data['type'] != 'categories' && $data['type'] != 'domains'):
		
			$sql = "SELECT ".$table1.".*, ".$table2.".name as cat_name FROM `".$table1."` LEFT JOIN ".$table2." on ".$table2.".id = ".$table1.".cat_id";
			
		else:
		
			$sql = "SELECT * FROM `".$table2."` ORDER by name";
			
		endif;	
		
		
	else:
	
		$table1 = 'tbl_videos_ve';
		$table2 = 'tbl_videos_ve_cat';
		$table3 = 'tbl_videos_ve_domain';
		$table4 = 'tbl_videos_ve_tags';
		
		if(isset($data['type']) && $data['type'] != 'categories' && $data['type'] != 'domains' && $data['type'] != 'tags'):

			 if(isset($data['limit']) && isset($data['offset'])) {
				 
				 //$sql = "SELECT ".$table1.".*, ".$table2.".name as cat_name, ".$table3.".name as domain_name, GROUP_CONCAT(tbl_videos_ve_tags_assigned.tag_id) as tags FROM `".$table1."` LEFT JOIN ".$table2." on ".$table2.".id = ".$table1.".cat_id LEFT JOIN ".$table3." on ".$table3.".id = ".$table1.".domain   LEFT JOIN tbl_videos_ve_tags_assigned on tbl_videos_ve_tags_assigned.video_id = tbl_videos_ve.id GROUP BY tbl_videos_ve.id ORDER BY `id` DESC LIMIT ".$data['limit']." OFFSET ".$data['offset'];
				 
				 $sql = "SELECT ".$table1.".*, ".$table2.".name as cat_name, ".$table3.".name as domain_name, GROUP_CONCAT(tbl_videos_ve_tags_assigned.tag_id) as tags, GROUP_CONCAT(tbl_videos_ve_tags.title) as ntags FROM `".$table1."` LEFT JOIN ".$table2." on ".$table2.".id = ".$table1.".cat_id LEFT JOIN ".$table3." on ".$table3.".id = ".$table1.".domain   LEFT JOIN tbl_videos_ve_tags_assigned on tbl_videos_ve_tags_assigned.video_id = tbl_videos_ve.id LEFT JOIN tbl_videos_ve_tags on tbl_videos_ve_tags.id = tbl_videos_ve_tags_assigned.tag_id GROUP BY tbl_videos_ve.id ORDER BY `tags` DESC LIMIT ".$data['limit']." OFFSET ".$data['offset'];
				 
				 //exit();
				
			 } else {
				 
				 //$sql = "SELECT ".$table1.".*, ".$table2.".name as cat_name, ".$table3.".name as domain_name, GROUP_CONCAT(tbl_videos_ve_tags_assigned.tag_id) as tags FROM `".$table1."` LEFT JOIN ".$table2." on ".$table2.".id = ".$table1.".cat_id LEFT JOIN ".$table3." on ".$table3.".id = ".$table1.".domain   LEFT JOIN tbl_videos_ve_tags_assigned on tbl_videos_ve_tags_assigned.video_id = tbl_videos_ve.id GROUP BY tbl_videos_ve.id ORDER BY `tags` DESC";
				 
				 $sql = "SELECT ".$table1.".*, ".$table2.".name as cat_name, ".$table3.".name as domain_name, GROUP_CONCAT(tbl_videos_ve_tags_assigned.tag_id) as tags, GROUP_CONCAT(tbl_videos_ve_tags.title) as ntags FROM `".$table1."` LEFT JOIN ".$table2." on ".$table2.".id = ".$table1.".cat_id LEFT JOIN ".$table3." on ".$table3.".id = ".$table1.".domain   LEFT JOIN tbl_videos_ve_tags_assigned on tbl_videos_ve_tags_assigned.video_id = tbl_videos_ve.id LEFT JOIN tbl_videos_ve_tags on tbl_videos_ve_tags.id = tbl_videos_ve_tags_assigned.tag_id GROUP BY tbl_videos_ve.id ORDER BY `tags` DESC";
				 
			 
			 }
			
		elseif(isset($data['type']) && $data['type'] == 'domains'):
		
			$sql = "SELECT * FROM `".$table3."` ORDER by name";
		
		elseif(isset($data['type']) && $data['type'] == 'tags'):
		
			 $sql = "SELECT * FROM `".$table4."` ORDER by title";
		
		else:
		
			$sql = "SELECT * FROM `".$table2."` ORDER by name";
			
		endif;			
		
	endif;			
		
		
		
	$result = $conn->query($sql); 
	$rows  = [];
	
	if($result->num_rows > 0)
	{ 
		while($row = $result->fetch_assoc()) 
		{
			$rows[] = $row;	
		}
		$return = array('success' => true, 'message' => 'Successfully fetched data!', 'data' => $rows);
	} else{
		$return = array('success' => false, 'message' => 'No record found!', 'data' => $rows);
	}	
	
	echo json_encode($return);
	
}


if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
	
	
	
	
	$data = json_decode(file_get_contents('php://input'), true); 
	
	
	if(isset($data['rating'])){
		
		$return = array('success' => false, 'message' => 'Rating update to be initiated');
		
		$sql  = 'SELECT id,score_given FROM `tbl_videos_ve_rating` WHERE `video_id` = '.$data['video_id'].' and `user_id` = ' . $data['user_id'];
		$find = $conn->query($sql);
		
		if($find->num_rows > 0)
		{ 
			$row = $find->fetch_assoc(); 
			$update = $conn->query("UPDATE `tbl_videos_ve_rating` SET `score_given` = '".$data['rating']."' WHERE `tbl_videos_ve_rating`.`id` = " . $row['id']); 
		} else { 
			$insert = $conn->query("INSERT INTO `tbl_videos_ve_rating` (`id`, `video_id`, `user_id`, `score_given`, `create_datetime`) VALUES (NULL, '".$data['video_id']."', '".$data['user_id']."', '".$data['rating']."', CURRENT_TIMESTAMP)");
		}		
		
		$sql  = 'SELECT AVG(score_given) as avgScore FROM `tbl_videos_ve_rating` WHERE video_id = '.$data['video_id'].' GROUP By video_id';
		$find = $conn->query($sql);
		
		if($find->num_rows > 0)
		{ 
			$row = $find->fetch_assoc(); 
			$avgScore = $row ['avgScore'];
		} else { 
			$avgScore = NULL;
		}		
			
		$update = $conn->query("UPDATE `tbl_videos_ve` SET `average_rating` = $avgScore WHERE `tbl_videos_ve`.`id` = " . $data['video_id']); 	
		
		$return = array('success' => true, 'message' => 'Rating update to be initiated', 'avgScore' => $avgScore);
		
		echo json_encode($return); die();
		
	}
	
	
	
	
	if(isset($data['type']))
	$return = array('success' => false, 'message' => $data['type']);
	else
	$return = array('success' => false, 'message' => '');
	
	

	
	if(isset($data['item']) && $data['item'] == 'video'):
		if(isset($data['type']) && $data['type'] == 'pd'):
			if($data['id'] != '' &&  $data['id'] != null){
				
				$creation_date = isset($data['creation_date']) ? substr($data['creation_date'],0,10) : 'NULL';
				
				$sql = "UPDATE `tbl_videos_paradox` SET `title`='".addslashes($data['title'])."', `cat_id`='".addslashes($data['cat_id'])."', `editing_status`='".addslashes($data['editing_status'])."', `particular`='".addslashes($data['particular'])."', `keyword`='".addslashes($data['keyword'])."', `youtube_status`='".addslashes($data['youtube_status'])."', `youtube_link`='".addslashes($data['youtube_link'])."', `fb_status`='".addslashes($data['fb_status'])."', `fb_link`='".addslashes($data['fb_link'])."', `linkedIn_status`='".addslashes($data['linkedIn_status'])."', `linkedin_link`='".addslashes($data['linkedin_link'])."', `destination`='".addslashes($data['destination'])."', `remarks`='".addslashes($data['remarks'])."', `creation_date` = $creation_date WHERE `tbl_videos_paradox`.`id` = ".$data['id']; 
				

				
			} else {

				$creation_date = isset($data['creation_date']) ? substr($data['creation_date'],0,10) : 'NULL';
				
				$sql = "INSERT INTO `tbl_videos_paradox` 
				(`title`, `cat_id`, `editing_status`, `particular`, `keyword`, `youtube_status`, `youtube_link`, `fb_status`, `fb_link`, `linkedIn_status`, `linkedin_link`, `destination`, `remarks`, `uploaded_by`, `creation_date`) 
				VALUES ('".addslashes($data['title'])."', '".addslashes($data['cat_id'])."', '".addslashes($data['editing_status'])."', '".addslashes($data['particular'])."', '".addslashes($data['keyword'])."', '".addslashes($data['youtube_status'])."', '".addslashes($data['youtube_link'])."', '".addslashes($data['fb_status'])."', '".addslashes($data['fb_link'])."', '".addslashes($data['linkedIn_status'])."', '".addslashes($data['linkedin_link'])."', '".addslashes($data['destination'])."','".addslashes($data['remarks'])."', '".addslashes($data['uploaded_by'])."', $creation_date);"; 				

			}
		else:
		
			if($data['id'] != '' &&  $data['id'] != null){
				
				$creation_date = isset($data['creation_date']) ? substr($data['creation_date'],0,10) : 'NULL';			
				
				
				if($data['youtube_video_id'] == '') {
					$novideo = 1;
				} else {
					
					$sql = "UPDATE `tbl_videos_ve` SET `title`='".addslashes($data['title'])."', `youtube_video_id`='".addslashes($data['youtube_video_id'])."', `cat_id`='".addslashes($data['cat_id'])."', `quote`='".addslashes($data['quote'])."', `quote_long`='".addslashes($data['quote_long'])."', `client_name`='".addslashes($data['client_name'])."', `company_name`='".addslashes($data['company_name'])."', `designation`='".addslashes($data['designation'])."', `city`='".addslashes($data['city'])."', `state`='".addslashes($data['state'])."', `country`='".addslashes($data['country'])."', `domain`='".addslashes($data['domain'])."', `status`='".addslashes($data['status'])."', `website`='".addslashes($data['website'])."', `remarks`='".addslashes($data['remarks'])."', `creation_date` = $creation_date WHERE `tbl_videos_ve`.`id` = ".$data['id']; 
									
                }
				
			} else {

				$creation_date = isset($data['creation_date']) ? substr($data['creation_date'],0,10) : 'NULL';
				
				$presql  = "SELECT * FROM `tbl_videos_ve` WHERE youtube_video_id = '".addslashes($data['youtube_video_id'])."' LIMIT 1";
		        $find = $conn->query($presql);
						
				if($data['youtube_video_id'] == '') {
					$novideo = 1;
				} else {
				
					if($find->num_rows > 0) {
						$novideo = 2;
					} else {
					
					$sql = "INSERT INTO `tbl_videos_ve` 
					(`title`, `youtube_video_id`, `cat_id`, `quote`, `quote_long`, `client_name`, `company_name`, `designation`, `city`, `state`, `country`, `domain`, `status`, `website`, `remarks`, `uploaded_by`, `creation_date`) 
					VALUES ('".addslashes($data['title'])."', '".addslashes($data['youtube_video_id'])."', '".addslashes($data['cat_id'])."', '".addslashes($data['quote'])."', '".addslashes($data['quote_long'])."', '".addslashes($data['client_name'])."', '".addslashes($data['company_name'])."', '".addslashes($data['designation'])."', '".addslashes($data['city'])."', '".addslashes($data['state'])."', '".addslashes($data['country'])."', '".addslashes($data['domain'])."', '".addslashes($data['status'])."', '".addslashes($data['website'])."', '".addslashes($data['remarks'])."', '".addslashes($data['uploaded_by'])."', $creation_date);"; 	

					}

                }				

			}
			

			
		endif;	
		
		
		//echo $sql; echo $data['id']; exit;
		
		if(isset($sql) && $sql != '') {
		
			if ($conn->query($sql) === TRUE) { 
				
				if($data['id'] == '' ||  $data['id'] == null)
				$data['id'] = $conn->insert_id;
				
				
				unset($data['item']);
				unset($data['type']);
				
				
				
				
				$data['tags'] = $data['tags'] ? explode(",",$data['tags']) : array();
				
				

				$add=array_diff($data['tagsDummy'],$data['tags']);

				$remove=array_diff($data['tags'],$data['tagsDummy']); 
				
				foreach($remove as $rem){
					
					$conn->query("DELETE FROM `tbl_videos_ve_tags_assigned` WHERE `video_id` = '".$data['id']."'  AND `tag_id` = '" . $rem . "'");
				}			
				
				foreach($add as $ad){
					$conn->query("INSERT INTO `tbl_videos_ve_tags_assigned` (`video_id`, `tag_id`, `assigned_by`, `create_datetime`) VALUES ('".$data['id']."', '".$ad."', '".addslashes($data['uploaded_by'])."', CURRENT_TIMESTAMP);");
				}			
				
				$data['tags'] = implode(",",$data['tagsDummy']);
				
				//$return = array('success' => false, 'message' => 'Failed');
				
				$return = array('success' => true, 'message' => 'Video '.($data['id'] != '' &&  $data['id'] != null ? 'Added' : 'Update').' Successfully', 'data' => $data);
				
			} else {
				
				$return = array('success' => false, 'message' => 'Failed');
			
			}	
		} else {
		   if($novideo == 2) {
			   $return = array('success' => false, 'message' => 'Oop! Duplicate Video Found with this ID ');
		   } else {			   
				$return = array('success' => false, 'message' => 'Oop! Please add Video ID.');
		   }
		}			
	
	endif;	
	
	
	if(isset($data['item']) && $data['item'] == 'category'):
		if(isset($data['type']) && $data['type'] == 'pd'):
			$sql = "INSERT INTO `tbl_videos_paradox_cat` 
			(`name`, `description`) 
			VALUES ('".addslashes($data['name'])."', '".addslashes($data['description'])."');"; 
		else:
			$sql = "INSERT INTO `tbl_videos_ve_cat` 
			(`name`, `description`) 
			VALUES ('".addslashes($data['name'])."', '".addslashes($data['description'])."');"; 
		endif;	
		if ($conn->query($sql) === TRUE) {
			$data['id'] = $conn->insert_id;
			unset($data['item']);
			unset($data['type']);
			$return = array('success' => true, 'message' => 'Category Added Successfully', 'data' => $data);
		} else {
			$return = array('success' => false, 'message' => 'Failed');
		}	
	
	endif;	
	
	if(isset($data['item']) && $data['item'] == 'tag'):
		
		$sql = "INSERT INTO `tbl_videos_ve_tags` 
		(`title`, `created_by`) 
		VALUES ('".addslashes($data['title'])."', '".addslashes($data['created_by'])."');"; 
		
		if ($conn->query($sql) === TRUE) {
			$data['id'] = (string)$conn->insert_id;
			unset($data['item']);
			unset($data['type']);
			$return = array('success' => true, 'message' => 'Tag Added Successfully', 'data' => $data);
		} else {
			$return = array('success' => false, 'message' => 'Failed');
		}	
	
	endif;	
	
		
	
	echo json_encode($return);
}


if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
		
	$data = $_REQUEST;   
	
	$return = array('success' => false, 'message' => $data['u']);
	
	if(isset($data['s']) && $data['s'] == 'project'):
		
		
		$sql = "UPDATE `tbl_project` SET `is_deleted` = '1' WHERE `tbl_project`.`project_uid` ='" . $data['p'] . "' AND `tbl_project`.`created_by` ='" . $data['u'] . "';";

		if ($conn->query($sql) === TRUE) 
		{
			$return = array('success' => true, 'message' => 'Project Deleted Successfully');
		} 
		else 
		{
			$return = array('success' => false, 'message' => 'Unable to delete project. Please contact administrator.');
		}		

	endif;	
	
	if(isset($data['s']) && $data['s'] == 'thread'):
		
		
		$sql = "UPDATE `tbl_marker` SET `is_deleted` = '1' WHERE `tbl_marker`.`id` ='" . $data['m'] . "' AND `tbl_marker`.`created_by` ='" . $data['u'] . "';";

		if ($conn->query($sql) === TRUE) 
		{
			$return = array('success' => true, 'message' => 'Thread deleted successfully');
		} 
		else 
		{
			$return = array('success' => false, 'message' => 'Unable to delete thread. Please contact administrator.');
		}		

	endif;
	
	if(isset($data['s']) && $data['s'] == 'comment'):
		
		
		$sql = "UPDATE `tbl_reply` SET `is_deleted` = '1' WHERE `tbl_reply`.`id` ='" . $data['r'] . "' AND `tbl_reply`.`posted_by` ='" . $data['u'] . "';";

		if ($conn->query($sql) === TRUE) 
		{
			$return = array('success' => true, 'message' => 'Comment deleted successfully');
		} 
		else 
		{
			$return = array('success' => false, 'message' => 'Unable to delete Comment. Please contact administrator.');
		}		

	endif;		
	
	echo json_encode($return);
	
}
