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

// Cek login
cek_login();

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

$karyawan_id = 0;
$restrict_to_self = false;
if ($_SESSION['role'] == 'karyawan') {
    $user_id = $_SESSION['user_id'];
    $karyawan = get_karyawan_by_user($user_id);
    if ($karyawan) {
        $karyawan_id = $karyawan['id'];
        $restrict_to_self = true;
    } else {
        header("Location: " . BASE_URL . "/index.php?error=" . urlencode("Data karyawan Anda belum terdaftar."));
        exit();
    }
} else {
    $karyawan_id = isset($_GET['karyawan_id']) ? (int)$_GET['karyawan_id'] : 0;
}

$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : date('m');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : date('Y');
$where = "WHERE MONTH(a.tanggal) = $bulan AND YEAR(a.tanggal) = $tahun";

if ($restrict_to_self) {
    $where = "WHERE a.karyawan_id = $karyawan_id AND MONTH(a.tanggal) = $bulan AND YEAR(a.tanggal) = $tahun";
} elseif ($karyawan_id > 0) {
    $where .= " AND a.karyawan_id = $karyawan_id";
}

$query = "SELECT a.*, k.nik, k.nama, k.jabatan 
          FROM absensi a JOIN karyawan k ON a.karyawan_id = k.id 
          $where ORDER BY a.tanggal DESC, k.nama ASC";
$result = mysqli_query($conn, $query);

$query_karyawan = "SELECT id, nik, nama FROM karyawan WHERE status = 'aktif' ORDER BY nama ASC";
$result_karyawan = mysqli_query($conn, $query_karyawan);
$pengaturan = get_pengaturan();
?>

<div class="main-content flex-1 p-8">
    <div class="mb-6">
        <h2 class="text-3xl font-bold text-white">Riwayat Absensi</h2>
        <p class="text-slate-400">Menampilkan riwayat dan rekapitulasi kehadiran per bulan.</p>
    </div>

    <div class="glass-effect p-6 rounded-xl shadow-lg mb-8">
        <form action="" method="GET" class="flex flex-wrap items-end gap-4">
            <?php if (!$restrict_to_self): ?>
            <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 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>
            <?php endif; ?>
            <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>
            <div class="flex items-end">
                <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>
            </div>
        </form>
    </div>
    
    <div class="glass-effect p-6 rounded-xl shadow-lg mb-8">
        <div class="overflow-x-auto">
            <table class="w-full text-left table-auto">
                <thead>
                    <tr class="border-b border-slate-700">
                        <th class="px-4 py-3 text-slate-300 font-semibold">No</th>
                        <?php if (!$restrict_to_self && $karyawan_id == 0): ?><th class="px-4 py-3 text-slate-300 font-semibold">Nama</th><?php endif; ?>
                        <th class="px-4 py-3 text-slate-300 font-semibold">Tanggal</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold">Jam Masuk</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold">Jam Keluar</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold text-center">Status</th>
                        <th class="px-4 py-3 text-slate-300 font-semibold">Keterangan</th>
                    </tr>
                </thead>
                <tbody class="text-slate-400">
                    <?php if (mysqli_num_rows($result) > 0): $no = 1; while ($row = mysqli_fetch_assoc($result)): ?>
                    <tr class="hover:bg-slate-800/50">
                        <td class="px-4 py-3 border-b border-slate-800"><?php echo $no++; ?></td>
                        <?php if (!$restrict_to_self && $karyawan_id == 0): ?>
                        <td class="px-4 py-3 border-b border-slate-800">
                            <p class="font-medium text-slate-200"><?php echo htmlspecialchars($row['nama']); ?></p>
                            <p class="text-xs"><?php echo htmlspecialchars($row['nik']); ?></p>
                        </td>
                        <?php endif; ?>
                        <td class="px-4 py-3 border-b border-slate-800"><?php echo tanggal_indo($row['tanggal']); ?><p class="text-xs"><?php echo date('l', strtotime($row['tanggal'])); ?></p></td>
                        <td class="px-4 py-3 border-b border-slate-800 <?php echo ($row['status']=='hadir' && $row['jam_masuk'] > $pengaturan['jam_masuk']) ? 'text-red-400 font-bold' : ''; ?>">
                            <?php echo $row['jam_masuk'] ?: '-'; ?>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800"><?php echo $row['jam_keluar'] ?: '-'; ?></td>
                        <td class="px-4 py-3 border-b border-slate-800 text-center">
                            <span class="px-3 py-1 text-xs font-semibold rounded-full <?php switch ($row['status']) { case 'hadir': echo 'bg-green-500/20 text-green-300'; break; case 'izin': echo 'bg-blue-500/20 text-blue-300'; break; case 'sakit': echo 'bg-yellow-500/20 text-yellow-300'; break; case 'cuti': echo 'bg-purple-500/20 text-purple-300'; break; case 'alpha': echo 'bg-red-500/20 text-red-300'; break; default: echo 'bg-gray-500/20 text-gray-300'; } ?>"><?php echo ucfirst($row['status']); ?></span>
                        </td>
                        <td class="px-4 py-3 border-b border-slate-800"><?php echo htmlspecialchars($row['keterangan'] ?: '-'); ?></td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="<?php echo (!$restrict_to_self && $karyawan_id == 0) ? '7' : '6'; ?>" class="px-4 py-10 text-center text-slate-500">Tidak ada data absensi.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php if ($karyawan_id > 0): ?>
    <?php
    $query_stats = "SELECT 
                       SUM(CASE WHEN status = 'hadir' THEN 1 ELSE 0 END) as total_hadir,
                       SUM(CASE WHEN status = 'izin' THEN 1 ELSE 0 END) as total_izin,
                       SUM(CASE WHEN status = 'sakit' THEN 1 ELSE 0 END) as total_sakit,
                       SUM(CASE WHEN status = 'cuti' THEN 1 ELSE 0 END) as total_cuti,
                       SUM(CASE WHEN status = 'alpha' THEN 1 ELSE 0 END) as total_alpha,
                       SUM(CASE WHEN jam_masuk > '{$pengaturan['jam_masuk']}' THEN 1 ELSE 0 END) as total_telat
                    FROM absensi WHERE karyawan_id = $karyawan_id AND MONTH(tanggal) = $bulan AND YEAR(tanggal) = $tahun";
    $result_stats = mysqli_query($conn, $query_stats);
    $stats = mysqli_fetch_assoc($result_stats);
    ?>
    <div class="glass-effect p-6 rounded-xl shadow-lg">
        <h3 class="text-xl font-semibold text-white mb-4">Ringkasan Absensi Bulan <?php echo date('F Y', mktime(0, 0, 0, $bulan, 1, $tahun)); ?></h3>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-green-400 mb-2">Hadir</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_hadir']; ?></p></div>
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-blue-400 mb-2">Izin</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_izin']; ?></p></div>
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-yellow-400 mb-2">Sakit</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_sakit']; ?></p></div>
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-purple-400 mb-2">Cuti</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_cuti']; ?></p></div>
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-red-400 mb-2">Alpha</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_alpha']; ?></p></div>
            <div class="bg-slate-700/50 border border-slate-600 rounded-lg p-4 text-center"><h4 class="text-sm font-medium text-orange-400 mb-2">Terlambat</h4><p class="text-3xl font-bold text-white"><?php echo (int)$stats['total_telat']; ?></p></div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/footer.php';
?>