<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireRole('admin');

$id   = (int)($_GET['id'] ?? 0);
$edit = $id > 0;
$data = [];

if ($edit) {
    $data = Database::fetchOne("SELECT * FROM sekolah WHERE id=?", [$id]);
    if (!$data) { setFlash('error','Sekolah tidak ditemukan.'); redirect(BASE_URL.'/modules/sekolah/index.php'); }
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $errors[] = 'Token CSRF tidak valid.'; }

    $fields = [
        'npsn'           => sanitize($_POST['npsn'] ?? ''),
        'nama_sekolah'   => sanitize($_POST['nama_sekolah'] ?? ''),
        'jenis'          => sanitize($_POST['jenis'] ?? ''),
        'kecamatan'      => sanitize($_POST['kecamatan'] ?? ''),
        'alamat'         => sanitize($_POST['alamat'] ?? ''),
        'kepala_sekolah' => sanitize($_POST['kepala_sekolah'] ?? ''),
        'nip_kepsek'     => sanitize($_POST['nip_kepsek'] ?? ''),
        'telepon'        => sanitize($_POST['telepon'] ?? ''),
        'email'          => sanitize($_POST['email'] ?? ''),
        'website'        => sanitize($_POST['website'] ?? ''),
        'akreditasi'     => sanitize($_POST['akreditasi'] ?? '') ?: null,
        'jumlah_guru'    => (int)($_POST['jumlah_guru'] ?? 0) ?: null,
        'jumlah_siswa'   => (int)($_POST['jumlah_siswa'] ?? 0) ?: null,
        'aktif'          => isset($_POST['aktif']) ? 1 : 0,
    ];

    if (empty($fields['npsn']))         $errors[] = 'NPSN wajib diisi.';
    if (empty($fields['nama_sekolah'])) $errors[] = 'Nama sekolah wajib diisi.';
    if (empty($fields['kecamatan']))    $errors[] = 'Kecamatan wajib diisi.';
    if (empty($fields['kepala_sekolah'])) $errors[] = 'Kepala sekolah wajib diisi.';

    // Cek duplikat NPSN
    $dupCheck = Database::fetchOne(
        "SELECT id FROM sekolah WHERE npsn=? AND id<>?",
        [$fields['npsn'], $id]
    );
    if ($dupCheck) $errors[] = 'NPSN sudah digunakan oleh sekolah lain.';

    if (empty($errors)) {
        if ($edit) {
            $set = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
            $vals = array_values($fields);
            $vals[] = $id;
            Database::execute("UPDATE sekolah SET {$set} WHERE id=?", $vals);
            auditLog('UPDATE','sekolah',$id,'Update data sekolah: '.$fields['nama_sekolah']);
            setFlash('success','Data sekolah berhasil diperbarui.');
        } else {
            $cols = implode(',', array_keys($fields));
            $pls  = implode(',', array_fill(0, count($fields), '?'));
            Database::execute("INSERT INTO sekolah ({$cols}) VALUES ({$pls})", array_values($fields));
            $newId = (int)Database::lastInsertId();
            auditLog('INSERT','sekolah',$newId,'Tambah sekolah: '.$fields['nama_sekolah']);
            setFlash('success','Sekolah baru berhasil ditambahkan.');
        }
        redirect(BASE_URL.'/modules/sekolah/index.php');
    }

    $data = array_merge($data, $fields);
}

$pageTitle  = ($edit ? 'Edit' : 'Tambah') . ' Sekolah';
$activePage = 'sekolah';
require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-building me-2 text-primary"></i><?= $pageTitle ?></h1>
    <nav><ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/sekolah/index.php">Sekolah</a></li>
      <li class="breadcrumb-item active"><?= $edit?'Edit':'Tambah' ?></li>
    </ol></nav>
  </div>
</div>

<?php if($errors): ?>
<div class="alert alert-danger border-0 mb-3">
  <ul class="mb-0 ps-3"><?php foreach($errors as $e): ?><li><?= e($e) ?></li><?php endforeach; ?></ul>
</div>
<?php endif; ?>

