<?php
/**
 * SisPen Snesaka - Input Absensi
 * Role: Admin      → semua kelas
 *       Guru BK    → kelas bimbingan yang ditugaskan
 *       Wali Kelas → hanya kelas yang diwali
 *       Guru biasa → akses ditolak
 */
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';
$guruId     = $_SESSION['guru_id'] ?? 0;

// ── Tentukan role dan kelas yang boleh diakses ──────────────
$isBK        = false;
$isWaliKelas = false;
$kelasList   = [];

if ($isAdmin) {
    // Admin: semua kelas
    $kelasList = db_fetchAll(
        "SELECT k.*, g.nama as nama_wali
         FROM kelas k LEFT JOIN guru g ON g.id=k.wali_kelas_id
         WHERE k.tahun_ajaran=? AND k.semester=?
         ORDER BY k.tingkat, k.nama_kelas",
        [$ta, $sem]
    );
} elseif ($guruId) {
    $guruData    = db_fetch("SELECT is_bk FROM guru WHERE id=?", [$guruId]);
    $isBK        = !empty($guruData['is_bk']);

    if ($isBK) {
        // Guru BK: hanya kelas bimbingan yang ditugaskan
        $kelasList = db_fetchAll(
            "SELECT k.*, g.nama as nama_wali
             FROM bk_kelas bk
             JOIN kelas k ON k.id=bk.kelas_id
             LEFT JOIN guru g ON g.id=k.wali_kelas_id
             WHERE bk.guru_id=? AND bk.tahun_ajaran=? AND bk.semester=?
             ORDER BY k.tingkat, k.nama_kelas",
            [$guruId, $ta, $sem]
        );
    } else {
        // Cek wali kelas
        $kelasList = db_fetchAll(
            "SELECT k.*, g.nama as nama_wali
             FROM kelas k LEFT JOIN guru g ON g.id=k.wali_kelas_id
             WHERE k.wali_kelas_id=? AND k.tahun_ajaran=? AND k.semester=?
             ORDER BY k.tingkat, k.nama_kelas",
            [$guruId, $ta, $sem]
        );
        $isWaliKelas = !empty($kelasList);
    }
}

// Guru biasa (bukan admin, BK, atau wali) → tolak
if (!$isAdmin && !$isBK && !$isWaliKelas) {
    include '../../templates/header.php';
    ?>
    <div class="card">
      <div class="card-body" style="text-align:center;padding:60px 40px;">
        <div style="font-size:56px;margin-bottom:16px;">🚫</div>
        <h3 style="color:#dc2626;margin-bottom:8px;">Akses Ditolak</h3>
        <p style="color:var(--text-muted);font-size:14px;line-height:1.8;">
          Halaman ini hanya dapat diakses oleh:<br>
          <strong>Administrator</strong>, <strong>Guru BK</strong> (sesuai kelas bimbingan),<br>
          atau <strong>Wali Kelas</strong>.
        </p>
        <a href="<?= BASE_URL ?>/guru.php" class="btn btn-outline" style="margin-top:16px;">
          <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
        </a>
      </div>
    </div>
    <?php
    include '../../templates/footer.php';
    exit;
}

// Guru BK tapi belum ada kelas ditugaskan
if ($isBK && empty($kelasList)) {
    include '../../templates/header.php';
    ?>
    <div class="card">
      <div class="card-body" style="text-align:center;padding:60px 40px;">
        <div style="font-size:56px;margin-bottom:16px;">📋</div>
        <h3 style="color:var(--warning);margin-bottom:8px;">Belum Ada Kelas Bimbingan</h3>
        <p style="color:var(--text-muted);font-size:14px;line-height:1.8;">
          Anda terdaftar sebagai Guru BK, namun belum ada kelas bimbingan yang ditugaskan.<br>
          Hubungi Administrator untuk mengatur kelas bimbingan Anda.
        </p>
        <a href="<?= BASE_URL ?>/guru.php" class="btn btn-outline" style="margin-top:16px;">
          <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
        </a>
      </div>
    </div>
    <?php
    include '../../templates/footer.php';
    exit;
}

