<?php
    ob_start();
	session_start();
	require_once "includes/config.php";
	require_once "includes/functions.php";
	

?>

<html lang="en">
<head>
	<title><?php echo "Order manager"; ?></title>
	<meta charset="UTF-8">
	<link rel="icon" type="image/x-icon" href="images/favicon.ico">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

	<!-- DataTables and jQuery Dependencies -->
	<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>  

	<!-- DataTables and jQuery Dependencies -->
	<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
	<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>  
	<link rel="stylesheet" href="bootstrap/4.3.1/css/bootstrap.min.css">

	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">	
	<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
	<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">

	<link rel="stylesheet" href="styles/w3.css">
	
	<!-- DataTable css -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
	<link rel="stylesheet" href="https://cdn.datatables.net/2.1.8/css/dataTables.dataTables.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
	
	<link rel="stylesheet" href="styles/sitestyles.css">

    <style>
        /* Adjust the DataTables table design */
        table.dataTable tbody tr td {
            vertical-align: middle;
        }
    </style>
    <style>
        /* Custom styling for the plus/minus icons */
        td.details-control {
            cursor: pointer;
            text-align: center;
        }
        tr.details td {
            background-color: #f9f9f9;
        }
    </style>
	<link rel="stylesheet" href="styles/sitestyles.css">
	<script>
	
		function playNotificationSound() {
			var audio = new Audio("sounds/notification.mp3"); // Ensure the file exists
			audio.play().catch(error => console.error("Error playing sound:", error));
		}
	
		// Function to trigger the notification
		function showNotification() {
			
			// Show the notification icon
			document.getElementById("notification-icon").style.display = "block";
			
		}
		
		// Check if notification is triggered by PHP (flag passed from PHP)
		// Poll the server for new order notifications
		setInterval(() => {
			const cacheBuster = `?_=${new Date().getTime()}`; // Unique timestamp
			fetch('new_order_flag.txt' + cacheBuster, { cache: 'no-cache' })
				.then(response => response.text())
				.then(flag => {
					console.log ("FLAG:"+flag.trim());
					//alert("FLAG:"+flag.trim());
					if (flag.trim() !== '0') {
						playNotificationSound();
						showNotification();
						// Call printOrder() and wait for it to complete
						printOrder(flag.trim())
							.then(() => {
								console.log("finished printing");
								// Reset the flag on the server after printing completes
								return fetch('reset_order_flag.php', { method: 'POST' });
							})
							.then(response => response.text())
							.then(data => {
								console.log('Flag reset:', data);
								location.reload(); // Reload the page AFTER resetting the flag
							})
							.catch(error => console.error("Error in printOrder or resetting flag:", error));

					}
				})
				.catch(error => console.error('Error checking new order flag:', error));
		}, 15000); // Check every 20 seconds	
	</script>
