<?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 users WHERE id=?", [$id]);
    if (!$data) { setFlash('error','User tidak ditemukan.'); redirect(BASE_URL.'/modules/users/index.php'); }
}

$sekolahList = Database::fetchAll("SELECT id, nama_sekolah FROM sekolah WHERE aktif=1 ORDER BY nama_sekolah");
$errors = [];

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

    $fields = [
        'nama'       => sanitize($_POST['nama'] ?? ''),
        'username'   => sanitize($_POST['username'] ?? ''),
        'email'      => sanitize($_POST['email'] ?? ''),
        'role'       => sanitize($_POST['role'] ?? 'dinas'),
        'sekolah_id' => (int)($_POST['sekolah_id'] ?? 0) ?: null,
        'aktif'      => isset($_POST['aktif']) ? 1 : 0,
    ];
    $password     = $_POST['password'] ?? '';
    $passwordConf = $_POST['password_conf'] ?? '';

    if (empty($fields['nama']))     $errors[] = 'Nama wajib diisi.';
    if (empty($fields['username'])) $errors[] = 'Username wajib diisi.';
    if (empty($fields['email']))    $errors[] = 'Email wajib diisi.';
    if (!filter_var($fields['email'], FILTER_VALIDATE_EMAIL)) $errors[] = 'Format email tidak valid.';

    if (!$edit || !empty($password)) {
        if (strlen($password) < 8)          $errors[] = 'Password minimal 8 karakter.';
        if ($password !== $passwordConf)    $errors[] = 'Konfirmasi password tidak cocok.';
    }

    if ($fields['role'] === 'sekolah' && !$fields['sekolah_id']) {
        $errors[] = 'Pilih sekolah untuk role Sekolah.';
    }

    // Cek duplikat
    $dupU = Database::fetchOne("SELECT id FROM users WHERE username=? AND id<>?", [$fields['username'], $id]);
    if ($dupU) $errors[] = 'Username sudah digunakan.';
    $dupE = Database::fetchOne("SELECT id FROM users WHERE email=? AND id<>?", [$fields['email'], $id]);
    if ($dupE) $errors[] = 'Email sudah digunakan.';

    if (empty($errors)) {
        if (!$edit || !empty($password)) {
            $fields['password'] = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        }

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

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

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-person-gear 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/users/index.php">Users</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="row justify-content-center">
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header"><span class="card-header-title"><i class="bi bi-person-plus me-2"></i>Form User</span></div>
      <div class="card-body">
        <form method="POST">
          <?= csrf_field() ?>
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
              <input type="text" name="nama" class="form-control" value="<?= e($data['nama'] ?? '') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Username <span class="text-danger">*</span></label>
              <input type="text" name="username" class="form-control" value="<?= e($data['username'] ?? '') ?>" required autocomplete="off">
            </div>
            <div class="col-md-6">
              <label class="form-label">Email <span class="text-danger">*</span></label>
              <input type="email" name="email" class="form-control" value="<?= e($data['email'] ?? '') ?>" required autocomplete="off">
            </div>
            <div class="col-md-6">
              <label class="form-label">Password <?= $edit ? '' : '<span class="text-danger">*</span>' ?></label>
              <input type="password" name="password" class="form-control" autocomplete="new-password"
                     placeholder="<?= $edit ? 'Kosongkan jika tidak diubah' : 'Min. 8 karakter' ?>" <?= $edit?'':'required' ?>>
            </div>
            <div class="col-md-6">
              <label class="form-label">Konfirmasi Password <?= $edit ? '' : '<span class="text-danger">*</span>' ?></label>
              <input type="password" name="password_conf" class="form-control" autocomplete="new-password"
                     placeholder="Ulangi password" <?= $edit?'':'required' ?>>
            </div>
            <div class="col-md-6">
              <label class="form-label">Role / Hak Akses <span class="text-danger">*</span></label>
              <select name="role" class="form-select" id="roleSelect">
                <option value="admin"   <?= ($data['role']??'')==='admin'?'selected':'' ?>>Administrator</option>
                <option value="dinas"   <?= ($data['role']??'')==='dinas'?'selected':'' ?>>Dinas Pendidikan</option>
                <option value="sekolah" <?= ($data['role']??'')==='sekolah'?'selected':'' ?>>Sekolah</option>
              </select>
            </div>
            <div class="col-md-6" id="sekolahGroup" style="<?= ($data['role']??'') !== 'sekolah' ? 'display:none' : '' ?>">
              <label class="form-label">Sekolah</label>
              <select name="sekolah_id" class="form-select">
                <option value="">— Pilih Sekolah —</option>
                <?php foreach($sekolahList as $s): ?>
                <option value="<?= $s['id'] ?>" <?= ($data['sekolah_id']??0)==(int)$s['id']?'selected':'' ?>><?= e($s['nama_sekolah']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <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">Akun aktif</label>
              </div>
            </div>

            <!-- Info Role -->
            <div class="col-12">
              <div class="alert border-0 mb-0 py-2 px-3" id="roleInfo" style="font-size:.8rem;background:#f0f4f8">
                <i class="bi bi-info-circle me-1"></i>
                <span id="roleInfoText">Pilih role untuk melihat hak akses.</span>
              </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 User' ?></button>
              <a href="<?= BASE_URL ?>/modules/users/index.php" class="btn btn-outline-secondary">Batal</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php
$extraJs = <<<JS
<script>
const roleInfo = {
  admin:   'Administrator: Dapat mengelola seluruh data, user, dan hak akses.',
  dinas:   'Dinas Pendidikan: Dapat melihat seluruh isi aplikasi. Tidak dapat menghapus/mengedit.',
  sekolah: 'Sekolah: Hanya dapat melihat data sekolah yang bersangkutan saja.',
};
const roleSelect   = document.getElementById('roleSelect');
const sekolahGroup = document.getElementById('sekolahGroup');
const roleInfoText = document.getElementById('roleInfoText');

function updateRole() {
  const r = roleSelect.value;
  sekolahGroup.style.display = r === 'sekolah' ? '' : 'none';
  roleInfoText.textContent = roleInfo[r] || '';
}
roleSelect.addEventListener('change', updateRole);
updateRole();
</script>
JS;
require_once ROOT_PATH . '/views/layouts/footer.php';
?>
