<?php
/**
 * SISPENRA - Tambah Siswa
 */
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';
requireAdmin();

$pageTitle  = 'Tambah Siswa';
$activeMenu = 'siswa';

$pengaturan = getPengaturan();
$kelasList  = db_fetchAll(
    "SELECT * FROM kelas WHERE tahun_ajaran = ? AND semester = ? ORDER BY tingkat, nama_kelas",
    [$pengaturan['tahun_ajaran_aktif'], $pengaturan['semester_aktif']]
);
$errors = array();
$data   = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;

    // --- Validasi dasar ---
    if (empty(trim($data['nis'] ?? '')))  $errors['nis']  = 'NIS wajib diisi.';
    if (empty(trim($data['nama'] ?? ''))) $errors['nama'] = 'Nama Siswa wajib diisi.';
    if (empty($data['jenis_kelamin'] ?? '')) $errors['jenis_kelamin'] = 'Jenis Kelamin wajib dipilih.';
    if (empty($data['kelas_id'] ?? ''))   $errors['kelas_id'] = 'Kelas wajib dipilih.';

    // --- Cek duplikat NIS ---
    if (empty($errors['nis'])) {
        $cekNis = db_fetch("SELECT id FROM siswa WHERE nis = ?", [trim($data['nis'])]);
        if ($cekNis) $errors['nis'] = 'NIS ' . trim($data['nis']) . ' sudah digunakan siswa lain.';
    }

    // --- Cek duplikat NISN (hanya jika diisi) ---
    $nisn = trim($data['nisn'] ?? '');
    if ($nisn !== '') {
        $cekNisn = db_fetch("SELECT id FROM siswa WHERE nisn = ?", [$nisn]);
        if ($cekNisn) $errors['nisn'] = 'NISN ' . $nisn . ' sudah digunakan siswa lain.';
    }

    if (empty($errors)) {
        try {
            db_insert('siswa', array(
                'nis'           => sanitize(trim($data['nis'])),
                'nisn'          => $nisn !== '' ? sanitize($nisn) : null, // NULL jika kosong
                'nama'          => sanitize(trim($data['nama'])),
                'jenis_kelamin' => $data['jenis_kelamin'],
                'tempat_lahir'  => sanitize($data['tempat_lahir'] ?? ''),
                'tanggal_lahir' => !empty($data['tanggal_lahir']) ? $data['tanggal_lahir'] : null,
                'alamat'        => sanitize($data['alamat'] ?? ''),
                'nama_ayah'     => sanitize($data['nama_ayah'] ?? ''),
                'nama_ibu'      => sanitize($data['nama_ibu'] ?? ''),
                'telepon_ortu'  => sanitize($data['telepon_ortu'] ?? ''),
                'kelas_id'      => intval($data['kelas_id']),
                'tahun_masuk'   => !empty($data['tahun_masuk']) ? intval($data['tahun_masuk']) : intval(date('Y')),
                'status'        => 'aktif',
            ));
            setFlash('success', 'Siswa ' . htmlspecialchars(trim($data['nama'])) . ' berhasil ditambahkan!');
            header('Location: list.php');
            exit;
        } catch (Exception $e) {
            // Tangkap error DB yang lolos validasi (misal race condition)
            if (strpos($e->getMessage(), 'nisn') !== false) {
                $errors['nisn'] = 'NISN sudah digunakan siswa lain.';
            } elseif (strpos($e->getMessage(), 'nis') !== false) {
                $errors['nis'] = 'NIS sudah digunakan siswa lain.';
            } else {
                $errors['global'] = 'Gagal menyimpan data: ' . $e->getMessage();
            }
        }
    }
}

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

