<?php
include 'koneksi.php';
include 'auth.php'; // Cek login
date_default_timezone_set("Asia/Jakarta");

if (!isset($_SESSION['user'])) {
    header('location:login.php');
    exit;
}

// Ambil nama user dari session
$nama = $_SESSION['user']['nama'];
$tanggal_sekarang = date('Y-m-d');
$now = new DateTime();
$nama_asli = '';
$cek_nama_asli = mysqli_query($koneksi, "SELECT nama_asli FROM user WHERE nama = '$nama' LIMIT 1");
if ($cek_nama_asli && mysqli_num_rows($cek_nama_asli) > 0) {
    $row = mysqli_fetch_assoc($cek_nama_asli);
    $nama_asli = $row['nama_asli'];
}

// Ambil data absensi hari ini (jika ada)
$absen_result = $koneksi->prepare("SELECT sift, stay, off FROM absen WHERE nama = ? AND tanggal = ?");
$absen_result->bind_param("ss", $nama_asli, $tanggal_sekarang);
$absen_result->execute();
$absen_data = $absen_result->get_result()->fetch_assoc();
$absen_result->close();

// Ambil nilai status dan sift
$sift_value = $absen_data['sift'] ?? '-';
$status_value = '';
if (!empty($absen_data['off'])) {
    $status_value = 'OFF';
} elseif (!empty($absen_data['stay'])) {
    $status_value = 'STAY';
} else {
    $status_value = '-';
}

// Ambil semua nama dari tabel user
$user_query = $koneksi->query("SELECT nama_asli FROM user");
$nama_list = [];
while ($row = $user_query->fetch_assoc()) {
    $nama_list[] = $row['nama_asli'];
}

// Ubah semua data STAY yang tanggalnya sudah lewat dan belum OFF
$now_date = date('Y-m-d');
$now_time = date('H:i:s');

// Ambil semua data yang masih STAY tapi sudah lewat tanggal
$sql_update = "
    UPDATE absen 
    SET off = IF(off IS NULL OR off = '', '$now_time', off)
    WHERE tanggal < ? AND stay IS NOT NULL AND (off IS NULL OR off = '')
";
$stmt_update = $koneksi->prepare($sql_update);
$stmt_update->bind_param("s", $now_date);
$stmt_update->execute();
$stmt_update->close();

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Home | Driver</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="css/fa/all.css">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="css/navbar.css">
</head>

