<?php
include 'koneksi.php';

$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : date('n');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : date('Y');
$jumlah_hari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);

$today = date('Y-m-d');

// Ambil data karyawan
$karyawan = mysqli_query($conn, "SELECT rfid, nama FROM karyawan");

// Ambil data absensi
$absensi = [];
$query = mysqli_query($conn, "SELECT rfid, DATE(tanggal) as tanggal, jam_masuk, jam_pulang 
    FROM absensi 
    WHERE MONTH(tanggal) = $bulan AND YEAR(tanggal) = $tahun");

while ($row = mysqli_fetch_assoc($query)) {
    $absensi[$row['rfid']][$row['tanggal']] = [
        'masuk' => $row['jam_masuk'],
        'pulang' => $row['jam_pulang']
    ];
}

// Buat thead
$thead = "<tr class='header-nama'>";
$thead .= "<th class='sticky-col sticky-col-header' rowspan='2'>Nama</th>";
$thead .= "<th class='header-tanggal' colspan='{$jumlah_hari}'>Tanggal</th>";
$thead .= "</tr><tr class='header-tanggal'>";
for ($tgl = 1; $tgl <= $jumlah_hari; $tgl++) {
    $thead .= "<th>{$tgl}</th>";
}
$thead .= "</tr>";

// Buat tbody
$tbody = '';
while ($row = mysqli_fetch_assoc($karyawan)) {
    $tbody .= "<tr>";
    $tbody .= "<td class='sticky-col'>{$row['nama']}</td>";

    for ($tgl = 1; $tgl <= $jumlah_hari; $tgl++) {
        $tanggal = sprintf('%04d-%02d-%02d', $tahun, $bulan, $tgl);
        $hari = date('N', strtotime($tanggal)); // 6 = Sabtu, 7 = Minggu

        // Tanggal ke depan, tampil abu
        if ($tanggal > $today) {
            $tbody .= "<td style='background-color: #e0e0e0; color: #999;'>-</td>";
        }
        // Sabtu/Minggu
        elseif ($hari == 6 || $hari == 7) {
            $tbody .= "<td style='background-color: #000; color: white;'>X</td>";
        }
        // Hari kerja, evaluasi absensi
        else {
            $status = '';
            if (isset($absensi[$row['rfid']][$tanggal])) {
                $data = $absensi[$row['rfid']][$tanggal];
                if ($data['masuk'] && $data['pulang']) {
                    $status = 'hadir';
                } elseif ($data['masuk']) {
                    $status = 'masuk';
                } else {
                    $status = 'tidak_masuk';
                }
            } else {
                $status = 'tidak_masuk';
            }

            if ($status == 'hadir') {
                $tbody .= "<td style='background-color: #28a745; color: white;'>✔</td>";
            } elseif ($status == 'masuk') {
                $tbody .= "<td style='background-color: #ffc107; color: black;'>●</td>";
            } else {
                $tbody .= "<td style='background-color: #dc3545; color: white;'>-</td>";
            }
        }
    }

    $tbody .= "</tr>";
}

// Kirim JSON
echo json_encode([
    'thead' => $thead,
    'tbody' => $tbody
]);
?>