</head>
<?php
	$order_status = "any";
	$order_status_title = "Όλες οι παραγγελίες";
	// Handle POST request and set a flag for notification
	$notificationFlag = false;
	
	$daysSelect = 1;
	// Retrieve the value from session if it exists
	if (isset($_SESSION['daysSelect'])) {
		$daysSelect = $_SESSION['daysSelect'];
	}
	
	// If the form is submitted, update the session value
	if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['daysSelect'])) {
		$daysSelect = $_POST['daysSelect'];
		$_SESSION['daysSelect'] = $daysSelect;
	}

	if ($_SERVER['REQUEST_METHOD'] == 'POST') 
	{
		
		$secret = WOO_API_SECRET; // WooCommerce/settings/advanced/webhooks

		// When receive data from WooCommerce webhook
		$json = file_get_contents('php://input');
		$data = json_decode($json, true);
		$req_dump = print_r( $json, true );

		$fp = file_put_contents('request.log', $req_dump. PHP_EOL, FILE_APPEND);

		// Verify the request using the secret
		$headers = getallheaders();

		// Check if the data is valid
		if (isset($data['id'])) 
		{
			// A new order has been received
			$order_id = $data['id'];
			file_put_contents('new_order_flag.txt', $order_id); // Set flag to indicate new order
			// You can perform actions with the order data here
			// For example, store it in a database, send an email, etc.
			
			// Example output (for testing)
			//echo json_encode(['status' => 'success', 'order_id' => $order_id]);
			$notificationFlag = true;
		}
		
		// $notificationFlag = true;   // FOR TEST ONLY
		
		// Χειριζόμαστε τα cookies για να φορτώνουμε τις τελευταίες τιμές
		// των κριτηρίων που εισήγαγε ο χρήστης
		if (isset($_POST['order_status']))
			$order_status = $_POST['order_status'];
		else
			if (isset($_SESSION['order_status']))
				$order_status = $_SESSION['order_status'];
			
		if (isset($_POST['order_status_title']))
			$order_status_title = $_POST['order_status_title'];
		else
			if (isset($_SESSION['order_status_title']))
				$order_status_title = $_SESSION['order_status_title'];

		// Retrieve the values from the form and set them to the variables
		if (isset($_POST['date_from']))
			$date_from = htmlspecialchars($_POST['date_from']);
		else
		{
			if (isset($_SESSION['date_from']))
				$date_from = $_SESSION['date_from'];
			else
			{
				$date = new DateTime();
				$date_from = $date->format('Y-m-d');
			}
		}
		$today = date("Y-m-d");
		$date_to = $today;
		
		if (isset($_POST['date_to']))
			$date_to = htmlspecialchars($_POST['date_to']);
		else
		{
			if (isset($_SESSION['date_to']))
				$date_to = $_SESSION['date_to'];
			else
			{
				$date = new DateTime();
				$date_to = $date->format('Y-m-d');
			}
		}
		$adjustDates = '';
		if (isset($_POST['adjustDatesCheckbox']))
			$adjustDates = 'checked';
			
		if (isset($_POST['daysSelect']))
			$daysSelect = $_POST['daysSelect'];
		
		// Αποθηκεύω το order_status στο session cookie
		$_SESSION['order_status'] = $order_status;
		$_SESSION['order_status_title'] = $order_status_title;
		// Αποθηκεύω τις ημερομηνίες στο session cookie
		$_SESSION['date_from'] = $date_from;
		$_SESSION['date_to'] = $date_to;
		
		$_SESSION['adjustDates'] = $adjustDates;
		$_SESSION['daysSelect'] = $daysSelect;
	}
	else
	{
		if (isset($_SESSION['order_status']))
			$order_status = $_SESSION['order_status'];
		
		if (isset($_SESSION['order_status_title']))
			$order_status_title = $_SESSION['order_status_title'];

		if (isset($_SESSION['date_from']))
			$date_from = $_SESSION['date_from'];
		else
		{
			$date = new DateTime();
			$date_from = $date->format('Y-m-d');
		}
		$today = date("Y-m-d");
		$date_to = $today;
		if (isset($_SESSION['date_to']))
			$date_to = $_SESSION['date_to'];
		else
		{
			$date = new DateTime();
			$date_to = $date->format('Y-m-d');
		}

		$adjustDates = '';
		if (isset($_POST['adjustDatesCheckbox']))
			$adjustDates = checked;
			
		if (isset($_POST['daysSelect']))
			$daysSelect = $_POST['daysSelect'];

		$_SESSION['adjustDates'] = $adjustDates;
		$_SESSION['daysSelect'] = $daysSelect;

	}

?>
<body>

<!-- Sidebar/menu -->
<nav class="w3-sidebar w3-red w3-collapse w3-top w3-large w3-padding menu_colors" style="z-index:3;width:300px;font-weight:bold;" id="mySidebar"><br>
	<a href="javascript:void(0)" onclick="w3_close()" class="w3-button w3-hide-large w3-display-topleft menu_colors" style="width:100%;font-size:22px"><?php echo ICON_CLOSE; ?></a>
	<div class="w3-container">
		<h3 class="w3-padding-32"><b><?php echo SITE_TITLE; ?></b></h3>
	</div>
	<div class="w3-bar-block">
		<?php include "inc_menu.php"; ?>
	</div>
</nav>

<!-- Top menu on small screens -->
<header class="w3-container w3-top w3-hide-large w3-red w3-xlarge w3-padding menu_colors">
	<a href="javascript:void(0)" class="w3-button w3-red w3-margin-right" onclick="w3_open()">☰</a>
	<span><?php echo SITE_TITLE; ?></span>
</header>

<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large menu_colors" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>

