<?php include '../src/session_check.php'; ?>

<html lang="en" data-bs-theme="dark">
<head>
	<!-- Required meta tags -->
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="../assets/images/favicon-32x32.png" type="image/png">
	<!--plugins-->
	<link href="../assets/plugins/vectormap/jquery-jvectormap-2.0.2.css" rel="stylesheet">
	<link href="../assets/plugins/simplebar/css/simplebar.css" rel="stylesheet">
	<link href="../assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet">
	<link href="../assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet">
	<!-- loader-->
	<link href="../assets/css/pace.min.css" rel="stylesheet"/>    
	<script src="../assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="../assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
	
	<link href="../assets/sass/app.css" rel="stylesheet">
	<link href="../assets/css/icons.css" rel="stylesheet">
	<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
	<!-- Theme Style CSS -->
	<link rel="stylesheet" href="../assets/sass/dark-theme.css">
	<link rel="stylesheet" href="../assets/sass/semi-dark.css">
	<link rel="stylesheet" href="../assets/sass/bordered-theme.css">
	
	<title>TOD Dashboard</title>
</head>

<body>
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<?php include '../src/nav.php'; ?>
		<!--end sidebar wrapper -->
		<!--start header -->
		<?php include '../src/header.php'; ?>
		<!--end header -->

		<!--start page wrapper -->
		<div class="page-wrapper">
			<div class="page-content">
		<!--start page content -->	


				<!-- Breadcrumb -->
				<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
					<div class="breadcrumb-title pe-3">Printer Dashboard</div>
					<div class="ps-3">
						<nav aria-label="breadcrumb">
							<ol class="breadcrumb mb-0 p-0">
								<li class="breadcrumb-item"><a href="index.php"><i class="bx bx-home-alt"></i></a></li>
								<li class="breadcrumb-item active" aria-current="page">Your Printers</li>
							</ol>
						</nav>
					</div>
					<div class="ms-auto">
						<div class="btn-group">
							<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
								Refresh Interval: <span id="selectedIntervalText">60s</span>
							</button>
							<ul class="dropdown-menu dropdown-menu-end" id="intervalDropdown">
								<li><a class="dropdown-item set-interval" data-interval="5000" href="#">5 seconds</a></li>
								<li><a class="dropdown-item set-interval" data-interval="10000" href="#">10 seconds</a></li>
								<li><a class="dropdown-item set-interval" data-interval="30000" href="#">30 seconds</a></li>
								<li><a class="dropdown-item set-interval" data-interval="60000" href="#">60 seconds</a></li>
								<li><a class="dropdown-item set-interval" data-interval="off" href="#">Off</a></li>
							</ul>
						</div>
					</div>

				</div>
				<!-- End Breadcrumb -->

				<div class="container">
					<div class="main-body">
						<div id="alertContainer" class="container mt-3">
   							 <!-- Alerts will be dynamically inserted here -->
						</div>
						<div class="row" id="printerContainer">
							<!-- Printer cards will be dynamically inserted here -->
						</div>
					</div>
				</div>


		<!--end page content -->
			</div>
		</div>
		<!--end page wrapper -->

		<!--start overlay-->
		 <div class="overlay mobile-toggle-icon"></div>
		<!--end overlay-->
		<!--Start Back To Top Button-->
		  <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
		<!--End Back To Top Button-->
	</div>
	<!--end wrapper-->


	<!-- search modal -->
    <div class="modal" id="SearchModal" tabindex="-1">
		<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-fullscreen-md-down">
		  <div class="modal-content">
			<div class="modal-header gap-2">
			  <div class="position-relative popup-search w-100">
				<input class="form-control form-control-lg ps-5 border border-3 border-primary" type="search" placeholder="Search">
				<span class="position-absolute top-50 search-show ms-3 translate-middle-y start-0 top-50 fs-4"><i class='bx bx-search'></i></span>
			  </div>
			  <button type="button" class="btn-close d-md-none" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
		  </div>
		</div>
	  </div>
    <!-- end search modal -->

	<!-- Bootstrap JS -->
	<script src="../assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="../assets/js/jquery.min.js"></script>
	<script src="../assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="../assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="../assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<script src="../assets/plugins/apexcharts-bundle/js/apexcharts.min.js"></script>
	<!--app JS-->
	<script src="../assets/js/app.js"></script>

	<script src="../assets/js/index.js"></script>
	<script src="../assets/plugins/peity/jquery.peity.min.js"></script>
    <script>
       $(".data-attributes span").peity("donut")
    </script>


