<?php
$pageTitle = 'Proses Klasifikasi';
require_once __DIR__ . '/includes/header.php';

$db = getDB();

$mode = $_GET['mode'] ?? 'manual'; // 'manual' or 'bulk'
$hasil = null;
$form = [
    'nama' => '',
    'pekerjaan_ortu' => '',
    'penghasilan_ortu' => '',
    'jumlah_saudara' => '',
    'kepemilikan_kps' => '',
    'kepemilikan_kip' => '',
];

// Pagination for bulk classification
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$validLimits = [10, 20, 50, 100, 300, 500];
if (!in_array($limit, $validLimits)) {
    $limit = 10;
}
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$offset = ($page - 1) * $limit;

$totalSiswa = $db->query('SELECT COUNT(*) FROM siswa')->fetchColumn();
$totalPages = ceil($totalSiswa / $limit);

// Load siswa untuk bulk classification
$siswaList = $db->query("SELECT id, nama, pekerjaan_ortu, penghasilan_ortu, jumlah_saudara, kepemilikan_kps, kepemilikan_kip FROM siswa ORDER BY id DESC LIMIT $limit OFFSET $offset")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'manual_classify') {
        $form = [
            'nama' => trim($_POST['nama'] ?? ''),
            'pekerjaan_ortu' => trim($_POST['pekerjaan_ortu'] ?? ''),
            'penghasilan_ortu' => trim($_POST['penghasilan_ortu'] ?? ''),
            'jumlah_saudara' => (int) ($_POST['jumlah_saudara'] ?? 0),
            'kepemilikan_kps' => $_POST['kepemilikan_kps'] ?? '',
            'kepemilikan_kip' => $_POST['kepemilikan_kip'] ?? '',
        ];

        if ($form['nama'] === '' || $form['pekerjaan_ortu'] === '') {
            flash('error', 'Nama dan pekerjaan orang tua wajib diisi.');
        } elseif (!validPekerjaanOrtu($form['pekerjaan_ortu'])) {
            flash('error', 'Pekerjaan orang tua wajib dipilih.');
        } elseif (!validPenghasilanOrtu($form['penghasilan_ortu'])) {
            flash('error', 'Penghasilan orang tua wajib dipilih.');
        } elseif (!validYaTidak($form['kepemilikan_kps']) || !validYaTidak($form['kepemilikan_kip'])) {
            flash('error', 'Penerima KPS dan KIP wajib dipilih.');
        } else {
            $input = [
                'pekerjaan_ortu' => $form['pekerjaan_ortu'],
                'penghasilan_ortu' => $form['penghasilan_ortu'],
                'jumlah_saudara' => $form['jumlah_saudara'],
                'kepemilikan_kps' => $form['kepemilikan_kps'],
                'kepemilikan_kip' => $form['kepemilikan_kip'],
            ];

            $hasil = runClassification($input);

            // Simpan ke tabel siswa tanpa status_kelayakan (hasil masuk ke laporan)
            $ins = $db->prepare(
                'INSERT INTO siswa (nama, pekerjaan_ortu, penghasilan_ortu, jumlah_saudara,
                 kepemilikan_kps, kepemilikan_kip, status_kelayakan, prob_layak, prob_tidak_layak)
                 VALUES (?,?,?,?,?,?,?,?,?)'
            );
            $ins->execute([
                $form['nama'], $form['pekerjaan_ortu'], $form['penghasilan_ortu'],
                $form['jumlah_saudara'], $form['kepemilikan_kps'], $form['kepemilikan_kip'],
                $hasil['kelas'], $hasil['prob_layak'], $hasil['prob_tidak_layak'],
            ]);

            flash('success', 'Klasifikasi berhasil. Data siswa tersimpan dan hasil masuk ke Laporan.');
        }
    } elseif ($action === 'bulk_classify') {
        $ids = array_values(array_filter(array_map('intval', $_POST['ids'] ?? []), static fn ($id) => $id > 0));
        if (empty($ids)) {
            flash('error', 'Pilih minimal satu data siswa untuk diklasifikasikan.');
        } else {
            $count = 0;
            foreach ($ids as $id) {
                $st = $db->prepare('SELECT pekerjaan_ortu, penghasilan_ortu, jumlah_saudara, kepemilikan_kps, kepemilikan_kip FROM siswa WHERE id = ?');
                $st->execute([$id]);
                $row = $st->fetch();
                if ($row) {
                    $input = [
                        'pekerjaan_ortu' => $row['pekerjaan_ortu'],
                        'penghasilan_ortu' => $row['penghasilan_ortu'],
                        'jumlah_saudara' => $row['jumlah_saudara'],
                        'kepemilikan_kps' => $row['kepemilikan_kps'],
                        'kepemilikan_kip' => $row['kepemilikan_kip'],
                    ];
                    $hasil = runClassification($input);
                    $upd = $db->prepare(
                        'UPDATE siswa SET status_kelayakan=?, prob_layak=?, prob_tidak_layak=? WHERE id=?'
                    );
                    $upd->execute([$hasil['kelas'], $hasil['prob_layak'], $hasil['prob_tidak_layak'], $id]);
                    $count++;
                }
            }
            flash('success', "$count data siswa berhasil diklasifikasikan. Hasil masuk ke Laporan.");
        }
    }
}

