<?php
session_start();
include 'koneksi.php';

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

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['rfid'])) {
    $rfid = $_POST['rfid'];
    $foto_kehadiran = isset($_POST['foto_kehadiran']) ? $_POST['foto_kehadiran'] : null;
    $foto_kepulangan = isset($_POST['foto_kepulangan']) ? $_POST['foto_kepulangan'] : null;
    $now = new DateTime("now", new DateTimeZone("Asia/Jakarta"));
    $jam = $now->format('H:i:s');
    $tanggal = $now->format('Y-m-d');

// Ambil jam masuk dan pulang dari database
$jamSet = mysqli_query($conn, "SELECT jam_masuk, jam_pulang FROM pengaturan_jam LIMIT 1");
if ($row = mysqli_fetch_assoc($jamSet)) {
    $jamMasukDeadline = new DateTime($row['jam_masuk'], new DateTimeZone("Asia/Jakarta"));
    $jamPulangBatas = new DateTime($row['jam_pulang'], new DateTimeZone("Asia/Jakarta"));
} else {
    // Default fallback jika tidak ada data
    $jamMasukDeadline = new DateTime('08:00:00', new DateTimeZone("Asia/Jakarta"));
    $jamPulangBatas = new DateTime('15:00:00', new DateTimeZone("Asia/Jakarta"));
}

    $jamSekarang = new DateTime($jam, new DateTimeZone("Asia/Jakarta"));

    $result_absen = mysqli_query($conn, "SELECT * FROM absensi WHERE rfid='$rfid' AND tanggal='$tanggal' AND jam_pulang IS NULL");

    if (mysqli_num_rows($result_absen) > 0) {
        // Cek apakah sudah boleh absen pulang
        if ($jamSekarang >= $jamPulangBatas) {
            $absen = mysqli_fetch_assoc($result_absen);
            $id_absen = $absen['id'];
            mysqli_query($conn, "UPDATE absensi SET jam_pulang='$jam', foto_kepulangan='$foto_kepulangan' WHERE id='$id_absen'");
            echo "Pulang: " . $jam;
        } else {
            echo "Belum waktunya pulang!";
        }
    } else {
        // Cek status kehadiran
        $status = ($jamSekarang > $jamMasukDeadline) ? 'Terlambat' : 'Tepat Waktu';

        // Input absen masuk dengan foto kehadiran
        mysqli_query($conn, "INSERT INTO absensi (rfid, nama, jabatan, tanggal, jam_masuk, status_kehadiran, foto_kehadiran) 
                             SELECT rfid, nama, jabatan, '$tanggal', '$jam', '$status', '$foto_kehadiran' FROM karyawan WHERE rfid='$rfid'");
        echo "Masuk: " . $jam . " ($status)";
    }

    exit();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Absensi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            min-height: 100vh;
            display: flex;
            font-family: 'Poppins', sans-serif;
            background-color: #f4f6f9;
        }
        .sidebar {
            width: 250px;
            background-color: #1f2d3d;
            color: white;
            display: flex;
            flex-direction: column;
            padding-top: 20px;
        }
        .sidebar a {
            color: #cfd8dc;
            text-decoration: none;
            display: flex;
            align-items: center;
            padding: 12px 20px;
        }
        .sidebar a:hover, .sidebar a.active {
            background-color: #273746;
            color: white;
        }
        .content {
            flex-grow: 1;
            padding: 30px;
        }
        .table thead {
            background-color: #1f2d3d;
            color: white;
        }
        .foto {
            max-width: 100px;
            height: auto;
        }
    </style>
</head>
<body>

<div class="sidebar">
    <h4 class="text-center text-white mb-4">ABSENSI RFID</h4>
    <a href="index.php"><i class="bi bi-house-door-fill"></i> Beranda</a>
    <a href="karyawan.php"><i class="bi bi-people-fill"></i> Data Karyawan</a>
    <a href="absensi.php" class="active"><i class="bi bi-clock-fill"></i> Absensi</a>
    <a href="rekap.php"><i class="bi bi-card-checklist"></i> Rekap Absensi</a>
      <a href="atur_jam.php"><i class="bi bi-clock-history"></i> Set Jam Masuk / Pulang</a> <!-- Tambahan tab baru -->
    <div class="mt-auto">
        <hr class="bg-secondary">
        <a href="logout.php"><i class="bi bi-box-arrow-right"></i> Logout</a>
    </div>
</div>

<div class="content">
    <h3>Absensi</h3>

    <!-- Tabel Absensi -->
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>No</th>
                <th>RFID</th>
                <th>Nama</th>
                <th>Jabatan</th>
                <th>Jam Masuk</th>
                <th>Status</th>
                <th>Jam Pulang</th>
                <th>Foto Kehadiran</th>
                <th>Foto Kepulangan</th>
            </tr>
        </thead>
        <tbody id="absensiTable">
            <!-- Data Absensi Akan Dimasukkan Secara Dinamis dengan AJAX -->
        </tbody>
    </table>

<!-- Script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Fungsi untuk mengambil data absensi secara real-time
    function getAbsensiData() {
        fetch('get_absensi.php')
            .then(res => res.json())
            .then(data => {
                const absensiTable = document.getElementById('absensiTable');
                absensiTable.innerHTML = '';
                data.forEach((item, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${item.rfid}</td>
                        <td>${item.nama}</td>
                        <td>${item.jabatan}</td>
                        <td>${item.jam_masuk}</td>
                        <td>${item.status_kehadiran}</td>
                        <td>${item.jam_pulang ? item.jam_pulang : 'Belum Pulang'}</td>
                        <td>${item.foto_kehadiran ? `<img src="data:image/jpeg;base64,${item.foto_kehadiran}" class="foto">` : 'Tidak Ada'}</td>
                        <td>${item.foto_kepulangan ? `<img src="data:image/jpeg;base64,${item.foto_kepulangan}" class="foto">` : 'Tidak Ada'}</td>
                    `;
                    absensiTable.appendChild(row);
                });
            });
    }

    // Polling setiap 3 detik untuk mengambil data absensi terbaru
    setInterval(getAbsensiData, 1000);

    // Simulasi pengambilan data log absensi dari RFID
    setInterval(() => {
        fetch('get_log_absen.php')
            .then(res => res.json())
            .then(data => {
                if (data.rfid) {
                    // Kirim data RFID ke server untuk absen
                    fetch('absensi.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: `rfid=${data.rfid}&foto_kehadiran=${data.foto_kehadiran}&foto_kepulangan=${data.foto_kepulangan}`
                    })
                    .then(res => res.text())
                    .then(response => {
                        console.log(response); // Debug response
                    });
                }
            });
    }, 3000);
</script>

</body>
</html>