<!-- !PAGE CONTENT! -->
<div class="w3-main" style="margin-left:340px;margin-right:40px">

	<!-- Header -->
	<div class="w3-container" style="margin-top:10px" id="page_head">
		<h1 class="w3-xxxlarge" id="order_status_title_h1">Παραγγελίες</h1>
		<div id="notification-icon" style="position: fixed; top: 20px; right: 20px; display: none;">
			<i class="bi bi-bell-fill" style="font-size: 30px; color: yellow;"></i>
		</div>
		 <audio id="order-sound" src="sounds/notification.mp3" preload="auto"></audio>
		<hr class="redhr w3-round">
	</div>


	<div class="container mt-4" style="margin-bottom: 0px; padding: 0;">
		<form id="datesForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
			<div class="form-container">
				<div class="row" style="margin-top: -26px;" >
				<input type="hidden" name="order_status" id="order_status" value="<?php echo $order_status; ?>" />
				<input type="text" name="order_status_title" id="order_status_title" value="<?php echo $order_status_title; ?>" readonly />
				</div>
				<!-- First row: Date fields -->
				<div class="row mb-3" style="margin-top: -20px; margin-bottom: 0px;">
					<div class="col-md-4">
						<label for="date1">Από</label>
						<input type="date" id="date_from" name="date_from" value="<?php echo $date_from; ?>">
					</div>
					<div class="col-md-4">
						<label for="date2">Έως</label>
						<input type="date" id="date_to" name="date_to" value="<?php echo $date_to; ?>">
					</div>
					<div class="col-md-4">
					</div>
				</div>
				
				<!-- Second row: Checkbox, Dropdown, and Submit button -->
				<div class="row mb-3" style="border-style: solid; border-width: 1px; border-color: transparent; margin-top: -50px;">
					<!-- Checkbox and Label in the same row -->
					<div class="col-md-9" style="margin-right: 0px; border-style: solid; border-width: 1px; border-color: transparent;">
						<input type="checkbox" name="adjustDatesCheckbox" id="adjustDatesCheckbox" style="margin-right: 5px; margin-top: 0px!important;" <?php echo $adjustDates; ?>>
						<label for="adjustDatesCheckbox" style="margin-bottom: 0;margin-top: -30px!important;">Παραγγελίες από τις  </label>
						<select name="daysSelect" id="daysSelect" style="width: 40px;">
							<option value="0"> </option>
							<?php
								for ($i=1; $i<=10; $i++)
								{
									$selected_item = '';
									if ($i == $daysSelect)
										$selected_item = 'selected';
									echo "<option value='".$i."' ".$selected_item.">".$i."</option>";
								}
							?>
						</select>  τελευταίες ημέρες.
					</div>

					<!-- Submit button -->
					<div class="row mb-3" style="margin-left: 10px; border-style: solid; border-width: 1px; border-color: transparent;">
						<input type="submit" name="Submit" value="Ανανέωση" style="margin-left: 20px; height: 40px;">
						<img id="progress" src="images/loading.gif" style="height: 30px!important; margin-top: 5px;margin-left: 20px; display: none;" />
					</div>
				</div>
			</div>  
		</form>
	</div>

	<div class="w3-container" style="margin-top: -80px;">
		<table id="order-table" class="display" style="width:100%">
			<thead>
				<tr>
					<th></th>
					<th>ID</th>
					<th>ΗΜΕΡΟΜΗΝΙΑ</th>
					<th>ΩΡΑ</th>
					<th>ΠΕΛΑΤΗΣ</th>
					<th>ΣΥΝΟΛΟ</th>
					<th>ΤΡΟΠΟΣ ΠΛΗΡΩΜΗΣ</th>
					<th>ΚΑΤΑΣΤΑΣΗ</th>
					<th>ΕΝΕΡΓΕΙΕΣ</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</div>
</div>

<!-- W3.CSS Container -->
<div class="w3-light-grey w3-container w3-padding-32" style="margin-top:75px;padding-right:58px"><p class="w3-right"><?php echo FOOTER_TEXT; ?></p></div>

