<?php
session_start();

// Cek apakah admin sudah login
if (!isset($_SESSION['admin_id'])) {
    // Jika belum login, arahkan ke halaman login
    header("Location: login.php");
    exit;
}

// Sertakan file config untuk koneksi database
include 'config.php';

// Ambil admin_id dari session
$admin_id = $_SESSION['admin_id'];

// Query untuk mengambil email admin berdasarkan admin_id
$query = "SELECT email FROM admin_master WHERE id = :admin_id";
$stmt = $db->prepare($query);
$stmt->bindParam(':admin_id', $admin_id, PDO::PARAM_INT);
$stmt->execute();

// Ambil hasil query
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

// Cek apakah email ditemukan
if ($admin) {
    $email = $admin['email'];
} else {
    echo "Admin data not found.";
    exit;
}

// Variabel untuk menampilkan alert
$alertMessage = '';
$alertType = '';

// Periksa apakah ada alert yang diset di session
if (isset($_SESSION['alert'])) {
    $alert = $_SESSION['alert'];
    
    // Tentukan type dan message dari alert
    $alertType = ($alert['type'] == 'success') ? 'alert-success' : 'alert-danger';
    $alertMessage = $alert['message'];
    
    // Hapus session alert setelah ditampilkan
    unset($_SESSION['alert']);
}

// Query to fetch machine data along with the associated branch name
$machineQuery = "
    SELECT m.*, b.branchName
    FROM machine m
    LEFT JOIN branch b ON m.branchId = b.id
";
$machineStmt = $db->prepare($machineQuery);
$machineStmt->execute();
$machines = $machineStmt->fetchAll(PDO::FETCH_ASSOC);
?>

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

<head>
	<!-- PAGE TITLE HERE -->
	<title>MyWash - Machine</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="author" content="DexignLab">
	<meta name="robots" content="index, follow">
	<!-- MOBILE SPECIFIC -->
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- FAVICONS ICON -->
	<link rel="shortcut icon" type="image/png" href="images/favicon.png">
	<link href="vendor/datatables/css/jquery.dataTables.min.css" rel="stylesheet">

	<link href="vendor/bootstrap-select/css/bootstrap-select.min.css" rel="stylesheet">

	<link class="main-css" href="css/style.css" rel="stylesheet">
	
	<style>

.bg-success {
    background-color: green;
}

.bg-danger {
    background-color: red;
}

	</style>

</head>

