<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'wali_kelas') {
    header("Location: index.php");
    exit;
}

include 'config.php';
date_default_timezone_set("Asia/Jakarta");

// Ambil kelas yang diampu oleh wali kelas
$username = $_SESSION['username'];
$wali_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT kelas FROM wali_kelas WHERE nip_wali='$username' LIMIT 1"));
$kelas_diampu = $wali_kelas['kelas'] ?? '';

if (empty($kelas_diampu)) {
    die("<script>alert('Anda tidak memiliki kelas yang diampu!'); window.location='dashboard_wali_kelas.php';</script>");
}

$tanggal = $_GET['tanggal'] ?? date('Y-m-d');

// Ubah atau tambah data absensi per siswa
if (isset($_POST['ubah'])) {
  $siswa_id = $_POST['siswa_id'];
  $status = $_POST['status'];
  $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);

  $cek = mysqli_query($conn, "SELECT id FROM absensi WHERE siswa_id=$siswa_id AND tanggal='$tanggal'");
  if (mysqli_num_rows($cek) > 0) {
    mysqli_query($conn, "UPDATE absensi SET status='$status', keterangan='$keterangan' WHERE siswa_id=$siswa_id AND tanggal='$tanggal'");
  } else {
    mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, status, keterangan) VALUES ($siswa_id, '$tanggal', '$status', '$keterangan')");
  }
  header("Location: absensi_kelas.php?tanggal=$tanggal");
  exit;
}

// Tombol Hadir Semua
if (isset($_POST['hadir_semua'])) {
  $qsiswa = mysqli_query($conn, "SELECT id FROM siswa WHERE kelas='$kelas_diampu' AND status='aktif'");
  while ($s = mysqli_fetch_assoc($qsiswa)) {
    $siswa_id = $s['id'];
    $cek = mysqli_query($conn, "SELECT id FROM absensi WHERE siswa_id=$siswa_id AND tanggal='$tanggal'");
    if (mysqli_num_rows($cek) > 0) {
      mysqli_query($conn, "UPDATE absensi SET status='H', keterangan='' WHERE siswa_id=$siswa_id AND tanggal='$tanggal'");
    } else {
      mysqli_query($conn, "INSERT INTO absensi (siswa_id, tanggal, status, keterangan) VALUES ($siswa_id, '$tanggal', 'H', '')");
    }
  }
  header("Location: absensi_kelas.php?tanggal=$tanggal");
  exit;
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Input S/I/A - Kelas <?php echo $kelas_diampu; ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .status-H { background-color: #d4edda !important; }
    .status-A { background-color: #f8d7da !important; }
    .status-I { background-color: #fff3cd !important; }
    .status-S { background-color: #d1ecf1 !important; }
  </style>
</head>
<body class="container mt-4">
  <h2>Input S/I/A - Kelas <?php echo $kelas_diampu; ?></h2>
  <a href="dashboard_wali_kelas.php" class="btn btn-secondary mb-3">← Kembali</a>

  <form method="get" class="mb-3 row g-2 align-items-center">
    <div class="col-auto">
      <label for="tanggal" class="form-label mb-0">Tanggal:</label>
      <input type="date" name="tanggal" value="<?= $tanggal ?>" class="form-control">
    </div>
    <div class="col-auto">
      <button class="btn btn-primary">Tampilkan</button>
    </div>
  </form>

  <!-- Tombol Hadir Semua -->
  <form method="post" class="mb-3">
    <button type="submit" name="hadir_semua" class="btn btn-success">
      ✅ Tandai Semua Hadir (H)
    </button>
    <small class="text-muted ms-2">* Akan menandai semua siswa sebagai Hadir</small>
  </form>

  <div class="table-responsive">
    <table class="table table-bordered table-sm">
      <thead class="table-light">
        <tr>
          <th>No</th>
          <th>NIS</th>
          <th>Nama</th>
          <th>Kelas</th>
          <th>Status</th>
          <th>Keterangan</th>
          <th>Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $q = mysqli_query($conn, "
          SELECT s.id AS siswa_id, s.nis, s.nama, s.kelas,
                 a.id AS absen_id, a.status, a.keterangan
          FROM siswa s
          LEFT JOIN absensi a ON a.siswa_id = s.id AND a.tanggal = '$tanggal'
          WHERE s.kelas = '$kelas_diampu' AND s.status='aktif'
          ORDER BY s.nama
        ");
        
        $no = 1;
        while ($d = mysqli_fetch_assoc($q)) {
          $status = $d['status'] ?? 'A'; // Default Alpha jika tidak ada data
          $rowClass = "status-$status";
          ?>
          <tr class="<?= $rowClass ?>">
            <form method="post">
              <input type="hidden" name="siswa_id" value="<?= $d['siswa_id'] ?>">
              <td><?= $no ?></td>
              <td><?= $d['nis'] ?></td>
              <td><?= $d['nama'] ?></td>
              <td><?= $d['kelas'] ?></td>
              <td>
                <select name="status" class="form-select form-select-sm">
                  <option value="H" <?= $status == 'H' ? 'selected' : '' ?>>H - Hadir</option>
                  <option value="S" <?= $status == 'S' ? 'selected' : '' ?>>S - Sakit</option>
                  <option value="I" <?= $status == 'I' ? 'selected' : '' ?>>I - Izin</option>
                  <option value="A" <?= $status == 'A' ? 'selected' : '' ?>>A - Alpha</option>
                </select>
              </td>
              <td>
                <input type="text" name="keterangan" class="form-control form-control-sm" value="<?= $d['keterangan'] ?? '' ?>" placeholder="Keterangan...">
              </td>
              <td>
                <button type="submit" name="ubah" class="btn btn-sm btn-success">
                  <?= $d['absen_id'] ? '💾 Update' : '➕ Tambah' ?>
                </button>
              </td>
            </form>
          </tr>
          <?php
          $no++;
        }
        ?>
      </tbody>
    </table>
  </div>

  <div class="mt-3">
    <div class="alert alert-info">
      <strong>Keterangan Warna:</strong>
      <span class="badge bg-success">Hijau = Hadir</span>
      <span class="badge bg-danger">Merah = Alpha</span>
      <span class="badge bg-warning">Kuning = Izin</span>
      <span class="badge bg-info">Biru = Sakit</span>
    </div>
  </div>
</body>
</html>