<!DOCTYPE html>
<html lang="hr">

<head>
	<meta charset="UTF-8">
	<title>Izvještaji</title>
	<style>
		body {
			font-family: Arial, sans-serif;
			background-color: #f4f4f9;
			color: #333;
			text-align: center;
			padding-left: 5%;
		}

		h1 {
			color: #333;
		}

		.month-list {
			display: grid;
			grid-template-columns: repeat(6, 1fr);
			/* Six buttons per row */
			gap: 10px;
			justify-content: center;
			max-width: 1200px;
			/* Adjust to your layout's width */
			margin-bottom: 20px;
		}

		.month-button {
			padding: 20px;
			font-size: 23px;
			font-weight: bold;
			cursor: pointer;
			border-radius: 5px;
			border: 1px solid #ddd;
			background-size: contain;
			background-position: center;
			background-repeat: no-repeat;
			width: 200px;
			height: 150px;
			color: #333;
			transition: background-color 0.3s;
			background-color: #f1f1f1;
		}

		.month-button:hover {
			background-color: blueviolet;
		}

		.alert {
			padding: 20px;
			margin: 20px auto;
			border-radius: 8px;
			font-size: 22px;
			max-width: 80%;
			font-weight: bold;
			display: inline-block;
			text-align: center;
		}

		/* Full-screen overlay to hide everything else */
		.full-page-overlay {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
			/* Semi-transparent black background */
			z-index: 1000;
			display: none;
			/* Hidden by default */
		}

		/* Alert success styling */
		.alert-success {
			color: #155724;
			background-color: #d4edda;
			border: 2px solid #c3e6cb;
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 1001;
			/* Above the overlay */
			padding: 30px;
			width: 80%;
			padding-top: 10%;
		}

		.alert-success button {
			margin-top: 15px;
			margin-left: 15%;
			padding: 8px 20px;
			font-size: 200%;
			cursor: pointer;
			border: none;
			border-radius: 5px;
			background-color: #28a745;
			color: white;
		}

		.alert-error {
			color: #721c24;
			background-color: #f8d7da;
			border: 1px solid #f5c6cb;
			width: 50%;
			margin: 0 auto;
			text-align: center;
		}

		.disabled {
			pointer-events: none;
			opacity: 0.6;
		}

		.loading-overlay {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(255, 255, 255, 0.8);
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			z-index: 1000;
			font-size: 24px;
			color: #333;
		}

		.spinner {
			border: 4px solid rgba(0, 0, 0, 0.1);
			border-top: 4px solid #333;
			border-radius: 50%;
			width: 40px;
			height: 40px;
			animation: spin 1s linear infinite;
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}

		/* Styling checkboxes */
		.checkbox-label {
			font-size: 18px;
			margin-right: 20px;
		}

		.checkbox-input {
			transform: scale(1.2);
			margin-right: 10px;
		}

		/* Styling the exit button in the bottom-right corner */
		.exit-button {
			position: fixed;
			bottom: 20px;
			/* Position 20px from the bottom */
			right: 20px;
			/* Position 20px from the right */
			background-color: #d9534f;
			/* Red background */
			color: white;
			border: none;
			padding: 25px 80px;
			font-size: 16px;
			cursor: pointer;
			border-radius: 4px;
			z-index: 1100;
			/* Ensures it stays on top of other elements */
		}

		.exit-button:hover {
			background-color: #c9302c;
			/* Darker red on hover */
		}
	</style>
</head>

