<?php
/**
 * SisPen Snesaka - Input Absensi
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle  = 'Input Absensi';
$activeMenu = 'absensi';
$pengaturan = getPengaturan();
$ta         = $pengaturan['tahun_ajaran_aktif'];
$sem        = $pengaturan['semester_aktif'];
$isAdmin    = $_SESSION['role'] === 'admin';

// Handle AJAX save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_absensi'])) {
    header('Content-Type: application/json');
    $kelasId  = intval($_POST['kelas_id']);
    $siswaId  = intval($_POST['siswa_id']);
    $sakit    = intval($_POST['sakit'] ?? 0);
    $izin     = intval($_POST['izin'] ?? 0);
    $alpha    = intval($_POST['alpha'] ?? 0);

    $existing = db_fetch(
        "SELECT id FROM absensi WHERE siswa_id=? AND kelas_id=? AND tahun_ajaran=? AND semester=?",
        [$siswaId, $kelasId, $ta, $sem]
    );
    if ($existing) {
        db_update('absensi',
            array('sakit'=>$sakit,'izin'=>$izin,'tanpa_keterangan'=>$alpha),
            'id=:id', array('id'=>$existing['id'])
        );
    } else {
        db_insert('absensi', array(
            'siswa_id'=>$siswaId,'kelas_id'=>$kelasId,
            'tahun_ajaran'=>$ta,'semester'=>$sem,
            'sakit'=>$sakit,'izin'=>$izin,'tanpa_keterangan'=>$alpha
        ));
    }
    echo json_encode(array('ok'=>true));
    exit;
}

// Handle save semua (bulk POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_save'])) {
    $kelasId = intval($_POST['kelas_id']);
    $rows    = $_POST['rows'] ?? array();
    foreach ($rows as $siswaId => $val) {
        $siswaId = intval($siswaId);
        $sakit   = intval($val['sakit']  ?? 0);
        $izin    = intval($val['izin']   ?? 0);
        $alpha   = intval($val['alpha']  ?? 0);
        $existing = db_fetch(
            "SELECT id FROM absensi WHERE siswa_id=? AND kelas_id=? AND tahun_ajaran=? AND semester=?",
            [$siswaId, $kelasId, $ta, $sem]
        );
        if ($existing) {
            db_update('absensi',
                array('sakit'=>$sakit,'izin'=>$izin,'tanpa_keterangan'=>$alpha),
                'id=:id', array('id'=>$existing['id'])
            );
        } else {
            db_insert('absensi', array(
                'siswa_id'=>$siswaId,'kelas_id'=>$kelasId,
                'tahun_ajaran'=>$ta,'semester'=>$sem,
                'sakit'=>$sakit,'izin'=>$izin,'tanpa_keterangan'=>$alpha
            ));
        }
    }
    setFlash('success', 'Data absensi berhasil disimpan.');
    header('Location: input.php?kelas_id='.$kelasId);
    exit;
}

$kelasId = intval($_GET['kelas_id'] ?? 0);

// Daftar kelas
if ($isAdmin) {
    $kelasList = db_fetchAll(
        "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
        [$ta, $sem]
    );
} else {
    $guruId = $_SESSION['guru_id'] ?? 0;
    $kelasList = $guruId ? db_fetchAll(
        "SELECT DISTINCT k.* FROM pengampu p JOIN kelas k ON k.id=p.kelas_id
         WHERE p.guru_id=? AND p.tahun_ajaran=? AND p.semester=? ORDER BY k.tingkat, k.nama_kelas",
        [$guruId, $ta, $sem]
    ) : array();
}

$siswaList = array();
$selectedKelas = null;
if ($kelasId) {
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);
    $siswaList = db_fetchAll("
        SELECT s.id, s.nis, s.nama, s.jenis_kelamin,
               a.sakit, a.izin, a.tanpa_keterangan
        FROM siswa s
        LEFT JOIN absensi a ON a.siswa_id=s.id AND a.kelas_id=? AND a.tahun_ajaran=? AND a.semester=?
        WHERE s.kelas_id=? AND s.status='aktif'
        ORDER BY s.nama
    ", [$kelasId, $ta, $sem, $kelasId]);
}

include '../../templates/header.php';
?>

<!-- Filter Kelas -->
<div class="card" style="margin-bottom:16px;">
  <div class="card-body" style="padding:14px 20px;">
    <form method="GET" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;">
      <div style="min-width:200px;flex:1;">
        <label class="form-label">Pilih Kelas</label>
        <select name="kelas_id" class="form-control" onchange="this.form.submit()">
          <option value="">-- Pilih Kelas --</option>
          <?php foreach ($kelasList as $k): ?>
          <option value="<?= $k['id'] ?>" <?= $kelasId==$k['id']?'selected':'' ?>>
            <?= htmlspecialchars($k['nama_kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($kelasId): ?>
      <div style="font-size:13px;color:var(--text-muted);padding-bottom:6px;">
        <i class="fas fa-info-circle"></i>
        TA <?= $ta ?> &bull; Semester <?= $sem ?>
      </div>
      <?php endif; ?>
    </form>
  </div>
</div>

<?php if ($kelasId && $selectedKelas): ?>
<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-calendar-check" style="color:var(--primary);margin-right:8px;"></i>
      Absensi &mdash; <?= htmlspecialchars($selectedKelas['nama_kelas']) ?>
      <span class="badge badge-info" style="margin-left:6px;"><?= count($siswaList) ?> siswa</span>
    </span>
    <div style="display:flex;gap:8px;">
      <a href="report.php?kelas_id=<?= $kelasId ?>" class="btn btn-outline btn-sm">
        <i class="fas fa-chart-bar"></i> Laporan
      </a>
    </div>
  </div>

  <form method="POST">
    <input type="hidden" name="bulk_save" value="1">
    <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">

    <div style="overflow-x:auto;">
      <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
          <tr style="background:var(--primary-dark);color:#fff;">
            <th style="padding:10px 12px;text-align:left;width:40px;">No</th>
            <th style="padding:10px 12px;text-align:left;">Nama Siswa</th>
            <th style="padding:10px 12px;text-align:center;width:90px;">NIS</th>
            <th style="padding:10px 12px;text-align:center;width:90px;background:rgba(59,130,246,.3);">
              <i class="fas fa-thermometer-half"></i> Sakit
            </th>
            <th style="padding:10px 12px;text-align:center;width:90px;background:rgba(245,158,11,.3);">
              <i class="fas fa-file-alt"></i> Izin
            </th>
            <th style="padding:10px 12px;text-align:center;width:90px;background:rgba(239,68,68,.3);">
              <i class="fas fa-times-circle"></i> Alpha
            </th>
            <th style="padding:10px 12px;text-align:center;width:80px;">Total</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($siswaList)): ?>
          <tr><td colspan="7" style="text-align:center;padding:32px;color:var(--text-muted);">Belum ada siswa di kelas ini</td></tr>
          <?php else: ?>
          <?php foreach ($siswaList as $idx => $s):
            $sakit = intval($s['sakit'] ?? 0);
            $izin  = intval($s['izin']  ?? 0);
            $alpha = intval($s['tanpa_keterangan'] ?? 0);
            $total = $sakit + $izin + $alpha;
            $rowBg = $idx % 2 === 0 ? '' : 'background:var(--surface-2);';
          ?>
          <tr style="<?= $rowBg ?>">
            <td style="padding:8px 12px;color:var(--text-muted);"><?= $idx+1 ?></td>
            <td style="padding:8px 12px;font-weight:600;">
              <?= htmlspecialchars($s['nama']) ?>
              <span class="badge <?= $s['jenis_kelamin']==='L'?'badge-info':'badge-warning' ?>" style="font-size:10px;margin-left:4px;"><?= $s['jenis_kelamin'] ?></span>
            </td>
            <td style="padding:8px 6px;text-align:center;"><code style="font-size:11px;"><?= $s['nis'] ?></code></td>
            <td style="padding:6px;text-align:center;background:rgba(59,130,246,.05);">
              <input type="number" name="rows[<?= $s['id'] ?>][sakit]"
                     value="<?= $sakit ?>" min="0" max="99"
                     class="abs-input"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;font-weight:600;color:#1d4ed8;"
                     onchange="updateTotal(this, <?= $s['id'] ?>)">
            </td>
            <td style="padding:6px;text-align:center;background:rgba(245,158,11,.05);">
              <input type="number" name="rows[<?= $s['id'] ?>][izin]"
                     value="<?= $izin ?>" min="0" max="99"
                     class="abs-input"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;font-weight:600;color:#b45309;"
                     onchange="updateTotal(this, <?= $s['id'] ?>)">
            </td>
            <td style="padding:6px;text-align:center;background:rgba(239,68,68,.05);">
              <input type="number" name="rows[<?= $s['id'] ?>][alpha]"
                     value="<?= $alpha ?>" min="0" max="99"
                     class="abs-input"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;font-weight:600;color:#dc2626;"
                     onchange="updateTotal(this, <?= $s['id'] ?>)">
            </td>
            <td style="padding:8px 6px;text-align:center;">
              <span id="total-<?= $s['id'] ?>"
                    style="font-weight:800;font-size:14px;color:<?= $total>10?'#dc2626':($total>5?'#d97706':'#16a34a') ?>;">
                <?= $total ?>
              </span>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
        <?php if (!empty($siswaList)): ?>
        <tfoot>
          <tr style="background:var(--bg);border-top:2px solid var(--border);">
            <td colspan="3" style="padding:10px 12px;font-weight:700;font-size:12px;color:var(--text-muted);">Total Keseluruhan</td>
            <?php
            $totS = array_sum(array_column($siswaList,'sakit'));
            $totI = array_sum(array_column($siswaList,'izin'));
            $totA = array_sum(array_column($siswaList,'tanpa_keterangan'));
            ?>
            <td style="padding:10px 6px;text-align:center;font-weight:800;color:#1d4ed8;"><?= $totS ?></td>
            <td style="padding:10px 6px;text-align:center;font-weight:800;color:#b45309;"><?= $totI ?></td>
            <td style="padding:10px 6px;text-align:center;font-weight:800;color:#dc2626;"><?= $totA ?></td>
            <td style="padding:10px 6px;text-align:center;font-weight:800;"><?= $totS+$totI+$totA ?></td>
          </tr>
        </tfoot>
        <?php endif; ?>
      </table>
    </div>

    <?php if (!empty($siswaList)): ?>
    <div style="padding:16px 20px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;gap:10px;">
      <button type="submit" class="btn btn-primary">
        <i class="fas fa-save"></i> Simpan Semua Absensi
      </button>
    </div>
    <?php endif; ?>
  </form>
</div>

<script>
function updateTotal(input, siswaId) {
    var row   = input.closest('tr');
    var inputs = row.querySelectorAll('.abs-input');
    var total = 0;
    inputs.forEach(function(i){ total += parseInt(i.value)||0; });
    var el = document.getElementById('total-'+siswaId);
    el.textContent = total;
    el.style.color = total > 10 ? '#dc2626' : (total > 5 ? '#d97706' : '#16a34a');
}
</script>

<?php elseif (!$kelasId): ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-calendar-check" style="font-size:48px;display:block;margin-bottom:14px;opacity:.2;"></i>
    <p>Pilih kelas untuk menginput data absensi.</p>
  </div>
</div>
<?php endif; ?>

<?php include '../../templates/footer.php'; ?>
