<?php
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';
requireAdmin();
$pageTitle = 'Tambah Guru';
$activeMenu = 'guru';
$errors = [];
$data = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    $v = validate($data)
        ->required('nama', 'Nama Guru')
        ->required('nip', 'NIP')
        ->required('jenis_kelamin', 'Jenis Kelamin');

    if ($v->fails()) {
        $errors = $v->getErrors();
    } else {
        global $pdo;

        // Username dari NIP, jika sudah dipakai tambah suffix
        $username = sanitize($data['nip']);
        $suffix = 1;
        while (db_fetch("SELECT id FROM users WHERE username = ?", [$username])) {
            $username = sanitize($data['nip']) . '_' . $suffix;
            $suffix++;
        }

        $pdo->beginTransaction();
        try {
            $userId = db_insert('users', [
                'username'     => $username,
                'password'     => password_hash($data['nip'], PASSWORD_DEFAULT),
                'nama_lengkap' => sanitize($data['nama']),
                'role'         => 'guru',
                'email'        => sanitize($data['email'] ?? ''),
                'status'       => 'aktif',
            ]);
            db_insert('guru', [
                'user_id'      => $userId,
                'nip'          => sanitize($data['nip']),
                'nama'         => sanitize($data['nama']),
                'jenis_kelamin'=> $data['jenis_kelamin'],
                'email'        => sanitize($data['email'] ?? ''),
                'telepon'      => sanitize($data['telepon'] ?? ''),
                'status'       => 'aktif',
            ]);
            $pdo->commit();
            setFlash('success', 'Guru berhasil ditambahkan! Username: <strong>' . htmlspecialchars($username) . '</strong>, Password: <strong>' . htmlspecialchars($data['nip']) . '</strong>');
            header('Location: list.php'); exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors['global'] = 'Gagal menyimpan: ' . $e->getMessage();
        }
    }
}

include '../../templates/header.php';
?>
<div class="card" style="max-width:700px;">
  <div class="card-header">
    <span class="card-title">Tambah Guru 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-circle"></i> <?= implode(', ', $errors) ?></div>
    <?php endif; ?>
    <form method="POST">
      <div class="form-group">
        <label class="form-label">Nama Lengkap <span class="required">*</span></label>
        <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($data['nama'] ?? '') ?>" required>
      </div>
      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">NIP <span class="required">*</span></label>
          <input type="text" name="nip" class="form-control" value="<?= htmlspecialchars($data['nip'] ?? '') ?>" required>
          <small style="color:var(--text-muted);font-size:11px;"><i class="fas fa-info-circle"></i> Username &amp; password login akan dibuat otomatis dari NIP</small>
        </div>
        <div class="form-group">
          <label class="form-label">Jenis Kelamin <span class="required">*</span></label>
          <select name="jenis_kelamin" class="form-control">
            <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>
      <div class="form-row cols-2">
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($data['email'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Telepon</label>
          <input type="text" name="telepon" class="form-control" value="<?= htmlspecialchars($data['telepon'] ?? '') ?>">
        </div>
      </div>
      <div style="display:flex;gap:10px;">
        <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'; ?>