<?php
session_start();
if (!isset($_SESSION['FirstName'])) {
	die('0');
}

include ('includes/db1config.php');
include ('../includes/mysql_connect.php');

$response = [
	'result' => 0
];

//Code to update monitor-name
if(isset($_POST['action']) && !empty($_POST['action'])){
	if($_POST['action'] == 'update-monitor-name'){
		$sql = "UPDATE menu_boards SET board_name = '".$_POST['monitorName']."' WHERE board_number = ".$_POST['boardNo'];
		mysql_query($sql) or die(mysql_error());
		echo "success";
		die;
	}
}
//End update code

//Code to add new slide
if(isset($_POST['action']) && !empty($_POST['action'])){
	if($_POST['action'] == 'add-new-slide'){

		//get highest board_number 
		$sql2 = "select max(board_number) as boardNumber from menu_boards";
		$result2 = mysql_query($sql2) or die(mysql_error());
		$row2 = mysql_fetch_assoc($result2);
		$row2['boardNumber'];
		$boardNumber = $row2['boardNumber'];
		$boardNumber++;

		//insert new row
		$sql = "INSERT INTO menu_boards (
				board_number,
				board_name,
				column_count,
				add_on_slide
				) VALUES (
					'".$boardNumber."',
					'New slide',
					'3',
					'1'					
				)";
		mysql_query($sql) or die(mysql_error());
		$recorkey = mysql_insert_id();

		//get inserted board_number
		$sql1 = "SELECT board_number from menu_boards where recordKey = '".$recorkey."'";
		$result = mysql_query($sql1) or die(mysql_error());
		$row = mysql_fetch_assoc($result);
		echo $row['board_number']; 
		die;
		//echo "new slide added!";
	}
}
//End add code

if (!isset($_POST['board']) || empty($_POST['board']) || $_POST['board'] < 1) {
	$response['message'] = 'Invalid board number.';
	die(json_encode($response));
}

$boardNumber = trim($_POST['board']);
$board = getMenuBoard($boardNumber);

if (empty($board)) {
	$response['message'] = 'Board not found.';
	die(json_encode($response));
}

if (isset($_POST['image_name']) && !empty($_POST['image_name'])) {
	$image_name = trim($_POST['image_name']);
} else {
	$image_name = '';
}
if (isset($_POST['image_as_bkgd']) && $_POST['image_as_bkgd'] == 1) {
	$image_as_bkgd = 1;
} else {
	$image_as_bkgd = 0;
}


if (!empty($_POST['bkgd_color'])) {
	$bkgd_color = $_POST['bkgd_color'];
} else {
	$bkgd_color = "FFFFFF";
}

if (isset($_POST['scroll_text']) && !empty($_POST['scroll_text'])) {
	$scroll_text = trim($_POST['scroll_text']);
} else {
	$scroll_text = '';
}
if (isset($_POST['scroll_position']) && in_array($_POST['scroll_position'], array(1, 2))) {
	$scroll_position = $_POST['scroll_position'];
} else {
	$scroll_position = 1;
}
if (isset($_POST['text_multiplier'])) {
	$text_multiplier = $_POST['text_multiplier'];
	if ($text_multiplier != 1.5 && $text_multiplier != 1.25 && $text_multiplier != 1.0 && $text_multiplier != 0.75 && $text_multiplier != 0.5) {
		$text_multiplier = 1.0;
	}
} else {
	$text_multiplier = 1.0;
}

if (isset($_POST['template']) && !empty($_POST['template'])) {
	$template = trim($_POST['template']);
} else {
	$template = '';
}

$toggle_boards = 0;
$use_schedule = 0;
if (isset($_POST['schedule'])) {
	if ($_POST['schedule'] == 'toggle_boards') {
		$toggle_boards = 1;
	} elseif ($_POST['schedule'] == 'use_schedule') {
		$use_schedule = 1;
	}
}

if (!empty($_POST['monitor_name'])) {
	$board_name = mysql_real_escape_string($_POST['monitor_name']);
} else {
	$board_name = "";
}

