<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/functions.php';

// Cek login
cek_login();

// Cek akses
if (!cek_akses('absensi', 'report')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Filter
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : date('m');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : date('Y');
$karyawan_id = isset($_GET['karyawan_id']) ? (int)$_GET['karyawan_id'] : 0;

// Ambil daftar karyawan untuk filter
$query_karyawan = "SELECT id, nik, nama FROM karyawan WHERE status = 'aktif' ORDER BY nama ASC";
$result_karyawan = mysqli_query($conn, $query_karyawan);

$jumlah_hari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
$pengaturan = get_pengaturan();

$query = "SELECT k.id, k.nik, k.nama, k.jabatan, k.departemen,
          COUNT(CASE WHEN a.status = 'hadir' THEN 1 END) as hadir,
          COUNT(CASE WHEN a.status = 'izin' THEN 1 END) as izin,
          COUNT(CASE WHEN a.status = 'sakit' THEN 1 END) as sakit,
          COUNT(CASE WHEN a.status = 'cuti' THEN 1 END) as cuti,
          COUNT(CASE WHEN a.status = 'alpha' THEN 1 END) as alpha,
          SUM(CASE WHEN a.jam_masuk > '{$pengaturan['jam_masuk']}' THEN 1 ELSE 0 END) as terlambat
          FROM karyawan k
          LEFT JOIN absensi a ON k.id = a.karyawan_id AND MONTH(a.tanggal) = $bulan AND YEAR(a.tanggal) = $tahun
          WHERE k.status = 'aktif'";

if ($karyawan_id > 0) {
    $query .= " AND k.id = $karyawan_id";
}
$query .= " GROUP BY k.id, k.nik, k.nama, k.jabatan, k.departemen ORDER BY k.nama ASC";
$result = mysqli_query($conn, $query);
$print_mode = isset($_GET['print']) && $_GET['print'] == 'true';

if (!$print_mode) {
    require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/header.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/sidebar.php';
}
?>

<?php if ($print_mode): ?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Absensi - <?php echo date('F Y', mktime(0, 0, 0, $bulan, 1, $tahun)); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @media print {
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .no-print { display: none !important; }
        }
    </style>
</head>
<body class="bg-white p-8" onload="window.print()">
    <div class="container mx-auto">
        <header class="text-center mb-8">
            <h1 class="text-3xl font-bold"><?php echo htmlspecialchars($pengaturan['nama_perusahaan']); ?></h1>
            <p class="text-gray-600"><?php echo htmlspecialchars($pengaturan['alamat']); ?></p>
            <div class="h-px bg-gray-300 my-4"></div>
            <h2 class="text-2xl font-semibold">LAPORAN REKAPITULASI ABSENSI</h2>
            <p class="text-lg">Periode: <?php echo date('F Y', mktime(0, 0, 0, $bulan, 1, $tahun)); ?></p>
        </header>
<?php else: ?>
<div class="main-content flex-1 p-8">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
        <div>
            <h2 class="text-3xl font-bold text-white">Laporan Absensi</h2>
            <p class="text-slate-400">Rekapitulasi absensi karyawan per periode.</p>
        </div>
        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?print=true&bulan=<?php echo $bulan; ?>&tahun=<?php echo $tahun; ?>&karyawan_id=<?php echo $karyawan_id; ?>" target="_blank" class="bg-teal-600 hover:bg-teal-700 text-white font-bold py-2.5 px-5 rounded-lg transition-colors flex items-center gap-2">
            <i class="fas fa-print"></i> Cetak Laporan
        </a>
    </div>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg mb-6">
        <form action="" method="GET" class="flex flex-wrap items-end gap-4">
            <div class="flex-grow min-w-[200px]">
                <label for="karyawan_id" class="block text-slate-400 text-sm font-medium mb-2">Karyawan</label>
                <select name="karyawan_id" id="karyawan_id" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    <option value="0">Semua Karyawan</option>
                    <?php mysqli_data_seek($result_karyawan, 0); while ($row = mysqli_fetch_assoc($result_karyawan)): ?>
                    <option value="<?php echo $row['id']; ?>" <?php echo ($karyawan_id == $row['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($row['nama']) . ' (' . htmlspecialchars($row['nik']) . ')'; ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div>
                <label for="bulan" class="block text-slate-400 text-sm font-medium mb-2">Bulan</label>
                <select name="bulan" id="bulan" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    <?php for ($i = 1; $i <= 12; $i++): ?><option value="<?php echo $i; ?>" <?php echo ($bulan == $i) ? 'selected' : ''; ?>><?php echo date('F', mktime(0, 0, 0, $i, 1)); ?></option><?php endfor; ?>
                </select>
            </div>
            <div>
                <label for="tahun" class="block text-slate-400 text-sm font-medium mb-2">Tahun</label>
                <select name="tahun" id="tahun" class="w-full border border-slate-600 bg-slate-700/50 text-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 px-3 py-2.5">
                    <?php for ($i = date('Y') - 5; $i <= date('Y'); $i++): ?><option value="<?php echo $i; ?>" <?php echo ($tahun == $i) ? 'selected' : ''; ?>><?php echo $i; ?></option><?php endfor; ?>
                </select>
            </div>
            <button type="submit" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors flex items-center gap-2"><i class="fas fa-filter"></i> Filter</button>
        </form>
    </div>
<?php endif; ?>
        
    <div class="<?php echo !$print_mode ? 'glass-effect p-6 rounded-xl shadow-lg' : '' ?>">
        <div class="overflow-x-auto">
            <table class="w-full text-left table-auto">
                <thead>
                    <tr class="<?php echo $print_mode ? 'bg-gray-100' : 'border-b border-slate-700'; ?>">
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold">No</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold">Nama</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold">Jabatan</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Hadir</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Izin</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Sakit</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Cuti</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Alpha</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">Terlambat</th>
                        <th class="px-4 py-3 <?php echo $print_mode ? 'text-gray-800' : 'text-slate-300'; ?> font-semibold text-center">% Hadir</th>
                    </tr>
                </thead>
                <tbody class="<?php echo $print_mode ? 'text-gray-700' : 'text-slate-400'; ?>">
                    <?php if (mysqli_num_rows($result) > 0): $no = 1; while ($row = mysqli_fetch_assoc($result)): ?>
                    <?php 
                        $kehadiran_efektif = $row['hadir'] + $row['sakit'] + $row['izin'] + $row['cuti'];
                        $persentase = ($jumlah_hari > 0) ? ($kehadiran_efektif / $jumlah_hari) * 100 : 0;
                    ?>
                    <tr class="<?php echo !$print_mode ? 'hover:bg-slate-800/50' : ''; ?>">
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?>"><?php echo $no++; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?>">
                            <p class="<?php echo !$print_mode ? 'font-medium text-slate-200' : ''; ?>"><?php echo htmlspecialchars($row['nama']); ?></p>
                            <p class="<?php echo $print_mode ? 'text-xs' : 'text-xs text-slate-500'; ?>"><?php echo htmlspecialchars($row['nik']); ?></p>
                        </td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?>"><?php echo htmlspecialchars($row['jabatan']); ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['hadir']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['izin']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['sakit']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['cuti']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['alpha']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center"><?php echo (int)$row['terlambat']; ?></td>
                        <td class="px-4 py-3 border-b <?php echo $print_mode ? 'border-gray-200' : 'border-slate-800'; ?> text-center">
                            <span class="<?php echo ($persentase >= 90) ? 'text-green-500' : (($persentase >= 70) ? 'text-yellow-500' : 'text-red-500'); ?> font-bold">
                                <?php echo number_format($persentase, 1); ?>%
                            </span>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="10" class="px-4 py-10 text-center text-slate-500">Tidak ada data untuk ditampilkan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
        
<?php if ($print_mode): ?>
    <footer class="mt-12">
        <div class="flex justify-end">
            <div class="text-center">
                <p>Tangerang, <?php echo tanggal_indo(date('Y-m-d')); ?></p>
                <p class="mt-2">Disetujui oleh,</p>
                <div class="h-24"></div>
                <p class="font-bold underline">Manajer HRD</p>
                <p><?php echo htmlspecialchars($pengaturan['nama_perusahaan']); ?></p>
            </div>
        </div>
    </footer>
    </div>
</body>
</html>
<?php else: ?>
</div>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/footer.php'; ?>
<?php endif; ?>