<body>
    <form method="post" id="absenForm">
        <div class="container">
            <input type="text" style="pointer-events: none;" id="nama_panggilan" value="<?= htmlspecialchars($nama) ?>"
                readonly>
            <input type="text" id="nama" name="nama" value="<?= htmlspecialchars($nama_asli) ?>" readonly hidden>

            <div class="total-box">
                <input style="pointer-events: none;" type="text" name="tanggal" value="<?= date('Y-m-d') ?>" readonly>

                <div class="icon-wrapper">
                    <div class="input-container">
                        <i class="fas fa-user input-icon"></i>
                        <input style="pointer-events: none;" type="text" name="sift" id="siftInput"
                            value="<?= htmlspecialchars($sift_value) ?>" readonly>
                    </div>
                </div>
                <div class="icon-wrapper">
                    <div class="input-container">
                        <i class="fa-solid fa-circle input-icon"></i>
                        <input style="pointer-events: none;" type="text" name="status" id="statusInput"
                            value="<?= htmlspecialchars($status_value) ?>" readonly>
                    </div>
                </div>
                <button type="button" onclick="handleAbsen()">Absen</button>
            </div>
    </form>
    
    <div class="menu-container" id="menuContainer">
        <div class="menu-grid" style="margin-bottom:10px;">
            <button type="button" class="menu-btn" id="orderButton" onclick="window.location.href='treport.php'">
                <i class="fas fa-shopping-cart"></i> Order
            </button>

            <button type="button" class="menu-btn" onclick="window.location.href='formreport.php'">
                <i class="fa-solid fa-file-lines"></i>Report
            </button>

            <button type="button" class="menu-btn" id="stayButton" onclick="window.location.href='penghasilan.php'">
                <i class="fa-solid fa-database"></i> Rincian
            </button>

            <button hidden type="button" class="menu-btn" onclick="window.location.href='menu_tabungan1.php'">
                <i class="fa-solid fa-sack-dollar"></i>Ongkir
            </button>

            <button type="button" class="menu-btn" onclick="window.location.href='cek_ongkir.php'">
                <i class="fa-solid fa-sack-dollar"></i>Ongkir
            </button>

            <button hidden type="button" class="menu-btn" onclick="window.location.href='note.php'">
                <i class="fa-solid fa-square-pen"></i>Notebook
            </button>

            <button type="button" class="menu-btn" onclick="window.location.href='profil.php'">
                <i class="fa-solid fa-user"></i>Akun
            </button>

            <button type="button" class="menu-btn" onclick="confirmLogout()">
                <i class="fas fa-sign-out"></i>Logout
            </button></a>
        </div>
    </div>

    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" hidden></span>
            <span class="visually-hidden">Sebelumnya</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
            <span class="carousel-control-next-icon" hidden></span>
            <span class="visually-hidden">Selanjutnya</span>
        </button>
    </div>

    <?php include 'navbar.php'; ?>

    <script>
        function handleAbsen() {
            // Reset dulu sebelum proses
            document.getElementById('statusInput').value = '';
            document.getElementById('siftInput').value = '';

            // Sembunyikan tombol "Order" saat awal
            document.getElementById('orderButton').style.display = 'none';

            Swal.fire({
                title: 'Pilih Status Absensi',
                showDenyButton: true,
                showCancelButton: true,
                confirmButtonText: 'STAY',
                denyButtonText: 'OFF',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // STAY
                    Swal.fire({
                        title: 'Pilih Sift',
                        html: `
                    <button class="swal2-confirm swal2-styled" onclick="setSift('Pagi')">PAGI</button>
                    <button class="swal2-confirm swal2-styled" onclick="setSift('Siang')">SIANG</button>
                    <button class="swal2-confirm swal2-styled" onclick="setSift('Non')">NON</button>
                `,
                        showCancelButton: true,
                        cancelButtonText: 'Batal',
                        showConfirmButton: false
                    });
                } else if (result.isDenied) {
                    Swal.fire({
                        icon: 'question',
                        title: 'Konfirmasi',
                        text: 'Anda ingin lanjut OFF?',
                        showCancelButton: true,
                        confirmButtonText: 'Ya, lanjutkan',
                        cancelButtonText: 'Batal'
                    }).then((confirmResult) => {
                        if (confirmResult.isConfirmed) {
                            document.getElementById('statusInput').value = 'OFF';
                            document.getElementById('siftInput').value = '';

                            // Sembunyikan tombol "Order"
                            document.getElementById('orderButton').style.display = 'none';

                            // Tambahkan sedikit delay agar input sempat diperbarui sebelum submit
                            setTimeout(() => {
                                document.getElementById('absenForm').submit();
                            }, 100);
                        }
                    });
                }
            });
        }

        function setSift(value) {
            document.getElementById('siftInput').value = value;
            document.getElementById('statusInput').value = 'STAY';
            Swal.close(); // Tutup popup pilihan sift

            // Tampilkan tombol "Order"
            document.getElementById('orderButton').style.display = 'inline-block';

            // Konfirmasi untuk STAY
            Swal.fire({
                icon: 'question',
                title: 'Konfirmasi',
                text: 'Anda ingin lanjut STAY?',
                showCancelButton: true,
                confirmButtonText: 'Ya, lanjutkan',
                cancelButtonText: 'Batal'
            }).then((confirmResult) => {
                if (confirmResult.isConfirmed) {
                    document.getElementById('absenForm').submit();
                }
            });
        }

        function confirmLogout() {
            Swal.fire({
                title: 'Yakin ingin logout?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, Logout',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Hapus localStorage
                    localStorage.removeItem("userSession");

                    // Arahkan ke logout.php
                    window.location.href = "logout.php";
                }
            });
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const status = document.getElementById('statusInput').value;
            const orderBtn = document.getElementById('orderButton');

            if (status !== 'STAY') {
                orderBtn.style.display = 'none';
            } else {
                orderBtn.style.display = 'inline-block';
            }
        });
    </script>

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        include 'koneksi.php';

        $nama = $_POST['nama'];
        $tanggal = $_POST['tanggal'];
        $status = $_POST['status'];
        $sift = $_POST['sift'] ?? null;
        $waktu_sekarang = new DateTime();

        // Validasi status kosong
        if (empty($status)) {
            echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                text: 'Status absensi tidak boleh kosong.'
            }).then(() => {
                window.history.back();
            });
        </script>";
            exit;
        }

        if ($status === 'STAY' && empty($sift)) {
            echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                text: 'Sift harus dipilih untuk STAY.'
            }).then(() => {
                window.history.back();
            });
        </script>";
            exit;
        }

        // Ambil data absen hari ini
        $query = $koneksi->prepare("SELECT stay, off FROM absen WHERE nama = ? AND tanggal = ?");
        $query->bind_param("ss", $nama, $tanggal);
        $query->execute();
        $query->store_result();
        $query->bind_result($waktu_stay_db, $waktu_off_db);
        $query->fetch();

        // Validasi waktu 8 jam
        if ($status === 'STAY' && $waktu_stay_db) {
            $waktu_stay = new DateTime($waktu_stay_db);
            $selisih = $waktu_sekarang->getTimestamp() - $waktu_stay->getTimestamp();
            if ($selisih < 8 * 3600) {
                echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: 'Anda sudah melakukan STAY hari ini. Silakan tunggu minimal 8 jam sebelum STAY lagi.'
                }).then(() => {
                    window.history.back();
                });
            </script>";
                exit;
            }
        }

        if ($status === 'OFF' && $waktu_off_db) {
            $waktu_off = new DateTime($waktu_off_db);
            $selisih = $waktu_sekarang->getTimestamp() - $waktu_off->getTimestamp();
            if ($selisih < 8 * 3600) {
                echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: 'Anda sudah melakukan OFF hari ini. Silakan tunggu minimal 8 jam sebelum OFF lagi.'
                }).then(() => {
                    window.history.back();
                });
            </script>";
                exit;
            }
        }

        $query->close();

        $waktu = $waktu_sekarang->format("H:i:s");
        $cek = $koneksi->prepare("SELECT id FROM absen WHERE nama = ? AND tanggal = ?");
        $cek->bind_param("ss", $nama, $tanggal);
        $cek->execute();
        $cek->store_result();

        $success = false;

        if ($cek->num_rows > 0) {
            if ($status === 'STAY') {
                $update = $koneksi->prepare("UPDATE absen SET sift = ?, stay = ? WHERE nama = ? AND tanggal = ?");
                $update->bind_param("ssss", $sift, $waktu, $nama, $tanggal);
            } elseif ($status === 'OFF') {
                $update = $koneksi->prepare("UPDATE absen SET off = ? WHERE nama = ? AND tanggal = ?");
                $update->bind_param("sss", $waktu, $nama, $tanggal);
            }
            $success = $update->execute();
            $update->close();
        } else {
            if ($status === 'STAY') {
                $insert = $koneksi->prepare("INSERT INTO absen (nama, tanggal, sift, stay) VALUES (?, ?, ?, ?)");
                $insert->bind_param("ssss", $nama, $tanggal, $sift, $waktu);
                $success = $insert->execute();
                $insert->close();
            } else {
                echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: 'Anda belum melakukan STAY hari ini.'
                }).then(() => {
                    window.history.back();
                });
            </script>";
                exit;
            }
        }

        $cek->close();

        if ($success) {
            echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: 'Absensi berhasil disimpan.'
            }).then(() => {
                window.location.href = 'index.php';
            });
        </script>";
        } else {
            echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                text: 'Terjadi kesalahan saat menyimpan data.'
            }).then(() => {
                window.history.back();
            });
        </script>";
        }
    }
    ?>

</body>
</html>