<?php
// Koneksi Database dan Proses Mengambil Data
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Cek Koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

$bathrooms = [
    "bathroom1" => ["status" => "empty", "check_in_time" => null],
    "bathroom2" => ["status" => "empty", "check_in_time" => null]
];

// Menangani request AJAX
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['status_update'])) {
    $query = "SELECT * FROM bathroom_usage WHERE status = 'check_in' ORDER BY check_in_time DESC LIMIT 2";
    $result = $conn->query($query);

    while ($row = $result->fetch_assoc()) {
        if ($row['bathroom_name'] == 'Kamar Mandi 1') {
            $bathrooms['bathroom1'] = [
                "status" => $row['status'],
                "check_in_time" => date('Y-m-d\TH:i:s', strtotime($row['check_in_time'])),
            ];
        } elseif ($row['bathroom_name'] == 'Kamar Mandi 2') {
            $bathrooms['bathroom2'] = [
                "status" => $row['status'],
                "check_in_time" => date('Y-m-d\TH:i:s', strtotime($row['check_in_time'])),
            ];
        }
    }
    echo json_encode($bathrooms);
    exit;  // Mengakhiri eksekusi skrip setelah mengirimkan respons
}

// Menutup koneksi
$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Status Kamar Mandi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; padding: 20px; }
        .container { margin-top: 20px; }
        .card-body { text-align: center; }
        .status { font-size: 1.5em; font-weight: bold; }
        .timer { font-size: 2em; color: #007bff; }
        .toilet-image { width: 300px; height: 300px; margin-top: 20px; object-fit: cover; }
        .status-empty { background-color: #28a745; color: white; padding: 20px; border-radius: 10px; font-size: 1.2em; }
        .status-occupied { background-color: #dc3545; color: white; padding: 20px; border-radius: 10px; font-size: 1.2em; }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-4">Visual Status Kamar Mandi</h1>

        <div class="row">
            <!-- Kamar Mandi 1 -->
            <div class="col-md-6">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">Kamar Mandi 1</h5>
                    </div>
                    <div class="card-body">
                        <div id="status_bathroom1" class="status-empty">Kamar Mandi Kosong</div>
                        <img src="bathroom/unisex_toilet.png" alt="Unisex Toilet" class="toilet-image">
                        <p id="check_in_time_1"></p>
                        <p id="timer_1" class="timer"></p>
                    </div>
                </div>
            </div>

            <!-- Kamar Mandi 2 -->
            <div class="col-md-6">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">Kamar Mandi 2</h5>
                    </div>
                    <div class="card-body">
                        <div id="status_bathroom2" class="status-empty">Kamar Mandi Kosong</div>
                        <img src="bathroom/unisex_toilet.png" alt="Unisex Toilet" class="toilet-image">
                        <p id="check_in_time_2"></p>
                        <p id="timer_2" class="timer"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Fungsi untuk memperbarui status kamar mandi setiap 3 detik menggunakan AJAX
        function updateBathroomStatus() {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", "?status_update=true", true);  // Mengambil data status terbaru
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.responseText);

                    // Update Kamar Mandi 1
                    const bathroom1 = data.bathroom1;
                    const statusBathroom1 = document.getElementById("status_bathroom1");
                    const checkInTime1 = document.getElementById("check_in_time_1");
                    const timer1 = document.getElementById("timer_1");

                    if (bathroom1.status === 'check_in') {
                        statusBathroom1.classList.remove("status-empty");
                        statusBathroom1.classList.add("status-occupied");
                        statusBathroom1.textContent = "Kamar Mandi 1 Terpakai";
                        checkInTime1.textContent = "Check-in Time: " + bathroom1.check_in_time;

                        // Hitung selisih waktu dan tampilkan timer
                        const checkInDate = new Date(bathroom1.check_in_time);
                        const currentTime = new Date();
                        const diff = currentTime - checkInDate;  // Selisih waktu dalam milidetik
                        const seconds = Math.floor(diff / 1000);
                        const minutes = Math.floor(seconds / 60);
                        const hours = Math.floor(minutes / 60);
                        const formattedTime = `${hours} jam ${minutes % 60} menit ${seconds % 60} detik`;
                        timer1.textContent = "Waktu Terpakai: " + formattedTime;
                    } else {
                        statusBathroom1.classList.remove("status-occupied");
                        statusBathroom1.classList.add("status-empty");
                        statusBathroom1.textContent = "Kamar Mandi 1 Kosong";
                        checkInTime1.textContent = '';
                        timer1.textContent = '';
                    }

                    // Update Kamar Mandi 2
                    const bathroom2 = data.bathroom2;
                    const statusBathroom2 = document.getElementById("status_bathroom2");
                    const checkInTime2 = document.getElementById("check_in_time_2");
                    const timer2 = document.getElementById("timer_2");

                    if (bathroom2.status === 'check_in') {
                        statusBathroom2.classList.remove("status-empty");
                        statusBathroom2.classList.add("status-occupied");
                        statusBathroom2.textContent = "Kamar Mandi 2 Terpakai";
                        checkInTime2.textContent = "Check-in Time: " + bathroom2.check_in_time;

                        // Hitung selisih waktu dan tampilkan timer
                        const checkInDate2 = new Date(bathroom2.check_in_time);
                        const currentTime2 = new Date();
                        const diff2 = currentTime2 - checkInDate2;
                        const seconds2 = Math.floor(diff2 / 1000);
                        const minutes2 = Math.floor(seconds2 / 60);
                        const hours2 = Math.floor(minutes2 / 60);
                        const formattedTime2 = `${hours2} jam ${minutes2 % 60} menit ${seconds2 % 60} detik`;
                        timer2.textContent = "Waktu Terpakai: " + formattedTime2;
                    } else {
                        statusBathroom2.classList.remove("status-occupied");
                        statusBathroom2.classList.add("status-empty");
                        statusBathroom2.textContent = "Kamar Mandi 2 Kosong";
                        checkInTime2.textContent = '';
                        timer2.textContent = '';
                    }
                }
            };
            xhr.send();
        }

        // Update status setiap 3 detik
        setInterval(updateBathroomStatus, 2000);
    </script>
</body>
</html>
