<?php
/**
 * SisPen Snesaka - Kelola Kelas Bimbingan Guru BK
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Kelas Bimbingan BK';
$activeMenu = 'guru';
$pengaturan = getPengaturan();
$ta  = $pengaturan['tahun_ajaran_aktif'];
$sem = $pengaturan['semester_aktif'];

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_bk'])) {
    $guruId   = intval($_POST['guru_id']);
    $kelasIds = $_POST['kelas_ids'] ?? [];

    // Hapus semua kelas BK guru ini dulu
    db_query(
        "DELETE FROM bk_kelas WHERE guru_id=? AND tahun_ajaran=? AND semester=?",
        [$guruId, $ta, $sem]
    );

    // Insert yang baru
    foreach ($kelasIds as $kid) {
        $kid = intval($kid);
        if ($kid) {
            db_insert('bk_kelas', [
                'guru_id'      => $guruId,
                'kelas_id'     => $kid,
                'tahun_ajaran' => $ta,
                'semester'     => $sem,
            ]);
        }
    }
    setFlash('success', 'Kelas bimbingan BK berhasil disimpan.');
    header('Location: bk_kelas.php?guru_id=' . $guruId);
    exit;
}

$guruId    = intval($_GET['guru_id'] ?? 0);
$guruBkList = db_fetchAll(
    "SELECT g.id, g.nama, g.nip FROM guru g WHERE g.is_bk=1 AND g.status='aktif' ORDER BY g.nama"
);
$kelasList  = db_fetchAll(
    "SELECT k.*, wk.nama as nama_wali
     FROM kelas k
     LEFT JOIN guru wk ON wk.id = k.wali_kelas_id
     WHERE k.tahun_ajaran=? AND k.semester=?
     ORDER BY k.tingkat, k.nama_kelas",
    [$ta, $sem]
);

// Kelas yang sudah di-assign ke guru BK ini
$assigned = [];
if ($guruId) {
    $rows = db_fetchAll(
        "SELECT kelas_id FROM bk_kelas WHERE guru_id=? AND tahun_ajaran=? AND semester=?",
        [$guruId, $ta, $sem]
    );
    $assigned = array_column($rows, 'kelas_id');
}

// Ringkasan semua guru BK + kelas yang dipegang
$summary = db_fetchAll("
    SELECT g.id, g.nama, g.nip,
           GROUP_CONCAT(k.nama_kelas ORDER BY k.tingkat, k.nama_kelas SEPARATOR ', ') as kelas_list,
           COUNT(bk.id) as jumlah_kelas
    FROM guru g
    LEFT JOIN bk_kelas bk ON bk.guru_id=g.id AND bk.tahun_ajaran=? AND bk.semester=?
    LEFT JOIN kelas k ON k.id=bk.kelas_id
    WHERE g.is_bk=1 AND g.status='aktif'
    GROUP BY g.id
    ORDER BY g.nama
", [$ta, $sem]);

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

<div style="display:grid;grid-template-columns:1fr 380px;gap:20px;align-items:start;">

  <!-- Ringkasan semua Guru BK -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-user-md" style="color:var(--warning);margin-right:8px;"></i>
        Guru BK &amp; Kelas Bimbingan
        <span style="font-size:12px;font-weight:400;color:var(--text-muted);margin-left:6px;">
          TA <?= $ta ?> Sem <?= $sem ?>
        </span>
      </span>
    </div>

    <?php if (empty($guruBkList)): ?>
    <div class="card-body" style="text-align:center;padding:40px;color:var(--text-muted);">
      <i class="fas fa-user-md" style="font-size:40px;opacity:.2;display:block;margin-bottom:12px;"></i>
      <p>Belum ada Guru BK.</p>
      <p style="font-size:12px;">Tandai guru sebagai BK melalui <a href="list.php">Data Guru → Edit</a>.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>Nama Guru BK</th>
            <th>NIP</th>
            <th>Kelas Bimbingan</th>
            <th style="text-align:center;">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($summary as $g): ?>
          <tr style="<?= $guruId==$g['id']?'background:rgba(59,130,246,.06);':'' ?>">
            <td style="font-weight:600;">
              <?= htmlspecialchars($g['nama']) ?>
              <?php if ($guruId==$g['id']): ?>
              <span class="badge badge-blue" style="font-size:10px;margin-left:4px;">Dipilih</span>
              <?php endif; ?>
            </td>
            <td><code style="font-size:11px;"><?= htmlspecialchars($g['nip'] ?? '-') ?></code></td>
            <td>
              <?php if ($g['kelas_list']): ?>
                <?php foreach (explode(', ', $g['kelas_list']) as $kn): ?>
                <span class="badge badge-success" style="margin:1px;"><?= htmlspecialchars($kn) ?></span>
                <?php endforeach; ?>
              <?php else: ?>
                <span style="color:var(--text-muted);font-size:12px;">Belum ada kelas</span>
              <?php endif; ?>
            </td>
            <td style="text-align:center;">
              <a href="?guru_id=<?= $g['id'] ?>" class="btn btn-primary btn-xs">
                <i class="fas fa-edit"></i> Atur Kelas
              </a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Form assign kelas -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-tasks" style="color:var(--success);margin-right:8px;"></i>
        <?= $guruId ? 'Atur Kelas Bimbingan' : 'Pilih Guru BK' ?>
      </span>
    </div>
    <div class="card-body">

      <?php if (!$guruId): ?>
      <p style="text-align:center;color:var(--text-muted);padding:20px 0;">
        <i class="fas fa-arrow-left" style="margin-right:6px;"></i>
        Klik <strong>"Atur Kelas"</strong> pada salah satu Guru BK di sebelah kiri.
      </p>

      <?php else:
        $selectedGuru = db_fetch("SELECT * FROM guru WHERE id=?", [$guruId]);
      ?>

      <div style="background:linear-gradient(135deg,var(--primary-dark),var(--primary));color:#fff;border-radius:10px;padding:14px 16px;margin-bottom:18px;display:flex;align-items:center;gap:12px;">
        <div style="width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;flex-shrink:0;">
          <?= strtoupper(substr($selectedGuru['nama'],0,1)) ?>
        </div>
        <div>
          <div style="font-weight:700;font-size:14px;"><?= htmlspecialchars($selectedGuru['nama']) ?></div>
          <div style="font-size:11px;opacity:.8;">Guru BK &bull; NIP: <?= $selectedGuru['nip'] ?: '-' ?></div>
        </div>
      </div>

      <form method="POST">
        <input type="hidden" name="save_bk"  value="1">
        <input type="hidden" name="guru_id"  value="<?= $guruId ?>">

        <div class="form-label" style="margin-bottom:10px;">
          Centang kelas yang dibimbing:
        </div>

        <?php
        // Kelompokkan per tingkat
        $byTingkat = [];
        foreach ($kelasList as $k) {
            $byTingkat[$k['tingkat']][] = $k;
        }
        ?>

        <?php foreach ($byTingkat as $tingkat => $kelas): ?>
        <div style="margin-bottom:14px;">
          <div style="font-size:11px;font-weight:700;color:var(--text-muted);letter-spacing:.5px;margin-bottom:6px;text-transform:uppercase;">
            Kelas <?= $tingkat ?>
          </div>
          <div style="display:flex;flex-wrap:wrap;gap:8px;">
            <?php foreach ($kelas as $k): ?>
            <label style="display:flex;align-items:center;gap:6px;padding:6px 12px;border:1px solid var(--border);border-radius:8px;cursor:pointer;font-size:13px;transition:all .15s;<?= in_array($k['id'],$assigned)?'background:#dbeafe;border-color:#3b82f6;':'' ?>">
              <input type="checkbox" name="kelas_ids[]" value="<?= $k['id'] ?>"
                     <?= in_array($k['id'], $assigned) ? 'checked' : '' ?>
                     style="accent-color:var(--primary);"
                     onchange="this.closest('label').style.background=this.checked?'#dbeafe':'';this.closest('label').style.borderColor=this.checked?'#3b82f6':'var(--border)';">
              <strong><?= htmlspecialchars($k['nama_kelas']) ?></strong>
              <?php if ($k['nama_wali']): ?>
              <span style="font-size:10px;color:var(--text-muted);">(<?= htmlspecialchars($k['nama_wali']) ?>)</span>
              <?php endif; ?>
            </label>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endforeach; ?>

        <?php if (empty($kelasList)): ?>
        <p style="color:var(--text-muted);font-size:13px;">Belum ada kelas untuk TA/Semester aktif.</p>
        <?php endif; ?>

        <div style="display:flex;gap:8px;margin-top:16px;padding-top:16px;border-top:1px solid var(--border);">
          <button type="submit" class="btn btn-primary" style="flex:1;justify-content:center;">
            <i class="fas fa-save"></i> Simpan Kelas BK
          </button>
          <a href="bk_kelas.php" class="btn btn-outline">
            <i class="fas fa-times"></i>
          </a>
        </div>
      </form>
      <?php endif; ?>

    </div>
  </div>

</div>

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