// Ad Settings
$adInterval = isset($_POST['ad_interval']) ? $_POST['ad_interval'] : 1;
$adDuration = isset($_POST['ad_duration']) ? $_POST['ad_duration'] : 3;

// Update menu board
$sql = "UPDATE menu_boards
		SET 
			image_name = '".mysql_real_escape_string($image_name)."',
			image_as_bkgd = '".mysql_real_escape_string($image_as_bkgd)."',
			scroll_text = '".mysql_real_escape_string($scroll_text)."',
			scroll_position = '".mysql_real_escape_string($scroll_position)."',
			text_multiplier = '".mysql_real_escape_string($text_multiplier)."',
			bkgd_color = '".mysql_real_escape_string($bkgd_color)."',
			template = '".mysql_real_escape_string($template)."',
			use_schedule = '".$use_schedule."',
			toggle_boards = '".$toggle_boards."',
			board_name = '".$board_name."',
			ad_interval = '".$adInterval."',
			ad_duration = '".$adDuration."'
		WHERE board_number = '".$board['board_number']."'";
mysql_query($sql) or die(mysql_error());

// Check if bg updated
if (!empty($board['image_name']) && $board['image_name'] != $image_name) {
	deleteOldBgImage($board['image_name']);
}

// Check if menu board schedule needs to be updated
if ($toggle_boards == 1) {
	updateMenuBoardsRotation($boardNumber);
}
if ($use_schedule == 1) {
	updateMenuBoardsSchedule($boardNumber);
}

updateMenuBoardAds($boardNumber);

$response['result'] = 1;


echo json_encode($response);
die();

function getMenuBoard($boardNumber) {
	$sql = "SELECT *
			FROM menu_boards
			WHERE board_number = '".mysql_real_escape_string($boardNumber)."'
			LIMIT 1";
	$result = mysql_query($sql) or die(mysql_error());

	if (mysql_num_rows($result) < 1) {
		return null;
	}

	return mysql_fetch_assoc($result);
}

function addMenuBoardRow($boardNumber) {
	$sql = "INSERT INTO menu_boards (
				board_number,
				column_count
			) VALUES (
				'".$boardNumber."',
				1
			)";
	mysql_query($sql) or die(mysql_error());
	return getMenuBoard($boardNumber);
}

function deleteOldBgImage($imageName) {
	$dir = dirname(__FILE__) . '/../custom/images/menu-boards/';
	if (file_exists($dir . $imageName)) {
		unlink($dir.$imageName);
	}
}

function updateMenuBoardsRotation($boardNumber) {
	$new = [];

	// Get existing
	$existing = [];
	$sql = "SELECT *
			FROM menu_board_schedule
			WHERE menu_board = '".mysql_real_escape_string($boardNumber)."'";
	$result = mysql_query($sql) or die(mysql_error());

	while ($row = mysql_fetch_assoc($result)) {
		$existing[] = $row['display_board'];
	}

	if (isset($_POST['boards_in_rotation']) && is_array($_POST['boards_in_rotation'])) {
		foreach ($_POST['boards_in_rotation'] as $board) {
			if(isset($_POST['isMonitor'])){
				$sql = "INSERT INTO menu_board_schedule (
						menu_board,
						display_board
					) VALUES (
						'".mysql_real_escape_string($boardNumber)."',
						'".mysql_real_escape_string($board)."'
					)";
				mysql_query($sql) or die(mysql_error());
				$scheduleId = mysql_insert_id();
				$new[] = $scheduleId;
			}else{
				if (!in_array($board, $existing) && !in_array($board, $new)) {
				$sql = "INSERT INTO menu_board_schedule (
						menu_board,
						display_board
					) VALUES (
						'".mysql_real_escape_string($boardNumber)."',
						'".mysql_real_escape_string($board)."'
					)";
					mysql_query($sql) or die(mysql_error());
				}
					
				$new[] = $board;
				

			}
			
		}
	}

	// Delete any not saved
	$sql = "DELETE FROM menu_board_schedule
			WHERE menu_board = '".mysql_real_escape_string($boardNumber)."'";
	if (!empty($new)) {
		if(isset($_POST['isMonitor'])){
			$sql .= " and recordkey NOT IN (".implode(',', $new).")";
		}else{
			$sql .= " and display_board NOT IN (".implode(',', $new).")";
		}
	}
	mysql_query($sql) or die(mysql_error());
}