<div class="card" style="max-width:800px;">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-user-plus" style="color:var(--primary);margin-right:8px;"></i>
      Tambah Siswa Baru
    </span>
    <a href="list.php" class="btn btn-outline btn-sm"><i class="fas fa-arrow-left"></i> Kembali</a>
  </div>
  <div class="card-body">

    <?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
      <i class="fas fa-exclamation-triangle"></i>
      <div>
        <strong>Terdapat kesalahan, silakan perbaiki:</strong><br>
        <?php foreach ($errors as $e): ?>
        &bull; <?= htmlspecialchars($e) ?><br>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <form method="POST" action="">

      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">NIS <span class="required">*</span></label>
          <input type="text" name="nis" class="form-control <?= isset($errors['nis']) ? 'is-invalid' : '' ?>"
                 value="<?= htmlspecialchars($data['nis'] ?? '') ?>" placeholder="Nomor Induk Siswa" autofocus>
          <?php if (isset($errors['nis'])): ?>
          <div class="invalid-feedback"><?= htmlspecialchars($errors['nis']) ?></div>
          <?php endif; ?>
        </div>
        <div class="form-group">
          <label class="form-label">NISN <span style="font-weight:400;color:var(--text-muted);">(opsional)</span></label>
          <input type="text" name="nisn" class="form-control <?= isset($errors['nisn']) ? 'is-invalid' : '' ?>"
                 value="<?= htmlspecialchars($data['nisn'] ?? '') ?>" placeholder="Nomor Induk Siswa Nasional">
          <?php if (isset($errors['nisn'])): ?>
          <div class="invalid-feedback"><?= htmlspecialchars($errors['nisn']) ?></div>
          <?php else: ?>
          <div style="font-size:11px;color:var(--text-muted);margin-top:3px;">Kosongkan jika belum ada / tidak diketahui</div>
          <?php endif; ?>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">Nama Lengkap <span class="required">*</span></label>
        <input type="text" name="nama" class="form-control <?= isset($errors['nama']) ? 'is-invalid' : '' ?>"
               value="<?= htmlspecialchars($data['nama'] ?? '') ?>" placeholder="Nama lengkap siswa">
        <?php if (isset($errors['nama'])): ?>
        <div class="invalid-feedback"><?= htmlspecialchars($errors['nama']) ?></div>
        <?php endif; ?>
      </div>

      <div class="form-row cols-3">
        <div class="form-group">
          <label class="form-label">Jenis Kelamin <span class="required">*</span></label>
          <select name="jenis_kelamin" class="form-control <?= isset($errors['jenis_kelamin']) ? 'is-invalid' : '' ?>">
            <option value="">-- Pilih --</option>
            <option value="L" <?= ($data['jenis_kelamin'] ?? '') === 'L' ? 'selected' : '' ?>>Laki-laki</option>
            <option value="P" <?= ($data['jenis_kelamin'] ?? '') === 'P' ? 'selected' : '' ?>>Perempuan</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Tempat Lahir</label>
          <input type="text" name="tempat_lahir" class="form-control"
                 value="<?= htmlspecialchars($data['tempat_lahir'] ?? '') ?>" placeholder="Kota lahir">
        </div>
        <div class="form-group">
          <label class="form-label">Tanggal Lahir</label>
          <input type="date" name="tanggal_lahir" class="form-control"
                 value="<?= htmlspecialchars($data['tanggal_lahir'] ?? '') ?>">
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">Alamat</label>
        <textarea name="alamat" class="form-control" rows="2"
                  placeholder="Alamat lengkap"><?= htmlspecialchars($data['alamat'] ?? '') ?></textarea>
      </div>

      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">Nama Ayah</label>
          <input type="text" name="nama_ayah" class="form-control"
                 value="<?= htmlspecialchars($data['nama_ayah'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Nama Ibu</label>
          <input type="text" name="nama_ibu" class="form-control"
                 value="<?= htmlspecialchars($data['nama_ibu'] ?? '') ?>">
        </div>
      </div>

      <div class="form-row cols-3">
        <div class="form-group">
          <label class="form-label">Telepon Orang Tua</label>
          <input type="text" name="telepon_ortu" class="form-control"
                 value="<?= htmlspecialchars($data['telepon_ortu'] ?? '') ?>" placeholder="08xxx">
        </div>
        <div class="form-group">
          <label class="form-label">Kelas <span class="required">*</span></label>
          <select name="kelas_id" class="form-control <?= isset($errors['kelas_id']) ? 'is-invalid' : '' ?>">
            <option value="">-- Pilih Kelas --</option>
            <?php foreach ($kelasList as $k): ?>
            <option value="<?= $k['id'] ?>" <?= ($data['kelas_id'] ?? '') == $k['id'] ? 'selected' : '' ?>>
              <?= htmlspecialchars($k['nama_kelas']) ?>
            </option>
            <?php endforeach; ?>
          </select>
          <?php if (isset($errors['kelas_id'])): ?>
          <div class="invalid-feedback"><?= htmlspecialchars($errors['kelas_id']) ?></div>
          <?php endif; ?>
        </div>
        <div class="form-group">
          <label class="form-label">Tahun Masuk</label>
          <input type="number" name="tahun_masuk" class="form-control"
                 value="<?= htmlspecialchars($data['tahun_masuk'] ?? date('Y')) ?>"
                 min="2000" max="2035">
        </div>
      </div>

      <div style="display:flex;gap:10px;margin-top:8px;">
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        <a href="list.php" class="btn btn-outline">Batal</a>
      </div>
    </form>
  </div>
</div>

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