<script>
$(document).ready(function() {
    let refreshInterval = 60000;  // Default interval of 10s
    let intervalHandler;

    // Load printers asynchronously
    async function loadPrinters() {
        try {
            const response = await $.ajax({
                url: '../src/printers/getPrinters.php',
                method: 'GET',
                dataType: 'json',
                cache: false
            });

            let container = $('#printerContainer');

            if (response.status === 'success' && response.data.length > 0) {
                response.data.forEach(function(printer) {
                    let existingCard = container.find(`.printer-card[data-serial="${printer.serialNumber}"]`);
                    
                    let trayHTML = '';
                    printer.trays.forEach(tray => {
                        let trayColor = `#${tray.color.slice(0, 6)}`;
                        trayHTML += `
                            <div class="tray-slot text-center">
                                <div class="tray-circle" style="background-color: ${trayColor}; width: 40px; height: 40px; border-radius: 50%;"></div>
                                <p>Slot ${parseInt(tray.id) + 1}</p>
                            </div>`;
                    });

                    let printerCard = `
                        <div class="col-lg-4 printer-card" data-serial="${printer.serialNumber}">
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <img src="../assets/images/printer-icon.png" alt="Printer" class="rounded-circle p-1" width="110">
                                    <div class="mt-3">
                                        <h4>${printer.printerName}</h4>
                                        <p class="text-secondary mb-1">Current Job: <span>${printer.jobName}</span></p>
                                        <p class="text-muted font-size-sm">
                                            Bed Temp: <span>${printer.bedTemp}°C</span> | 
                                            Nozzle Temp: <span>${printer.nozzleTemp}°C</span>
                                        </p>
                                    </div>
                                    <div class="d-flex justify-content-center gap-4 mt-3">
                                        ${trayHTML}
                                    </div>
                                    <div class="mt-4 w-100">
                                        <label for="humidityBar${printer.serialNumber}" class="form-label">AMS Humidity</label>
                                        <div class="progress" style="height: 20px;">
                                            <div id="humidityBar${printer.serialNumber}" class="progress-bar" role="progressbar" 
                                                style="width: ${printer.humidity * 20}%;" 
                                                aria-valuemin="1" 
                                                aria-valuemax="5">
                                                ${printer.humidity}/5
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>`;

                    if (existingCard.length) {
                        existingCard.replaceWith(printerCard);
                    } else {
                        container.append(printerCard);
                    }
                });
            }
        } catch (error) {
            console.log('Failed to load printers:', error);
        }
    }

    // Polling function
    function startPolling(interval) {
        clearInterval(intervalHandler);
        if (interval !== 'off') {
            intervalHandler = setInterval(loadPrinters, interval);
        }
    }

    // Handle refresh dropdown
    $('.set-interval').on('click', function(e) {
        e.preventDefault();
        let selectedInterval = $(this).data('interval');

        if (selectedInterval === 'off') {
            clearInterval(intervalHandler);
            console.log("Auto-refresh turned off.");
        } else {
            refreshInterval = parseInt(selectedInterval);
            startPolling(refreshInterval);
            console.log(`Refresh interval set to ${refreshInterval / 1000} seconds.`);
        }
        $('#selectedIntervalText').text(selectedInterval === 'off' ? 'Off' : `${selectedInterval / 1000}s`);
    });

    loadPrinters();
    startPolling(refreshInterval);  // Start polling immediately
});


</script>



</body>

</html>