function updateMenuBoardsSchedule($boardNumber) {
	$saved = [];

	if (isset($_POST['boards_in_schedule']) && is_array($_POST['boards_in_schedule'])) {
		foreach ($_POST['boards_in_schedule'] as $board) {
			$time = date('H:i:s', strtotime($board['hour'].':'.$board['minute'].' '.$board['meridiem']));

			if(isset($_POST['isMonitor'])){
					$sql = "INSERT INTO menu_board_schedule (
							menu_board,
							display_board,
							switch_time
						) VALUES (
							'".mysql_real_escape_string($boardNumber)."',
							'".mysql_real_escape_string($board['board'])."',
							'".mysql_real_escape_string($time)."'
						)";
					mysql_query($sql) or die(mysql_error());

					$scheduleId = mysql_insert_id();
					$saved[] = $scheduleId;
				}else{

					if (! ($scheduleId = menuBoardScheduleExists($boardNumber, $board['board'], $time))) {

						$sql = "INSERT INTO menu_board_schedule (
								menu_board,
								display_board,
								switch_time
							) VALUES (
								'".mysql_real_escape_string($boardNumber)."',
								'".mysql_real_escape_string($board['board'])."',
								'".mysql_real_escape_string($time)."'
							)";
						mysql_query($sql) or die(mysql_error());

						$scheduleId = mysql_insert_id();
					}

					$saved[] = $scheduleId;
					
				}

			
		}
	}

	// Delete any not saved
	$sql = "DELETE FROM menu_board_schedule
			WHERE menu_board = '".mysql_real_escape_string($boardNumber)."'";
	if (!empty($saved)) {
		$sql .= " and recordkey NOT IN (".implode(',', $saved).")";
	}
	mysql_query($sql) or die(mysql_error());
}

function menuBoardScheduleExists($boardNumber, $displayBoard, $time) {
	$sql = "SELECT recordkey
			FROM menu_board_schedule
			WHERE menu_board = '".mysql_real_escape_string($boardNumber)."'
			AND display_board = '".mysql_real_escape_string($displayBoard)."'
			AND switch_time = '".mysql_real_escape_string($time)."'
			LIMIT 1";

	$result = mysql_query($sql) or die(mysql_error());

	if (mysql_num_rows($result) > 0) {
		$row = mysql_fetch_assoc($result);

		return $row['recordkey'];
	} else {
		return false;
	}
}

function updateMenuBoardAds($boardNumber) {
    // Get existing ads
    $existing = [];

    $sql = "SELECT * FROM menu_board_ads WHERE menu_board = '" . $boardNumber . "'";
    $result = mysql_query($sql) or die(mysql_error());

    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $existing[] = $row['display_board'];
        }
    }

    $new = [];

    if (isset($_POST['ads']) && is_array($_POST['ads'])) {
        foreach ($_POST['ads'] as $ad) {
            if (! in_array($ad, $existing)) {
                $sql = "INSERT INTO menu_board_ads (menu_board, display_board) 
                        VALUES ('".mysql_real_escape_string($boardNumber)."', '".mysql_real_escape_string($ad)."')";
                mysql_query($sql) or die(mysql_error());
            }

            $new[] = $ad;
        }
    }

    $deleteQuery = "DELETE FROM menu_board_ads WHERE menu_board = '".$boardNumber."'";

    if (! empty($new)) {
        $deleteQuery .= "AND display_board NOT IN (" . implode(',', $new) . ")";
    }

    mysql_query($deleteQuery) or die(mysql_error());
}

?>