<?php
session_start();
require_once '../koneksi.php';
require_once '../auth.php';
cekAdminAtauGuru();

// 1. Ambil data semester aktif
$q_aktif = mysqli_query($koneksi, "SELECT s.id_semester, t.id_tp_tahun, s.nama_semester FROM semester s JOIN tahun_pelajaran t ON t.status = 'Aktif' WHERE s.status = 'Aktif' LIMIT 1");
$d_aktif = mysqli_fetch_assoc($q_aktif);

$id_semester = $d_aktif['id_semester'] ?? '1';
$id_tp       = $d_aktif['id_tp_tahun'] ?? '1';
$nama_sem    = $d_aktif['nama_semester'] ?? 'Ganjil';

// 2. Query Kelas - Hanya menampilkan kelas milik guru yang login
if ($_SESSION['role'] == 'admin') {
    $sql_kelas = "SELECT DISTINCT r.id_rombel, r.kelas FROM rombel r JOIN anggota_rombel ar ON r.id_rombel = ar.id_rombel WHERE ar.id_semester = '$id_semester' AND ar.id_tp_tahun = '$id_tp' ORDER BY r.kelas ASC";
} else {
    $id_guru_login = mysqli_real_escape_string($koneksi, $_SESSION['id_guru'] ?? '0');
    $sql_kelas = "SELECT id_rombel, kelas FROM rombel WHERE wali_kelas = '$id_guru_login' ORDER BY kelas ASC";
}
$q_k = mysqli_query($koneksi, $sql_kelas);

$id_rombel = $_GET['id_rombel'] ?? '';
$menu      = $_GET['menu'] ?? 'input';
$bulan     = $_GET['bulan'] ?? date('m');
$tahun     = $_GET['tahun'] ?? date('Y');

include 'layout.php';
?>

<div class="container-fluid p-4">
    <h3>Absensi Siswa (Semester: <?= htmlspecialchars($nama_sem) ?>)</h3>
    
    <div class="d-flex gap-2 mb-4 no-print">
        <a href="?menu=input&id_rombel=<?=$id_rombel?>" class="btn btn-primary">Input Harian</a>
        <a href="?menu=rekap_bulanan&id_rombel=<?=$id_rombel?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="btn btn-info text-white">Rekap Bulanan</a>
    </div>

    <div class="card p-3 mb-4 no-print">
        <form method="GET" class="row g-2 align-items-center">
            <input type="hidden" name="menu" value="<?= htmlspecialchars($menu) ?>">
            <div class="col-md-3">
                <select name="id_rombel" class="form-select" onchange="this.form.submit()">
                    <option value="">-- Pilih Kelas --</option>
                    <?php while($k = mysqli_fetch_array($q_k)) {
                        $sel = ($k['id_rombel'] == $id_rombel) ? 'selected' : '';
                        echo "<option value='{$k['id_rombel']}' $sel>{$k['kelas']}</option>";
                    } ?>
                </select>
            </div>
            
            <?php if($menu == 'rekap_bulanan'): ?>
                <div class="col-md-2"><select name="bulan" class="form-select" onchange="this.form.submit()"><?php for($m=1; $m<=12; $m++): $m_val = str_pad($m, 2, '0', STR_PAD_LEFT); ?><option value="<?=$m_val?>" <?=($m_val==$bulan?'selected':'')?>><?=date('F', mktime(0,0,0,$m,1))?></option><?php endfor; ?></select></div>
                <div class="col-md-2"><input type="number" name="tahun" class="form-control" value="<?=$tahun?>" onchange="this.form.submit()"></div>
            <?php endif; ?>

            <?php if (!empty($id_rombel)): ?>
                <div class="col-md-auto d-flex gap-2">
                    <a href="cetak_absensi.php?id_rombel=<?=$id_rombel?>&menu=<?=$menu?>&bulan=<?=$bulan?>&tahun=<?=$tahun?>" class="btn btn-warning" target="_blank"><i class="fa fa-print"></i> Cetak Absensi</a>
                    
                </div>
            <?php endif; ?>
        </form>
    </div>

    <?php 
    if (!empty($id_rombel)): 
        $id_guru_login = $_SESSION['id_guru'];
        $akses_query = ($_SESSION['role'] == 'admin') ? "id_rombel = '$id_rombel'" : "id_rombel = '$id_rombel' AND wali_kelas = '$id_guru_login'";
        $cek_akses = mysqli_query($koneksi, "SELECT id_rombel FROM rombel WHERE $akses_query");

        if (mysqli_num_rows($cek_akses) > 0) {
            $q_siswa = mysqli_query($koneksi, "SELECT s.id_siswa, s.nama FROM master_siswa s JOIN anggota_rombel ar ON s.id_siswa = ar.id_siswa WHERE ar.id_rombel = '$id_rombel' AND ar.id_semester = '$id_semester' AND ar.id_tp_tahun = '$id_tp' ORDER BY s.nama ASC");
            
            if ($menu == 'input'): ?>
                <form method='POST' action='simpan_absensi.php'>
                    <input type='hidden' name='id_rombel' value='<?=$id_rombel?>'>
                    <div class="mb-3"><label>Tanggal:</label> <input type="date" name="tanggal" class="form-control" style="width: 200px;" value="<?=date('Y-m-d')?>" required></div>
                    <table class='table table-bordered bg-white'><thead><tr><th>Nama Siswa</th><th>Keterangan</th></tr></thead><tbody>
                    <?php while($s = mysqli_fetch_array($q_siswa)): ?>
                        <tr><td><?=$s['nama']?></td><td><select name='status[<?=$s['id_siswa']?>]' class='form-select'><option value='H'>Hadir</option><option value='S'>Sakit</option><option value='I'>Izin</option><option value='A'>Alfa</option></select></td></tr>
                    <?php endwhile; ?>
                    </tbody></table>
                    <button type='submit' class='btn btn-success'>Simpan Absensi</button>
                </form>
            <?php elseif ($menu == 'rekap_bulanan'): ?>
                <div class='table-responsive'><table class='table table-bordered table-sm'><thead><tr><th>Nama</th><?php for($d=1; $d<=cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun); $d++) echo "<th>$d</th>"; ?></tr></thead><tbody>
                <?php while($s = mysqli_fetch_array($q_siswa)) { echo "<tr><td>{$s['nama']}</td>"; for($d=1; $d<=cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun); $d++) echo "<td>-</td>"; echo "</tr>"; } ?>
                </tbody></table></div>
            <?php endif; 
        } else {
            echo "<div class='alert alert-danger'>Akses ditolak: Anda tidak memiliki akses ke kelas ini.</div>";
        }
    endif; ?>
</div>

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