<?php
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Strict');

session_start();

if (!isset($_SESSION['initialized'])) {
    session_regenerate_id(true);
    $_SESSION['initialized'] = true;
}

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];

include './db.php';

$stmt = $conn->prepare("SELECT name, phone, saldo, status FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($name, $phone, $saldo, $status);
$stmt->fetch();
$stmt->close();

if (empty($name)) {
    session_destroy();
    header("Location: login.php");
    exit();
}

// Hitung jumlah notifikasi dari tabel cart
$stmt = $conn->prepare("SELECT COUNT(*) FROM cart WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($notificationCount);
$stmt->fetch();
$stmt->close();


// Check if there's a cart message
$cart_message = $_SESSION['cart_message'] ?? null;
unset($_SESSION['cart_message']); // Clear the message after displaying

header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("Content-Security-Policy: default-src 'self'; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; script-src 'self' https://cdn.jsdelivr.net 'unsafe-inline';");

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

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

	<!-- FAVICONS ICON -->
	<link rel="shortcut icon" href="images/favicon.png">
	<link href="vendor/bootstrap-select/css/bootstrap-select.min.css" rel="stylesheet">

	<!-- STYLE CSS -->
	<link class="main-css" href="css/style.css" rel="stylesheet">
	
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&icon_names=notifications" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        .machine-wrapper {
            position: relative;
            display: inline-block;
            width: 100px; /* Sesuaikan dengan ukuran gambar */
            height: 100px; /* Sesuaikan dengan ukuran gambar */
        }
        
        .machine-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: 1;
        }
        
        .overlay-icon {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 40px; /* Ukuran GIF */
            height: 40px; /* Ukuran GIF */
            z-index: 2;
            pointer-events: none; /* Agar ikon tidak menghalangi klik */
            display: none; /* Default disembunyikan */
        }
        
        .machine-wrapper .machine-link[disabled] .overlay-icon {
            display: block; /* Tampilkan jika disabled */
        }
        
        .machine-wrapper .machine-link[disabled] .machine-image {
            opacity: 0.5; /* Tambahkan efek transparan */
        }
    </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" class="show">
        
        <?php include './page/header.php'; ?>
        
		<!--**********************************
            Content body start
        ***********************************-->
		<div class="container">
			<div style="margin-top: 2rem;">
				<!-- Page Head -->
				<div class="page-head">
					<div class="row">
						<div class="col-sm-6 mb-sm-4 mb-3">
							<h3 class="mb-0">Good Morning, <?php echo htmlspecialchars($name); ?></h3>
							<p class="mb-0">Your clothes are getting cleaner today!</p>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xl-12">
						<div class="row">
							<div class="col-xl-4 col-lg-6 col-sm-6">
        						<div class="card overflow-hidden">
        							<div class="card-body">
        								<div class="text-center">
        									<div class="profile-photo">
        										<img src="images/profile/profile.png" width="100"
        											class="img-fluid rounded-circle" alt="">
        									</div>
        									<h3 class="mt-4 mb-1"><?php echo htmlspecialchars($name); ?></h3>
        									<p class="text-muted"><?php echo htmlspecialchars($phone); ?></p>
        									<a class="btn btn-outline-primary btn-rounded mt-3 px-5"
        										href="topup.php">Top Up</a>
        								</div>
        							</div>
        
        							<div class="card-footer pt-0 pb-0 text-center">
                                        <div class="row">
                                            <div class="col-8 pt-3 pb-3 border-end">
                                                <!-- Make the saldo clickable by wrapping it in an anchor tag -->
                                                <a href="topup.php" style="text-decoration: none; color: inherit;">
                                                    <h3 class="mb-1"><?php echo 'Rp ' . number_format($saldo, 0, ',', '.'); ?></h3>
                                                    <span>Balance</span>
                                                </a>
                                            </div>
                                            <div class="col-4 pt-3 pb-3">
                                                <h3 class="mb-1"><?php echo htmlspecialchars($status); ?></h3>
                                                <span>Status</span>
                                            </div>
                                        </div>
                                    </div>
        						</div>
        					</div>
							<div class="col-xl-8 col-md-6">
								<div class="card overflow-hidden">
								    <div class="card-header border-0 pb-0 flex-wrap">
									    <h5 class="mb-0">Order History</h5>
									</div>
									<div class="card-body mb-0">
										<div class="table-responsive">
                                            <table class="table header-border table-responsive-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Invoice Number</th>
                                                        <th>Total Price</th>
                                                        <th>Status</th>
                                                        <th>Transaction Date</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="transaction-history">
                                                    <!-- Data transaksi akan ditampilkan di sini -->
                                                </tbody>
                                            </table>
                                        </div>
									</div>
								</div>
							</div>
						</div>
					</div>
                    <div class="col-xl-12">
                        <div class="card overflow-hidden">
                            <div class="card-header border-0 pb-0 flex-wrap">
                                <h5 class="mb-0">Select Machine</h5>
                            </div>
                            <div class="card-body border-0 pb-0 flex-wrap">
                                <!-- Tabs -->
                                <ul class="nav nav-tabs" id="machineTab" role="tablist">
                                    <li class="nav-item">
                                        <button class="nav-link active" id="washing-tab" data-bs-toggle="tab" data-bs-target="#washing" type="button" role="tab" aria-controls="washing" aria-selected="true">Washing</button>
                                    </li>
                                    <li class="nav-item">
                                        <button class="nav-link" id="drayer-tab" data-bs-toggle="tab" data-bs-target="#drayer" type="button" role="tab" aria-controls="drayer" aria-selected="false">Drayer</button>
                                    </li>
                                </ul>
                    
                               <!-- Tab Content -->
                                <div class="tab-content" id="machineTabContent">
                                    <!-- Washing Machines -->
                                    <div class="tab-pane fade show active" id="washing" role="tabpanel" aria-labelledby="washing-tab">
                                        <div class="row mt-3">
                                            <?php
                                            // Query for Washing Machines
                                            $sql = "SELECT id, serialNumber, machineName, command FROM machine WHERE type = 'Washing'";
                                            $result = $conn->query($sql);
                                
                                            // Display washing machines
                                            if ($result->num_rows > 0) {
                                                while ($row = $result->fetch_assoc()) {
                                                    $status = $row['command'] === 'ON' ? 'disabled' : '';
                                                    $icon = $row['command'] === 'ON' ? '<img src="./images/used.gif" alt="Busy" class="overlay-icon">' : '';
                                                    echo '
                                                    <div class="col-md-3 text-center mb-3">
                                                        <div class="machine-wrapper">
                                                            <a href="#" class="machine-link" data-id="' . $row['serialNumber'] . '" ' . $status . '>
                                                                <img src="./images/washing.png" alt="Washing Machine" class="machine-image">
                                                                <p>' . htmlspecialchars($row['machineName']) . '</p>
                                                                ' . $icon . '
                                                            </a>
                                                        </div>
                                                    </div>';
                                                }
                                            } else {
                                                echo '<p>No washing machines available.</p>';
                                            }
                                            ?>
                                        </div>
                                    </div>
                                
                                    <!-- Drayer Machines -->
                                    <div class="tab-pane fade" id="drayer" role="tabpanel" aria-labelledby="drayer-tab">
                                        <div class="row mt-3">
                                            <?php
                                            // Query for Dryer Machines
                                            $sql = "SELECT id, serialNumber, machineName, command FROM machine WHERE type = 'Drayer'";
                                            $result = $conn->query($sql);
                                
                                            // Display dryer machines
                                            if ($result->num_rows > 0) {
                                                while ($row = $result->fetch_assoc()) {
                                                    $status = $row['command'] === 'ON' ? 'disabled' : '';
                                                    $icon = $row['command'] === 'ON' ? '<img src="./images/used.gif" alt="Busy" class="overlay-icon">' : '';
                                                    echo '
                                                    <div class="col-md-3 text-center mb-3">
                                                        <div class="machine-wrapper">
                                                            <a href="#" class="machine-link" data-id="' . $row['serialNumber'] . '" ' . $status . '>
                                                                <img src="./images/drayer.png" alt="Drayer Machine" class="machine-image">
                                                                <p>' . htmlspecialchars($row['machineName']) . '</p>
                                                                ' . $icon . '
                                                            </a>
                                                        </div>
                                                    </div>';
                                                }
                                            } else {
                                                echo '<p>No dryer machines available.</p>';
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>

                                </div>
                            </div>
                        </div>
                    </div>
				</div>
			</div>
			<?php if ($cart_message): ?>
                <script>
                    Swal.fire({
                        icon: '<?php echo $cart_message['type']; ?>',
                        title: '<?php echo $cart_message['message']; ?>',
                        showConfirmButton: false,
                        timer: 3000
                    });
                </script>
            <?php endif; ?>

			<!--**********************************
            Footer start
        ***********************************-->
			<div class="footer">
				<div class="copyright">
					<p>© Designed &amp; Developed by <a
							href="#" target="_blank">My Wash</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>
		<script src="vendor/bootstrap-select/js/bootstrap-select.min.js"></script>
		<!-- Dashboard 1 -->
		<script src="./vendor/swiper/js/swiper-bundle.min.js"></script>
		<script src="js/custom.js"></script>
		<script src="js/ic-sidenav-init.js"></script>
		<script>
		    $(document).ready(function() {
                // Fungsi untuk mengambil riwayat transaksi
                function fetchTransactionHistory() {
                    $.ajax({
                        url: 'fetch_transactions.php',  // URL untuk mengambil riwayat transaksi
                        method: 'GET',
                        success: function(response) {
                            // Masukkan data transaksi ke dalam tabel
                            $('#transaction-history').html(response);
                        }
                    });
                }
            
                // Ambil riwayat transaksi saat halaman dimuat
                fetchTransactionHistory();
            
                // Setiap detik, ambil riwayat transaksi lagi
                setInterval(fetchTransactionHistory, 3000);
            });
            
            document.addEventListener('DOMContentLoaded', function () {
                document.querySelectorAll('.machine-link').forEach(function (link) {
                    link.addEventListener('click', function (e) {
                        e.preventDefault(); // Prevent default link behavior
            
                        const machineId = this.dataset.id;
            
                        // AJAX request to check machine status
                        fetch('check_machine_status.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ machine_id: machineId })
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.status === 'OFF') {
                                    window.location.href = 'add_to_cart.php?machine_id=' + machineId;
                                } else {
                                    alert('Machine is currently ON and cannot be used.');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                            });
                    });
                });
            });

		</script>
</body>

</html>