<body>
	<button id="exit-button" class="exit-button" onclick="exitPage()">Izlaz</button>
	<h1 id="main-title">Slanje Izvještaja po mjesecima</h1>

	<!-- Loading overlay -->
	<div id="loading-overlay" class="loading-overlay" style="display: none;">
		<div class="spinner"></div>
		<div>Slanje izvještaja na mail ... (<span id="loading-percentage">0</span>%)</div>
	</div>

	<div id="full-page-overlay" class="full-page-overlay" style="display: none;"></div>

	<!-- Month buttons -->
	<div id="month-buttons" class="month-list">
		<?php
		$months = [
			["Siječanj", "January", 1],
			["Veljača", "February", 2],
			["Ožujak", "March", 3],
			["Travanj", "April", 4],
			["Svibanj", "May", 5],
			["Lipanj", "June", 6],
			["Srpanj", "July", 7],
			["Kolovoz", "August", 8],
			["Rujan", "September", 9],
			["Listopad", "October", 10],
			["Studeni", "November", 11],
			["Prosinac", "December", 12]
		];

		foreach ($months as $month) {
			// HTTP path to the corresponding image for each month
			$imagePath = 'http://localhost/ugo/app/webroot/izvjestaji/slike/month_' . $month[2] . '_report_graphic_button.png';

			echo '<button class="month-button" style="background-image: url(\'' . $imagePath . '\');" onclick="startScript(' . $month[2] . ')">'
				. $month[0] . ' / ' . $month[1] . '</button>';
		}
		?>
	</div>



	<!-- Checkbox for recipient selection -->
	<div style="margin-bottom: 20px;">
		<label class="checkbox-label"><input type="checkbox" id="vlasnik" class="checkbox-input" name="vlasnik">
			Vlasnik</label>
		<label class="checkbox-label"><input type="checkbox" id="knjigovodstvo" class="checkbox-input"
				name="knjigovodstvo"> Knjigovodstvo</label>
	</div>

	<!-- Message display -->
	<div id="messages" class="message"></div>

	<?php
	// Database and license setup
	$currentUrl = $_SERVER['REQUEST_URI'];
	if (strpos($currentUrl, 'ugo') !== false) {
		$projectName = 'ugo';
		$pid = 1;
	} elseif (strpos($currentUrl, 'malo') !== false) {
		$projectName = 'malo';
		$pid = 2;
	} else {
		$projectName = 'nepoznato';
	}

	$mysqli = new mysqli("localhost", "root", "", $projectName);
	if ($mysqli->connect_error) {
		die("Greška prilikom povezivanja na bazu: " . $mysqli->connect_error);
	}

	function getMailerOwner($mysqli)
	{
		$query = "SELECT value FROM settings WHERE name = 'mailer.owner' LIMIT 1";
		$result = $mysqli->query($query);
		if ($result && $result->num_rows > 0) {
			$row = $result->fetch_assoc();
			return $row['value'];
		} else {
			die("Nema vrijednosti za 'mailer.owner' u bazi.");
		}
	}

	function getMailerAccounting($mysqli)
	{
		$query = "SELECT value FROM settings WHERE name = 'mailer.accounting' LIMIT 1";
		$result = $mysqli->query($query);
		if ($result && $result->num_rows > 0) {
			$row = $result->fetch_assoc();
			return $row['value'];
		} else {
			die("Nema vrijednosti za 'mailer.accounting' u bazi.");
		}
	}

	$ownerEmail = getMailerOwner($mysqli);
	$accountingEmail = getMailerAccounting($mysqli);

	?>

	<script>
		let loadingInterval;

		function startScript(month) {
			const vlasnikChecked = document.getElementById('vlasnik').checked;
			const knjigovodstvoChecked = document.getElementById('knjigovodstvo').checked;
			let recipient = 'both';

			if (!vlasnikChecked && !knjigovodstvoChecked) {
				document.getElementById('messages').innerHTML = "<div class='alert alert-error'>Molimo označite barem jednog primatelja.</div>";
				return;
			}


			// Determine recipient parameter based on checkboxes
			if (vlasnikChecked && !knjigovodstvoChecked) {
				recipient = 'vlasnik';

				var ownerEmail = <?php echo json_encode($ownerEmail); ?>;
				if (ownerEmail.length === 0) {
					document.getElementById('messages').innerHTML = "<div class='alert alert-error'>Molimo unesite email adresu za vlasnika.</div>";
					return;
				}

			} else if (!vlasnikChecked && knjigovodstvoChecked) {
				recipient = 'knjigovodstvo';

				var accountingEmail = <?php echo json_encode($accountingEmail); ?>;
				if (accountingEmail.length === 0) {
					document.getElementById('messages').innerHTML = "<div class='alert alert-error'>Molimo unesite email adresu za knjigovodtsvo.</div>";
					return;
				}
			}

			document.getElementById('messages').innerHTML = '';
			document.getElementById('loading-overlay').style.display = 'flex';
			document.getElementById('month-buttons').classList.add('disabled');
			document.getElementById("main-title").style.display = "block";

			let seconds = 0;
			const totalSeconds = 80; // estimated total duration in seconds for 100% progress

			let loadingInterval = setInterval(() => {
				seconds++;
				document.getElementById('loading-percentage').innerText = Math.min(100, Math.floor((seconds / totalSeconds) * 100));
				if (seconds >= totalSeconds) {
					clearInterval(loadingInterval);
				}
			}, 1000);


			var xhr = new XMLHttpRequest();
			xhr.open("POST", "index.php", true);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					clearInterval(loadingInterval);
					document.getElementById('loading-overlay').style.display = 'none';
					document.getElementById('messages').innerHTML = xhr.responseText;
					document.getElementById('month-buttons').classList.remove('disabled');

					if (xhr.responseText.includes("Izvještaji generirani i emailovi poslani.")) {
						let successAlert = document.querySelector('.alert-success');
						if (successAlert) {
							let okButton = document.createElement("button");
							okButton.innerText = "OK";
							okButton.onclick = function () {
								location.reload();
							};
							okButton.style.marginTop = "15px";
							okButton.style.padding = "10px 25px";
							successAlert.appendChild(okButton);

							document.getElementById('month-buttons').style.display = 'none';
							document.getElementById('main-title').style.display = 'none';
						}
					}
				}
			};
			xhr.send("start_script=true&month=" + encodeURIComponent(month) + "&recipient=" + encodeURIComponent(recipient));
		}

		function exitPage() {
			fetch('close_browser.php')
				.then(response => response.text())
				.then(data => {
					console.log(data); // Log the server response
					alert("Browsers have been closed.");
				})
				.catch(error => {
					console.error('Error:', error);
				});
		}
	</script>

	<?php



	function getBaseUrl($mysqli)
	{
		$query = "SELECT value FROM settings WHERE name = 'putanja.http' LIMIT 1";
		$result = $mysqli->query($query);
		if ($result && $result->num_rows > 0) {
			$row = $result->fetch_assoc();
			return $row['value'];
		} else {
			die("Nema URL-a sa imenom 'putanja.http' u bazi.");
		}
	}

	function getMB($mysqli)
	{
		$query = "SELECT value FROM settings WHERE name = 'general.oib' LIMIT 1";
		$result = $mysqli->query($query);
		if ($result && $result->num_rows > 0) {
			$row = $result->fetch_assoc();
			return $row['value'];
		} else {
			die("Nema MB-a sa imenom 'general.oib' u bazi.");
		}
	}

	function checkLicense($mb, $pid)
	{
		$url = "http://kasa-hr.com/vp/xpos/index.php/partner/checkMB?mb=" . $mb . "&pid=" . $pid;
		$response = file_get_contents($url);
		$licenseValue = intval($response);
		return $licenseValue > 7;
	}

	$baseUrl = getBaseUrl($mysqli);
	$mb = getMB($mysqli);
	$licenseValid = checkLicense($mb, $pid);
	?>

	<script>
		var licenseValid = <?php echo json_encode($licenseValid); ?>;
		if (!licenseValid) {
			document.addEventListener('DOMContentLoaded', function () {
				var messageDiv = document.getElementById('messages');
				var monthButtonsDiv = document.getElementById('month-buttons');
				messageDiv.innerHTML = "<div class='alert alert-error'>Licenca nije u redu. Obratite se korisničkoj službi.</div>";
				monthButtonsDiv.classList.add("disabled");
			});
		}
	</script>

	<?php
	if (isset($_POST['start_script']) && $licenseValid) {
		$phantomJsPath = "C:\\wamp\\www\\$projectName\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe";
		$scriptPath = "C:\\wamp\\www\\$projectName\\app\\webroot\\izvjestaji\\open_url.js";
		$month = isset($_POST['month']) ? $_POST['month'] : 1;
		$recipient = isset($_POST['recipient']) ? $_POST['recipient'] : 'both';

		$output = shell_exec("\"$phantomJsPath\" \"$scriptPath\" \"$month\" \"$baseUrl\" \"$projectName\" \"$recipient\" 2>&1");
		if (strpos($output, "Svi izveštaji su generirani i poslani.") !== false || strpos($output, "Svi izveštaji su generirani i poslani.") !== false) {
			// Display the overlay and success alert
			echo "<div id='full-page-overlay' class='full-page-overlay' style='display: block;'></div>";
			echo "<div class='alert alert-success'>Izvještaji uspješno poslani.</div>";
		} else {
			echo "<div class='alert alert-error'>Došlo je do greške. Obratite se korisničkoj službi.</div>";
		}
	}
	?>
</body>

</html>