<body>

	<!--*******************
        Preloader start
    ********************-->
	<div id="preloader">
		<div class="loading-wave">
			<div class="loading-bar"></div>
			<div class="loading-bar"></div>
			<div class="loading-bar"></div>
			<div class="loading-bar"></div>
		</div>
	</div>
	<!--*******************
        Preloader end
    ********************-->

	<!--**********************************
        Main wrapper start
    ***********************************-->
	<div id="main-wrapper">

		<!--**********************************
            Nav header start
        ***********************************-->
		<div class="nav-header">
			<a href="index.html" class="brand-logo">
				<div class="logo-abbr" width="35" height="35">
					<img src="./images/mywash.png" width="50" height="50">
				</div>
				<div class="brand-title">
					<span class="text-dark">My Wash</span>
				</div>
			</a>
			<div class="nav-control">
				<div class="hamburger">
					<span class="line"></span><span class="line"></span><span class="line"></span>
				</div>
			</div>
		</div>
		<!--**********************************
            Nav header end
        ***********************************-->
		<?php include './page/navbar.php'; ?>
        <?php include './page/sidebar.php'; ?>
		<!--**********************************
            Content body start
        ***********************************-->
		<div class="content-body">
			<!-- row -->
			<div class="container-fluid">
				<div class="page-titles">
					<ol class="breadcrumb">
						<li class="breadcrumb-item"><a href="javascript:void(0)">Machine</a></li>
						<li class="breadcrumb-item active"><a href="javascript:void(0)">Machine Table</a></li>
					</ol>
				</div>
				<div class="row">
					<div class="col-12">
						<div class="card">
							<div class="card-header">
								<h4 class="card-title">Machine List</h4>
								<a href="add-machine.php" class="btn btn-primary btn-sm">Add Machine</a>
							</div>
							<div class="card-body">
                                <?php if ($alertMessage): ?>
                                    <div class="alert <?php echo $alertType; ?> alert-dismissible fade show" role="alert">
                                        <?php echo $alertMessage; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
								<div class="table-responsive">
                                <table id="projectlist" class="display">
                                        <thead>
                                            <tr>
                                                <th>Serial Number</th>
                                                <th>Branch Name</th>
                                                <th>Machine Name</th>
                                                <th>Type</th>
                                                <th>Duration</th>
                                                <th>Created At</th>
                                                <th>Status</th>
                                                <th class="text-end">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($machines as $machine): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($machine['serialNumber']); ?></td>
                                                <td><span class="badge badge-sm badge-primary light"><?= htmlspecialchars($machine['branchName']); ?></span></td>
                                                <td><?= htmlspecialchars($machine['machineName']); ?></td>
                                                <td><?= htmlspecialchars($machine['type']); ?></td>
                                                <td><?= htmlspecialchars($machine['duration']); ?></td>
                                                <td><?= htmlspecialchars($machine['createAt']); ?></td>
                                                <td id="status-<?= $machine['serialNumber']; ?>">
                                                    <span class="badge bg-warning">Checking...</span> <!-- Status default -->
                                                </td>
                                                <td class="text-end">
                                                    <div>
                                                        <a href="delete-machine.php?id=<?= $machine['id']; ?>" class="btn btn-danger shadow btn-xs sharp"><i class="fa fa-trash"></i></a>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
								</div>
							</div>
						</div>
					</div>

				</div>

			</div>
		</div>
		<!--**********************************
            Content body end
        ***********************************-->
		<!--**********************************
            Footer start
        ***********************************-->
		<div class="footer">
			<div class="copyright">
				<p>Copyright © Designed &amp; Developed by <a href="#">MyWash</a> <span class="current-year">2024</span></p>
			</div>
		</div>
		<!--**********************************
            Footer end
        ***********************************-->
	</div>
	<!--**********************************
        Main wrapper end
    ***********************************-->

	<!--**********************************
        Scripts
    ***********************************-->
	<!-- Required vendors -->
	<script src="vendor/global/global.min.js"></script>
	<!-- Datatable -->
	<script src="vendor/datatables/js/jquery.dataTables.min.js"></script>
	<script src="js/plugins-init/datatables.init.js"></script>
	<script src="vendor/bootstrap-select/js/bootstrap-select.min.js"></script>
	<script src="js/custom.min.js"></script>
	<script src="js/ic-sidenav-init.js"></script>
	
    <script>
    $(document).ready(function() {
        function updateStatus(serialNumber) {
            $.ajax({
                url: 'get_machine_status.php',
                type: 'GET',
                data: { serialNumber: serialNumber },
                success: function(response) {
                    console.log("Response from server:", response); // Log response from server
                    var data = JSON.parse(response);
    
                    if (data.status === 'success') {
                        // Debug untuk memeriksa apakah class yang dikirim sudah benar
                        console.log("Received statusClass: " + data.statusClass);
                        
                        // Menyuntikkan HTML dengan badge baru
                        $('#status-' + serialNumber).html('<span class="badge ' + data.statusClass + '">' + data.deviceStatus + '</span>');
                        $('#last-seen-' + serialNumber).text(data.lastSeen);
                    } else {
                        $('#status-' + serialNumber).html('<span class="badge bg-danger">Offline</span>'); // Jika tidak ditemukan
                    }
                },
                error: function() {
                    console.error("AJAX request failed");
                    $('#status-' + serialNumber).html('<span class="badge bg-danger">Offline</span>');
                }
            });
        }
    
        // Perbarui status untuk setiap serialNumber di tabel setiap 2 detik
        setInterval(function() {
            $('td[id^="status-"]').each(function() {
                var serialNumber = $(this).attr('id').split('-')[1];
                updateStatus(serialNumber);
            });
        }, 5000);
    });
    </script>
</body>

</html>