<div class="card">
  <div class="card-header"><span class="card-header-title"><i class="bi bi-pencil-square me-2"></i>Form Data Sekolah</span></div>
  <div class="card-body">
    <form method="POST">
      <?= csrf_field() ?>
      <div class="row g-3">

        <div class="col-md-4">
          <label class="form-label">NPSN <span class="text-danger">*</span></label>
          <input type="text" name="npsn" class="form-control" value="<?= e($data['npsn'] ?? '') ?>" required maxlength="20">
        </div>

        <div class="col-md-8">
          <label class="form-label">Nama Sekolah <span class="text-danger">*</span></label>
          <input type="text" name="nama_sekolah" class="form-control" value="<?= e($data['nama_sekolah'] ?? '') ?>" required maxlength="200">
        </div>

        <div class="col-md-4">
          <label class="form-label">Jenis Sekolah</label>
          <select name="jenis" class="form-select">
            <option value="SMP Negeri"  <?= ($data['jenis']??'')==='SMP Negeri'?'selected':'' ?>>SMP Negeri</option>
            <option value="SMP Swasta"  <?= ($data['jenis']??'')==='SMP Swasta'?'selected':'' ?>>SMP Swasta</option>
          </select>
        </div>

        <div class="col-md-4">
          <label class="form-label">Kecamatan <span class="text-danger">*</span></label>
          <input type="text" name="kecamatan" class="form-control" value="<?= e($data['kecamatan'] ?? '') ?>" required>
        </div>

        <div class="col-md-4">
          <label class="form-label">Akreditasi</label>
          <select name="akreditasi" class="form-select">
            <option value="">— Pilih —</option>
            <?php foreach(['A','B','C','Belum Terakreditasi'] as $akr): ?>
            <option value="<?= $akr ?>" <?= ($data['akreditasi']??'')===$akr?'selected':'' ?>><?= $akr ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12">
          <label class="form-label">Alamat</label>
          <textarea name="alamat" class="form-control" rows="2"><?= e($data['alamat'] ?? '') ?></textarea>
        </div>

        <div class="col-md-6">
          <label class="form-label">Kepala Sekolah <span class="text-danger">*</span></label>
          <input type="text" name="kepala_sekolah" class="form-control" value="<?= e($data['kepala_sekolah'] ?? '') ?>" required>
        </div>

        <div class="col-md-6">
          <label class="form-label">NIP Kepala Sekolah</label>
          <input type="text" name="nip_kepsek" class="form-control" value="<?= e($data['nip_kepsek'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Telepon</label>
          <input type="text" name="telepon" class="form-control" value="<?= e($data['telepon'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Email</label>
          <input type="email" name="email" class="form-control" value="<?= e($data['email'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Website</label>
          <input type="url" name="website" class="form-control" value="<?= e($data['website'] ?? '') ?>" placeholder="https://...">
        </div>

        <div class="col-md-3">
          <label class="form-label">Jumlah Guru</label>
          <input type="number" name="jumlah_guru" class="form-control" min="0" value="<?= e($data['jumlah_guru'] ?? '') ?>">
        </div>

        <div class="col-md-3">
          <label class="form-label">Jumlah Siswa</label>
          <input type="number" name="jumlah_siswa" class="form-control" min="0" value="<?= e($data['jumlah_siswa'] ?? '') ?>">
        </div>

        <div class="col-md-6 d-flex align-items-end">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="aktif" id="chkAktif" <?= ($data['aktif'] ?? 1) ? 'checked' : '' ?>>
            <label class="form-check-label" for="chkAktif">Sekolah aktif</label>
          </div>
        </div>

        <div class="col-12 pt-2 d-flex gap-2">
          <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i><?= $edit?'Simpan Perubahan':'Tambah Sekolah' ?></button>
          <a href="<?= BASE_URL ?>/modules/sekolah/index.php" class="btn btn-outline-secondary">Batal</a>
        </div>
      </div>
    </form>
  </div>
</div>

<?php require_once ROOT_PATH . '/views/layouts/footer.php'; ?>