<script>
	// Script to open and close sidebar
	function w3_open() {
		
	  document.getElementById("mySidebar").style.display = "block";
	  document.getElementById("myOverlay").style.display = "block";
	  
	}
	 
	function w3_close() {
		
	  document.getElementById("mySidebar").style.display = "none";
	  document.getElementById("myOverlay").style.display = "none";
	  
	}

	// Modal Image Gallery
	function onClick(element) {
		
	  document.getElementById("img01").src = element.src;
	  document.getElementById("modal01").style.display = "block";
	  var captionText = document.getElementById("caption");
	  captionText.innerHTML = element.alt;
	  
	}

	// Διεύθυνση του RESTful server από το config.php
	const web_server = "<?php echo WEB_SERVER; ?>";
	
	function removeBOM(str) {
		return str.replace(/^\uFEFF/, '');
	}

	function getCookieValue(cname, default_val) {
	  let name = cname + "=";
	  let decodedCookie = decodeURIComponent(document.cookie);
	  let ca = decodedCookie.split(';');
	  for(let i = 0; i <ca.length; i++) {
		let c = ca[i];
		while (c.charAt(0) == ' ') {
		  c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
		  return c.substring(name.length, c.length);
		}
	  }
	  return default_val;
	}
	function dateFromISOTime(dateTimeString) {
		// Create a new Date object from the string
		var dateObject = new Date(dateTimeString);

		// Extract and format the date as dd/mm/yyyy
		var day = ("0" + dateObject.getDate()).slice(-2); // Adds leading zero
		var month = ("0" + (dateObject.getMonth() + 1)).slice(-2); // Months are zero-based
		var year = dateObject.getFullYear();
		var formattedDate = day + "/" + month + "/" + year;
		
		return formattedDate;
	}

	function timeFromISOTime(dateTimeString) {
		// Create a new Date object from the string
		var dateObject = new Date(dateTimeString);

		// Extract and format the time (HH:mm:ss)
		var hours = ("0" + dateObject.getHours()).slice(-2);
		var minutes = ("0" + dateObject.getMinutes()).slice(-2);
		var seconds = ("0" + dateObject.getSeconds()).slice(-2);
		var formattedTime = hours + ":" + minutes + ":" + seconds;
		
		return formattedTime;
	}

	var orderData = {};
	var orderDetails = {};
	
	// Function to get WooCommerce orders via AJAX request
	function getWooOrders() {
		
		return new Promise(function (resolve, reject) {
			
			// Εμφανίζω το στρογγυλό που γυρνάει
			document.getElementById("progress").style.display = "block"
			
			// Διαβάζουμε το woocommerce order status από κρυφό πεδίο
			order_status = document.getElementById("order_status").value;
			date_from = document.getElementById("date_from").value;
			date_to = document.getElementById("date_to").value;
			
			// Post header που στέλνεται στο api
			var creds = "order_status="+order_status+"&date_from="+date_from+"&date_to="+date_to;

			// Create an XMLHttpRequest object
			var ajx = new XMLHttpRequest();

			// Define what happens on successful data submission
			ajx.onreadystatechange = function() {
				if (ajx.readyState === 4) {  	// readyState 4 means the request is done
					if (ajx.status === 200) { 	// status 200 is a successful return
						try {
							// Parse the JSON response
							document.getElementById("progress").style.display = "none";
							var jsonData = JSON.parse(ajx.responseText);
							
							orderData = [];
							var newestOrder = true
							jsonData.forEach(function(order, index) {

								// Loop through each product in the line_items array
								var orderInfo = {
										"id": order.id,
										"status": order.status,
										"date_created": dateFromISOTime(order.date_created),
										"time_created": timeFromISOTime(order.date_created),
										"total": order.total.replace('.', ','),
										"billing": order.billing.first_name + ' ' + order.billing.last_name,
										"payment_method_title": order.payment_method_title
									};
									orderData.push(orderInfo);
									if (newestOrder == true) {
										//document.cookie = "newest_date=" + dateFromISOTime(order.date_created);
										//document.cookie = "newest_time=" + timeFromISOTime(order.date_created);
									}
									newestOrder = false;
							});		
							
							// Φτιάχνει πίνακα με τις λεπτομέρειες της παραγγελίας
							jsonData.forEach(function(order, index) {
								orderDetails[index] = [];
								// Loop through each product in the line_items array
								
								// Για κάθε line_item φτιάχνει ένα αντικείμενο "product"
								order.line_items.forEach(function(item) {
									var product = {
										"name": item.name,
										"quantity": item.quantity,
										"subtotal": item.subtotal
									};
									orderDetails[index].push(product);
								});
							});
							// Σηματοδοτεί το τέλος της δημιουργίας orderData
							resolve(orderData); // Resolve the Promise with the data
							
						} catch (error) {
							reject("Error parsing JSON data: " + error.message);
						}
					} else {
						reject("Error: " + ajx.status); // Reject with status code on failure
					}
				}
			};

			// Define what happens in case of an error
			ajx.onerror = function() {
				reject("Request failed");
			};

			// Initialize the request
			ajx.open("POST", web_server + "api.php?action=get_woo_orders", true);
			ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			// Send the request
			ajx.send(creds);
		});
			
	}	// getWooOrders


	function updateWooOrderByID(orderID, orderStatus) {
		
		return new Promise(function (resolve, reject) {
			
			// Post header που στέλνεται στο api
			var creds = "order_id="+orderID+"&order_status="+orderStatus;
			
			// Create an XMLHttpRequest object
			var ajx = new XMLHttpRequest();

			// Define what happens on successful data submission
			ajx.onreadystatechange = function() {
				if (ajx.readyState === 4) {  	// readyState 4 means the request is done
					if (ajx.status === 200) { 	// status 200 is a successful return
						try {

							var jsonData = JSON.parse(ajx.responseText);
							
							// Ensure jsonData is an array
							if (!Array.isArray(jsonData)) {
								jsonData = [jsonData]; // Wrap single object in an array
							}
							
							orderData = [];
							jsonData.forEach(function(order, index) {

								// Loop through each product in the line_items array
								var orderInfo = {
									"id": order.id,
									"status": order.status,
								};
															
								orderData.push(orderInfo);

							});		
							
							// Σηματοδοτεί το τέλος της δημιουργίας orderData
							resolve(orderData); // Resolve the Promise with the data
							
						} catch (error) {
							reject("Error parsing JSON data: " + error.message);
						}
					} else {
						reject("Error: " + ajx.status); // Reject with status code on failure
					}
				}
			};

			// Define what happens in case of an error
			ajx.onerror = function() {
				reject("Request failed");
			};

			// Initialize the request
			ajx.open("POST", web_server + "api.php?action=update_woo_order_status", true);
			ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			// Send the request
			ajx.send(creds);
		});	
	}	// updateWooOrderByID


	// Function to get WooCommerce orders via AJAX request
	function getWooOrderByID(orderID, orderStatus) {
		
		return new Promise(function (resolve, reject) {
			
			// Εμφανίζω το στρογγυλό που γυρνάει
			document.getElementById("progress").style.display = "block"
			
			// Διαβάζουμε το woocommerce order status από κρυφό πεδίο
			order_status = document.getElementById("order_status").value;
			date_from = document.getElementById("date_from").value;
			date_to = document.getElementById("date_to").value;
			
			// Post header που στέλνεται στο api
			var creds = "order_id="+orderID+"&order_status="+orderStatus;
			
			// Create an XMLHttpRequest object
			var ajx = new XMLHttpRequest();

			// Define what happens on successful data submission
			ajx.onreadystatechange = function() {
				if (ajx.readyState === 4) {  	// readyState 4 means the request is done
					if (ajx.status === 200) { 	// status 200 is a successful return
						try {
							// Parse the JSON response
							document.getElementById("progress").style.display = "none";
							var jsonData = JSON.parse(ajx.responseText);
							
							// Ensure jsonData is an array
							if (!Array.isArray(jsonData)) {
								jsonData = [jsonData]; // Wrap single object in an array
							}
							
							orderData = [];
							
							var newestOrder = true
							
							jsonData.forEach(function(order, index) {
								// Loop through each product in the line_items array
								var orderInfo = {
									"id": order.id,
									"status": order.status,
									"date_created": dateFromISOTime(order.date_created),
									"time_created": timeFromISOTime(order.date_created),
									"total": order.total.replace('.', ','),
									"billing": order.billing.first_name + ' ' + order.billing.last_name,
									"payment_method_title": order.payment_method_title,
									"address": order.billing.address_1 + " " + order.billing.address_2,
									"city": order.billing.city + " " + order.billing.state + " " + order.billing.postcode,
									"contact": order.billing.phone,
									"email": order.billing.email
								};
															
								orderData.push(orderInfo);
								if (newestOrder == true) {
									document.cookie = "newest_date=" + dateFromISOTime(order.date_created);
									document.cookie = "newest_time=" + timeFromISOTime(order.date_created);
								}
								newestOrder = false;
							});		
							
							// Φτιάχνει πίνακα με τις λεπτομέρειες της παραγγελίας
							jsonData.forEach(function(order, index) {
								orderDetails[index] = [];
								// Loop through each product in the line_items array
								
								// Για κάθε line_item φτιάχνει ένα αντικείμενο "product"
								order.line_items.forEach(function(item) {
									
									var product = {
										"name": item.name,
										"quantity": item.quantity,
										"subtotal": item.subtotal
									};
									orderDetails[index].push(product);
								});
							});
							// Σηματοδοτεί το τέλος της δημιουργίας orderData
							resolve({orderData, orderDetails}); // Resolve the Promise with the data
							
						} catch (error) {
							reject("Error parsing JSON data: " + error.message);
						}
					} else {
						reject("Error: " + ajx.status); // Reject with status code on failure
					}
				}
			};

			// Define what happens in case of an error
			ajx.onerror = function() {
				reject("Request failed");
			};

			// Initialize the request
			ajx.open("POST", web_server + "api.php?action=get_woo_order_by_id", true);
			ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			// Send the request
			ajx.send(creds);
		});	
	}	// getWooOrderByID

	function padRight(str, targetLength, padChar = ' ') {
		return str + padChar.repeat(Math.max(0, targetLength - str.length));
	}


	function sendPrintRequest(orderprintoutfile, content, retryCount = 2) {
		return new Promise((resolve, reject) => {
			function attemptPrint(retriesLeft) {
				console.log(`ℹ️ Sending print request (Retries Left: ${retriesLeft}) to http://localhost:3000/print`);
				console.log(`ℹ️ Print Data:`, { filename: orderprintoutfile, content: content });

				fetch('http://localhost:3000/print', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ filename: orderprintoutfile, content: content })
				})
				.then(response => {
					console.log("ℹ️ Fetch request completed with status:", response.status);
					
					if (!response.ok) {
						throw new Error(`❌ Server Error: ${response.status} - ${response.statusText}`);
					}
					
					return response.json();
				})
				.then(data => {
					console.log("✅ Print response received:", data);
					resolve(data); // Ensures the promise is properly resolved
				})
				.catch(error => {
					console.error("❌ Error caught during print:", error);

					if (error.message.includes("Failed to fetch") || error.message.includes("NetworkError")) {
						console.warn(`⚠️ Fetch failed, retrying... (${3 - retriesLeft}/2)`);

						if (retriesLeft > 0) {
							setTimeout(() => attemptPrint(retriesLeft - 1), 12000);
						} else {
							console.error("❌ Printer service unreachable after retries.");
							alert("Σφάλμα: Ο Print Manager δεν εκτελείται. Παρακαλώ ελέγξτε ότι ο διακομιστής εκτύπωσης είναι ενεργός.");
							reject(error); // Reject after all retries fail
						}
					} else {
						console.error("❌ Fatal error during print request.");
						alert("Σφάλμα κατά την αποστολή στην εκτύπωση: " + error.message);
						reject(error); // Reject other errors immediately
					}
				});
			}

			attemptPrint(retryCount);
		});
	}

	
	
	function printOrder(orderID) {
		return new Promise((resolve, reject) => {
			// Call the function to fetch order data and details
			getWooOrderByID(orderID, "any")
				.then(({ orderData, orderDetails }) => {
					console.log("ℹ️ Order details retrieved successfully for Order ID:", orderID);

					let newLine = "\r\n";
					let paddingLeft = "  ";
					let notesRows = 6;
					let content = paddingLeft + "---------------- ΠΑΡΑΓΓΕΛΙΑ --------------" + newLine;

					// Use the first order's data to populate the receipt
					let order = orderData[0];
					content += paddingLeft + "ΑΡ. ΠΑΡΑΓΓΕΛΙΑΣ: " + order.id + newLine;
					content += paddingLeft + order.date_created + " " + order.time_created + newLine;
					content += paddingLeft + order.billing + newLine;
					content += paddingLeft + order.address + newLine;
					content += paddingLeft + order.city + newLine;
					content += paddingLeft + order.contact + newLine;
					content += paddingLeft + order.email + newLine;
					content += newLine;

					// Use `orderDetails` to iterate over line items for the first order
					orderDetails[0].forEach(function (orderItem) {
						content += paddingLeft + padRight(orderItem.name, 41) + orderItem.quantity + newLine;
					});

					content += paddingLeft + "--------------- ΠΑΡΑΤΗΡΗΣΕΙΣ -------------" + newLine;

					for (let i = 1; i <= notesRows; i++) {
						content += paddingLeft + "____________________________________________" + newLine;
					}

					let orderprintoutfile = orderID + ".txt";

					// Call the print function and resolve the promise once completed
					sendPrintRequest(orderprintoutfile, content)
						.then(() => {
							console.log("Print job completed for Order ID:", orderID);
							resolve(); // Resolve the promise after printing is done
						})
						.catch(error => {
							console.error("Error printing order:", error);
							reject(error); // Reject in case of an error
						});
				})
				.catch(error => {
					console.error("Error fetching order details:", error);
					reject(error); // Reject if fetching order details fails
				});
		});
	}
	

	// **********************************************************************
	//
	// ΑΠΟ ΕΔΩ ΞΕΚΙΝΑΕΙ Η ΛΕΙΤΟΥΡΓΙΑ ΤΟΥ ΠΡΟΓΡΑΜΜΑΤΟΣ $(document).ready
	//
	// **********************************************************************


    $(document).ready(function() {
		
		// Κρύβουμε το στρογγυλό progress bar
		document.getElementById("progress").style.display = "none";
		
		
		const adjustDatesCheckbox = $("input[name='adjustDatesCheckbox']");
		const dateFrom = $("#date_from");
		const dateTo = $("#date_to");

		if (adjustDatesCheckbox.length) {
			// Restore checkbox state
			adjustDatesCheckbox.prop("checked", localStorage.getItem("adjustDatesChecked") === "true");

			// Adjust dates if checkbox is checked
			if (adjustDatesCheckbox.prop("checked")) {
				let today = new Date();
				let sevenDaysAgo = new Date();
				sevenDaysAgo.setDate(today.getDate() - <? echo $daysSelect; ?>);

				dateFrom.val(sevenDaysAgo.toISOString().split('T')[0]);
				dateTo.val(today.toISOString().split('T')[0]);
			}

			// Save checkbox state on change
			adjustDatesCheckbox.on("change", function() {
				localStorage.setItem("adjustDatesChecked", $(this).prop("checked"));
			});
		}		
	
        // Function to initialize and populate DataTable
        function initializeDataTable(orderCategory) {
            var table = $('#order-table').DataTable({
                "ordering": true,
                "paging": false,
                "data": [],  // Initialize the table with no data
                "columns": [
					{ 	"className": "details-control",
						"orderable": false,
						"data": null,
						"defaultContent": '<td class="details-control"><i class="fas fa-plus"></i></td>',
						"width" : "5%"
					},
                    { 	"data": "id",
						"width" : "5%"
					},
                    { 	"data": "date_created",
						"width" : "10%"
					},
                    { 	"data": "time_created",
						"width" : "10%"
					},
                    { 	"data": "billing",
						"width" : "30%"
					},
                    { 	"data": "total",
						"width" : "10%",
						"className" : "text-right"
					},
                    { 	"data": "payment_method_title",
						"width" : "20%"
					},
                    { 	"data": "status",
						"width" : "10%"
					},
					{ 
						data: null, 
						title: 'ΕΝΕΡΓΕΙΕΣ',
						render: function (data, type, row) {
							// Determine button states based on the "status" column
							let status = row.status;
							//let printDisabled = status === ("on-hold" || "processing" || "completed") ? "" : "disabled";
							let printDisabled = ["on-hold", "processing", "completed"].includes(status) ? "" : "disabled";
							let finishedDisabled = status === "processing" ? "" : "disabled";

							return `
								<button id="print-btn" class="print-btn" ${printDisabled}>Εκτύπωση</button>
								<button id="finished-btn" class="finished-btn" ${finishedDisabled}>Ολοκληρωμένη</button>
							`;
						}
					},
                ],
				rowCallback: function(row, data) {
						// Define your threshold values for date and time
						var thresholdDate = getCookieValue("newest_date", "01/01/2024"); //"10/12/2024"; // Example date
						var thresholdTime = getCookieValue("newest_time", "00:00:00"); //"12:00:00"; // Example time

						// Check if the row meets the condition
						if (data.date_created > thresholdDate || 
							(data.date_created === thresholdDate && data.time_created > thresholdTime)) {
							$(row).css('font-weight', 'bold'); // Apply bold style
						}
					}
            });


			$('#adjustDatesCheckbox').on('click', function () {
				const adjustDatesCheckbox = document.getElementById("adjustDatesCheckbox");
				const daysSelect = document.getElementById("daysSelect");
				const dateFrom = document.getElementById("date_from");
				const dateTo = document.getElementById("date_to");

				function adjustDates() {
					if (adjustDatesCheckbox.checked) {
						let days = parseInt(daysSelect.value, 10);
						let today = new Date();

						// Set dateTo to today's date
						let toDateStr = today.toISOString().split('T')[0];
						dateTo.value = toDateStr;

						// Set dateFrom to 'days' days before today
						let fromDate = new Date();
						fromDate.setDate(today.getDate() - days);
						let fromDateStr = fromDate.toISOString().split('T')[0];
						dateFrom.value = fromDateStr;
					}
				}

				// Trigger adjustment when the checkbox is clicked or dropdown changes
				adjustDatesCheckbox.addEventListener("change", adjustDates);
				daysSelect.addEventListener("change", adjustDates);
			});
			
			
			// Handle Print button click
			$('#order-table tbody').on('click', '.print-btn', function () {

				let rowData = table.row($(this).parents('tr')).data();
				let orderId = rowData.id; // Get Order ID
				let $row = $(this).parents('tr');
				
				printOrder(orderId);
				
				if (rowData.status != 'completed') {
					updateWooOrderByID(orderId, 'processing')
						.then(() => {
							// Alert the user and reload the page
							// alert('Order status updated to "processing". Reloading page...');
							location.reload();
						})
						.catch((error) => {
							// Handle errors (optional)
							console.error('Failed to update order status:', error);
							//alert('Failed to update order status. Please try again.');
						});
				}

			});
	

			// Handle Finished button click
			$('#order-table tbody').on('click', '.finished-btn', function () {

				let rowData = table.row($(this).parents('tr')).data();
				let orderId = rowData.id; // Get Order ID
				let $row = $(this).parents('tr');
				printOrder(orderId);

				updateWooOrderByID(orderId, 'completed')
					.then(() => {
						// Alert the user and reload the page
						// alert('Order status updated to "completed". Reloading page...');
						location.reload();
					})
					.catch((error) => {
						// Handle errors (optional)
						console.error('Failed to update order status:', error);
						// alert('Failed to update order status. Please try again.');
					});

			});
			
			// Add event listener for opening and closing details
			$('#order-table tbody').on('click', 'td.details-control', function () {
				var tr = $(this).closest('tr');
				var row = table.row(tr);
				var idx = row.index();
				
				// Toggle child row visibility
				if (row.child.isShown()) {
					row.child.hide();
					$(this).html('<i class="fas fa-plus"></i>'); // Change to plus icon
					tr.removeClass('details');
				} else {
					row.child(format(idx)).show();
					$(this).html('<i class="fas fa-minus"></i>'); // Change to minus icon
					tr.addClass('details');
				}
			});
			
			// Call getWooOrders to fetch the data
			getWooOrders().then(function(data) {
				// Populate the DataTable with fetched data
				table.clear().rows.add(data).draw();
			}).catch(function(error) {
				console.log(error);
			});
			
		};

        // Function to format child row with details
        function format(d) {
            var details = '<table class="table table-bordered"><thead><tr><th>ΠΡΟΪΟΝ</th><th>ΠΟΣΟΤΗΤΑ</th><th>ΑΞΙΑ</th></tr></thead><tbody>';
			
            orderDetails[d].forEach(function(orderItem) {
                details += '<tr><td>' + orderItem.name + '</td><td>' + orderItem.quantity + '</td><td>' + orderItem.subtotal + '</td></tr>';
            });
            details += '</tbody></table>';
            return details;
        }	

		initializeDataTable('any');

/*
		document.addEventListener("DOMContentLoaded", function() {
			const adjustDatesCheckbox = document.getElementById("adjustDatesCheckbox");
			const daysSelect = document.getElementById("daysSelect");
			const dateFrom = document.getElementById("fldDateFrom");
			const dateTo = document.getElementById("fldDateTo");

			function adjustDates() {
				if (adjustDatesCheckbox.checked) {
					let days = parseInt(daysSelect.value, 10);
					let today = new Date();

					// Set dateTo to today's date
					let toDateStr = today.toISOString().split('T')[0];
					dateTo.value = toDateStr;

					// Set dateFrom to 'days' days before today
					let fromDate = new Date();
					fromDate.setDate(today.getDate() - days);
					let fromDateStr = fromDate.toISOString().split('T')[0];
					dateFrom.value = fromDateStr;
				}
			}

			// Trigger adjustment when the checkbox is clicked or dropdown changes
			adjustDatesCheckbox.addEventListener("change", adjustDates);
			daysSelect.addEventListener("change", adjustDates);
		});		
*/
		
	});  //document.ready()
		
		
</script>

</body>
</html>