// ── Handle bulk save ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_save'])) {
    $kelasId = intval($_POST['kelas_id']);

    // Validasi: kelas harus ada di daftar yang boleh diakses
    $kelasIds = array_column($kelasList, 'id');
    if (!in_array($kelasId, $kelasIds)) {
        setFlash('danger', 'Anda tidak berhak mengisi absensi kelas ini.');
        header('Location: input.php');
        exit;
    }

    $rows = $_POST['rows'] ?? [];
    foreach ($rows as $siswaId => $val) {
        $siswaId = intval($siswaId);
        $sakit   = max(0, intval($val['sakit']  ?? 0));
        $izin    = max(0, intval($val['izin']   ?? 0));
        $alpha   = max(0, 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',
                ['sakit'=>$sakit,'izin'=>$izin,'tanpa_keterangan'=>$alpha],
                'id=:id', ['id'=>$existing['id']]
            );
        } else {
            db_insert('absensi', [
                '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;
}

// ── Ambil data siswa ────────────────────────────────────────
$kelasId       = intval($_GET['kelas_id'] ?? 0);
$selectedKelas = null;
$siswaList     = [];

// Auto-pilih jika hanya ada 1 kelas
if (!$kelasId && count($kelasList) === 1) {
    $kelasId = $kelasList[0]['id'];
}

if ($kelasId) {
    $kelasIds = array_column($kelasList, 'id');
    if (!in_array($kelasId, $kelasIds)) {
        setFlash('danger', 'Anda tidak berhak mengakses kelas ini.');
        header('Location: input.php');
        exit;
    }

    $selectedKelas = db_fetch(
        "SELECT k.*, g.nama as nama_wali
         FROM kelas k LEFT JOIN guru g ON g.id=k.wali_kelas_id WHERE k.id=?",
        [$kelasId]
    );

    $siswaList = db_fetchAll("
        SELECT s.id, s.nis, s.nama, s.jenis_kelamin,
               COALESCE(a.sakit,0)            as sakit,
               COALESCE(a.izin,0)             as izin,
               COALESCE(a.tanpa_keterangan,0) as alpha
        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';

$roleLabel = $isAdmin ? 'Administrator' : ($isBK ? 'Guru BK' : 'Wali Kelas');
$roleIcon  = $isAdmin ? 'shield-alt'    : ($isBK ? 'user-md' : 'chalkboard-teacher');
$roleBadge = $isAdmin ? 'badge-blue'    : ($isBK ? 'badge-warning' : 'badge-success');
$roleDesc  = $isAdmin ? 'Semua kelas'
           : ($isBK   ? count($kelasList).' kelas bimbingan'
           :             'Kelas '.($kelasList[0]['nama_kelas'] ?? ''));
?>

<!-- Info role -->
<div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding:10px 16px;
            background:var(--surface);border:1px solid var(--border);border-radius:10px;
            font-size:13px;flex-wrap:wrap;">
  <i class="fas fa-<?= $roleIcon ?>" style="color:var(--primary);font-size:15px;"></i>
  <span>Login sebagai <strong><?= htmlspecialchars($_SESSION['nama'] ?? '') ?></strong></span>
  <span class="badge <?= $roleBadge ?>"><?= $roleLabel ?></span>
  <span style="color:var(--text-muted);">— <?= $roleDesc ?></span>
  <?php if ($isBK): ?>
  <span style="display:flex;gap:4px;flex-wrap:wrap;">
    <?php foreach ($kelasList as $k): ?>
    <span class="badge badge-info" style="font-size:10px;"><?= htmlspecialchars($k['nama_kelas']) ?></span>
    <?php endforeach; ?>
  </span>
  <?php endif; ?>
</div>

<!-- 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']) ?>
            <?php if ($k['nama_wali'] && ($isAdmin||$isBK)): ?>
            (Wali: <?= htmlspecialchars($k['nama_wali']) ?>)
            <?php endif; ?>
          </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; <strong><?= htmlspecialchars($selectedKelas['nama_kelas']) ?></strong>
      <span class="badge badge-info" style="margin-left:6px;"><?= count($siswaList) ?> siswa</span>
      <?php if ($selectedKelas['nama_wali']): ?>
      <span style="font-size:12px;font-weight:400;color:var(--text-muted);margin-left:8px;">
        <i class="fas fa-chalkboard-teacher"></i> Wali: <?= htmlspecialchars($selectedKelas['nama_wali']) ?>
      </span>
      <?php endif; ?>
    </span>
    <a href="report.php?kelas_id=<?= $kelasId ?>" class="btn btn-outline btn-sm">
      <i class="fas fa-chart-bar"></i> Laporan
    </a>
  </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;width:40px;">No</th>
            <th style="padding:10px 12px;">Nama Siswa</th>
            <th style="padding:10px 8px;text-align:center;width:90px;">NIS</th>
            <th style="padding:10px 8px;text-align:center;width:90px;background:rgba(59,130,246,.3);">
              <i class="fas fa-thermometer-half"></i> Sakit
            </th>
            <th style="padding:10px 8px;text-align:center;width:90px;background:rgba(245,158,11,.3);">
              <i class="fas fa-file-alt"></i> Izin
            </th>
            <th style="padding:10px 8px;text-align:center;width:90px;background:rgba(239,68,68,.3);">
              <i class="fas fa-times-circle"></i> Alpha
            </th>
            <th style="padding:10px 8px;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']);
            $izin  = intval($s['izin']);
            $alpha = intval($s['alpha']);
            $total = $sakit + $izin + $alpha;
          ?>
          <tr style="<?= $idx%2===0?'':'background:var(--surface-2);' ?>">
            <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;"
                     oninput="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;"
                     oninput="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;"
                     oninput="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)):
          $totS = array_sum(array_column($siswaList,'sakit'));
          $totI = array_sum(array_column($siswaList,'izin'));
          $totA = array_sum(array_column($siswaList,'alpha'));
        ?>
        <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>
            <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:space-between;align-items:center;">
      <div style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-circle" style="color:#16a34a;font-size:8px;"></i> ≤5 Baik &nbsp;
        <i class="fas fa-circle" style="color:#d97706;font-size:8px;"></i> 6–10 Perhatian &nbsp;
        <i class="fas fa-circle" style="color:#dc2626;font-size:8px;"></i> &gt;10 Kritis
      </div>
      <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 inputs = input.closest('tr').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 else: ?>
<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'; ?>
