<?php
// CONNECTION TO DATABASE STARTS HERE
$servername = "localhost";
$username = "root";
$password = "#lbAcZvXP&RIjm9YoIT*1JuhAu^#QI";
$dbname = "livesmart_server_video";
$dbPrefix = 'lsv_';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}

// CONNECTION TO DATABASE ENDS HERE
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET'){
	echo 'This is a GET request.';
}
if ($method === 'POST'){
	$action = $_POST['action'];
	if ($action === 'create_room'){
        if (check_user($conn)) {
			create_room($conn);
		} else {
			$response = [
				"status" => false,
				"message" => "Invalid credentials."
			];

			echo json_encode($response);
		}
    }
	elseif ($action === 'update_room') {
		if (check_user($conn)) {
			update_room($conn);
		} else {
			$response = [
				"status" => false,
				"message" => "Invalid credentials."
			];

			echo json_encode($response);
		}
	}
}

function check_user($conn) {
	if (isset($_POST['username']) && $_POST['api_key']) {
		$username = $_POST['username'];
		$api_key = $_POST['api_key'];

		$sql = "SELECT *  FROM `lsv_agents` WHERE `username` LIKE '{$username}' AND `api_key` LIKE '{$api_key}'";
		$result = $conn->query($sql);

		if ($result->num_rows > 0) {
			return true;
		} else {
			return false;
		}
    }
}

function create_room($conn) {
	$agent_id = $_POST['username'];
	$api_key = $_POST['api_key'];
	$datetime = $_POST['datetime'];
	$roomId = $_POST['room_name'];
	$password = $_POST['meeting_password'];
	$agent = $_POST['organiser_name'];
	$duration = $_POST['duration'];
	$config = $_POST['config'];
	$meeting_status = $_POST['meeting_status'];
	$pingback_url = $_POST['pingback_url'];
	$is_active = $_POST['is_active'];

	$scheme = $_SERVER['REQUEST_SCHEME'];
	$host = $_SERVER['SERVER_NAME'];

	$visitorRoom = [   
		"agentName"=> $agent,
		"agentId" =>  $agent_id,
		"roomId"=> $roomId,
		"duration"=> $duration,
		"config"=> 'config',
		"disableAll"=> false,
		"disableVideo" => false
	];
	$jsonData = json_encode($visitorRoom);
	$visitorCode = base64_encode($jsonData);
	$visitorurl = $scheme . "://" . $host . "/" . $roomId . "?p=" . $visitorCode;

	if ($password) {
		$agentRoom = [
			"agentName"=> $agent,
			"admin"=> 1,    
			"pass" => $password, 
			"agentId" =>  $agent_id,
			"roomId"=> $roomId,
			"duration"=> $duration,
			"config"=> 'config',
			"disableAll"=> false,
			"disableVideo" => false
		];
	} else {
		$agentRoom = [
			"agentName"=> $agent,
			"admin"=> 1,    
			"agentId" =>  $agent_id,
			"roomId"=> $roomId,
			"duration"=> $duration,
			"config"=> 'config',
			"disableAll"=> false,
			"disableVideo" => false
		];
	}
	$jsonData = json_encode($agentRoom);
	$agentCode = base64_encode($jsonData);
	$agenturl = $scheme . "://" . $host . "/" . $roomId . "?p=" . $agentCode;


    $sql = 'SELECT * FROM lsv_rooms WHERE roomId = "'.$roomId.'"';
	$result = $conn->query($sql);

	$is_active = ($is_active == 'true') ? 0 : 1;

	$hash = md5($password);

	if (!isset($is_active)) {
		$is_active = 1;
	}
	if (!isset($disableall)) {
		$disableall = 0;
	}
	if (!isset($disablevideo)) {
		$disablevideo = 0;
	}

	if ($result->num_rows > 0) {
        try {
			$sql = "UPDATE lsv_rooms
			SET agent = '$agent', 
				visitor = '$visitor', 
				agenturl = '$agenturl', 
				visitorurl = '$visitorurl',
				password = '$hash',
				datetime = '$datetime',
				duration = '$duration',
				shortagenturl = '$shortagenturl',
				shortvisitorurl = '$shortvisitorurl',
				agent_id = '$agent_id',
				agenturl_broadcast = '$agenturl_broadcast',
				visitorurl_broadcast = '$visitorurl_broadcast',
				shortagenturl_broadcast = '$shortagenturl_broadcast',
				shortvisitorurl_broadcast = '$shortvisitorurl_broadcast',
				is_active = $is_active, 
				disableall = $disableall, 
				disablevideo = $disablevideo,
				pingback_url = '$pingback_url'
			WHERE roomId = '$roomId'";

			$result = $conn->query($sql);

			if ($result === TRUE) {
				$status =  true;
			} else {
				$status = false;
			}
		} catch (Exception $e) {
			$status = false;
		}
		$response = [
			"visitor_url" => $visitorurl,
			"agent_url" => $agenturl,
			"status" => $status,
			"message" => "Room updated successfully.",
		];
	} else {
		try {
			$sql = "INSERT INTO lsv_rooms (agent, visitor, agenturl, visitorurl, password, roomId, datetime, duration, shortagenturl, shortvisitorurl, agent_id, agenturl_broadcast, visitorurl_broadcast, shortagenturl_broadcast, shortvisitorurl_broadcast, is_active, disableall, disablevideo, pingback_url) "
					. "VALUES ('$agent', '$visitor', '$agenturl', '$visitorurl', '$hash', '$roomId', '$datetime', '$duration', '$shortagenturl', '$shortvisitorurl', '$agent_id', '$agenturl_broadcast', '$visitorurl_broadcast', '$shortagenturl_broadcast', '$shortvisitorurl_broadcast', $is_active, $disableall, $disablevideo, '$')";
			
			if ($conn->query($sql) === TRUE) {
				$insertId =  $conn->insert_id;
			} else {
				$insertId = "Error: ". $sql. "<br>". $conn->error;
			}
		} catch (Exception $e) {
			$insertId = 'Error';
		}

		$response = [
			"visitor_url" => $visitorurl,
			"agent_url" => $agenturl,
			"status" => true,
			"message" => "Room created successfully.",
			"insert_id" => $insertId
		];
	}

	echo json_encode($response);
}

function update_room($conn) {
	
}
?>