$error = flash('error');
$success = flash('success');
?>

<div class="page-header">
  <h1>Proses Klasifikasi</h1>
  <p class="subtitle">Klasifikasi Kelayakan dengan Naive Bayes</p>
</div>
<div class="page-body">
  <?php if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>
  <?php if ($success): ?><div class="alert alert-success"><?= e($success) ?></div><?php endif; ?>

  <div class="mode-buttons" style="display:flex;gap:1rem;margin-bottom:2rem">
    <a href="klasifikasi.php?mode=manual" class="btn <?= $mode === 'manual' ? 'btn-primary' : 'btn-outline' ?>">
      <i class="fas fa-edit"></i> Input Manual
    </a>
    <a href="klasifikasi.php?mode=bulk" class="btn <?= $mode === 'bulk' ? 'btn-primary' : 'btn-outline' ?>">
      <i class="fas fa-list"></i> Klasifikasi Data Tersimpan
    </a>
  </div>

  <?php if ($mode === 'manual'): ?>
  <!-- Input Manual Mode -->
  <div class="klasifikasi-grid">
    <div class="card form-card">
      <form method="post" novalidate>
        <input type="hidden" name="action" value="manual_classify">
        <div class="form-group">
          <label>Nama</label>
          <input type="text" name="nama" class="form-control" value="<?= e($form['nama']) ?>" required>
        </div>
        <div class="form-group">
          <label>Pekerjaan Orang Tua</label>
          <select name="pekerjaan_ortu" class="form-control" required>
            <?= optionsPekerjaanOrtu($form['pekerjaan_ortu']) ?>
          </select>
        </div>
        <div class="form-group">
          <label>Penghasilan Orang Tua</label>
          <select name="penghasilan_ortu" class="form-control" required>
            <?= optionsPenghasilanOrtu($form['penghasilan_ortu']) ?>
          </select>
        </div>
        <div class="form-group">
          <label>Jumlah Saudara Kandung</label>
          <input type="number" name="jumlah_saudara" class="form-control" min="0"
            value="<?= e($form['jumlah_saudara']) ?>" required>
        </div>
        <div class="form-group">
          <label>Penerima KPS</label>
          <select name="kepemilikan_kps" class="form-control" required>
            <?= optionsYaTidak($form['kepemilikan_kps']) ?>
          </select>
        </div>
        <div class="form-group">
          <label>Penerima KIP</label>
          <select name="kepemilikan_kip" class="form-control" required>
            <?= optionsYaTidak($form['kepemilikan_kip']) ?>
          </select>
        </div>
        <div style="display:flex;gap:0.5rem;margin-top:0.5rem">
          <button type="submit" class="btn btn-primary" style="flex:1">
            <i class="fas fa-calculator"></i> Hitung
          </button>
          <button type="button" class="btn btn-secondary" style="flex:1" onclick="resetForm()">
            <i class="fas fa-redo"></i> Reset
          </button>
        </div>
      </form>
    </div>

    <div class="card hasil-card">
      <h3>Hasil Klasifikasi</h3>
      <?php if ($hasil): ?>
      <div class="status-box <?= $hasil['kelas'] === 'Layak' ? 'layak' : 'tidak' ?>">
        <span class="label">Status Kelayakan</span>
        <span class="value"><?= e($hasil['kelas']) ?></span>
      </div>
      <p style="font-size:0.85rem;color:var(--text-muted);margin-top:1rem">
        <i class="fas fa-info-circle"></i>
        Hasil telah disimpan ke <a href="laporan.php">Laporan</a>.
      </p>
      <?php else: ?>
      <div class="status-box belum">
        <span class="label">Status Kelayakan</span>
        <span class="value">Belum Dihitung</span>
      </div>
      <p style="font-size:0.85rem;color:var(--text-muted);margin-top:1rem">
        <i class="fas fa-info-circle"></i>
        Isi data di samping dan klik "Hitung" untuk melihat hasil klasifikasi.
      </p>
      <?php endif; ?>
    </div>
  </div>

  <?php else: ?>
  <!-- Bulk Classification Mode -->
  <div class="card">
    <div class="card-body">
      <form method="post" id="formBulkClassify">
        <input type="hidden" name="action" value="bulk_classify">
        
        <?php if (empty($siswaList)): ?>
        <p style="text-align:center;color:var(--text-muted);padding:2rem">
          Belum ada data siswa. <a href="siswa_tambah.php">Tambah siswa terlebih dahulu.</a>
        </p>
        <?php else: ?>
        <!-- Sticky toolbar -->
        <div class="bulk-toolbar" style="display:flex;justify-content:space-between;align-items:center;padding:1rem;background:var(--card-bg);border:1px solid var(--border-color);border-radius:0.5rem;margin-bottom:1rem;position:sticky;top:0;z-index:10">
          <div style="display:flex;align-items:center;gap:0.5rem">
            <label>Tampilkan:</label>
            <select class="form-control" style="width:auto;padding:0.5rem" onchange="location.href='klasifikasi.php?mode=bulk&limit='+this.value+'&p=1'">
              <option value="10" <?= $limit === 10 ? 'selected' : '' ?>>10</option>
              <option value="20" <?= $limit === 20 ? 'selected' : '' ?>>20</option>
              <option value="50" <?= $limit === 50 ? 'selected' : '' ?>>50</option>
              <option value="100" <?= $limit === 100 ? 'selected' : '' ?>>100</option>
              <option value="300" <?= $limit === 300 ? 'selected' : '' ?>>300</option>
              <option value="500" <?= $limit === 500 ? 'selected' : '' ?>>500</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary" id="btnBulkClassify" disabled>
            <i class="fas fa-calculator"></i> Hitung Terpilih
          </button>
        </div>
        <div class="table-responsive">
          <table class="data-table">
            <thead>
              <tr>
                <th class="col-check">
                  <input type="checkbox" id="checkAllBulk" class="table-checkbox" title="Pilih semua">
                </th>
                <th>No</th>
                <th>Nama</th>
                <th>Pekerjaan Orang Tua</th>
                <th>Penghasilan Orang Tua</th>
                <th>Jumlah Saudara</th>
                <th>Penerima KPS</th>
                <th>Penerima KIP</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($siswaList as $i => $s): ?>
              <tr>
                <td class="col-check">
                  <input type="checkbox" form="formBulkClassify" name="ids[]" value="<?= (int) $s['id'] ?>"
                         class="table-checkbox row-check-bulk">
                </td>
                <td><?= $offset + $i + 1 ?></td>
                <td><?= e($s['nama']) ?></td>
                <td><?= e($s['pekerjaan_ortu']) ?></td>
                <td><?= e($s['penghasilan_ortu']) ?></td>
                <td><?= (int) $s['jumlah_saudara'] ?></td>
                <td><?= e($s['kepemilikan_kps']) ?></td>
                <td><?= e($s['kepemilikan_kip']) ?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
          <?php if ($page > 1): ?>
          <a href="klasifikasi.php?mode=bulk&limit=<?= $limit ?>&p=<?= $page - 1 ?>" class="btn btn-outline">&laquo; Prev</a>
          <?php endif; ?>
          
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <?php if ($i === $page): ?>
            <span class="btn btn-primary" style="pointer-events:none"><?= $i ?></span>
            <?php else: ?>
            <a href="klasifikasi.php?mode=bulk&limit=<?= $limit ?>&p=<?= $i ?>" class="btn btn-outline"><?= $i ?></a>
            <?php endif; ?>
          <?php endfor; ?>
          
          <?php if ($page < $totalPages): ?>
          <a href="klasifikasi.php?mode=bulk&limit=<?= $limit ?>&p=<?= $page + 1 ?>" class="btn btn-outline">Next &raquo;</a>
          <?php endif; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
      </form>
    </div>
  </div>
  <?php endif; ?>
</div>

<script>
// Bulk checkbox handling
if (document.getElementById('checkAllBulk')) {
  document.getElementById('checkAllBulk').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.row-check-bulk');
    checkboxes.forEach(cb => cb.checked = this.checked);
    updateBulkButton();
  });
}

document.querySelectorAll('.row-check-bulk').forEach(cb => {
  cb.addEventListener('change', updateBulkButton);
});

function updateBulkButton() {
  const checked = document.querySelectorAll('.row-check-bulk:checked').length;
  const btn = document.getElementById('btnBulkClassify');
  if (btn) btn.disabled = checked === 0;
}

// Reset form function
function resetForm() {
  const form = document.querySelector('form[method="post"]');
  if (form) {
    form.reset();
    // Reset select elements to default
    form.querySelectorAll('select').forEach(select => {
      select.selectedIndex = 0;
    });
    // Reset input fields
    form.querySelectorAll('input[type="text"], input[type="number"]').forEach(input => {
      input.value = '';
    });
  }
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
