<?php
/**
 * SisPen Snesaka - Edit Profil Guru (self-service)
 */
require_once '../../includes/functions.php';
requireLogin();

// Halaman ini untuk guru sendiri, bukan admin
$pageTitle  = 'Profil Saya';
$activeMenu = 'profil';
$guruId     = $_SESSION['guru_id'] ?? 0;

if (!$guruId) {
    setFlash('danger', 'Data guru tidak ditemukan.');
    header('Location: ' . BASE_URL . '/guru.php');
    exit;
}

$guru = db_fetch(
    "SELECT g.*, u.username FROM guru g JOIN users u ON u.id=g.user_id WHERE g.id=?",
    [$guruId]
);

if (!$guru) {
    setFlash('danger', 'Data guru tidak ditemukan.');
    header('Location: ' . BASE_URL . '/guru.php');
    exit;
}

$errors  = [];
$success = false;

// ── Handle simpan profil ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_profil'])) {
    $nama      = trim(sanitize($_POST['nama'] ?? ''));
    $telepon   = trim(sanitize($_POST['telepon'] ?? ''));
    $email     = trim(sanitize($_POST['email'] ?? ''));
    $alamat    = trim(sanitize($_POST['alamat'] ?? ''));
    $tglLahir  = $_POST['tanggal_lahir'] ?? '';
    $tmpLahir  = trim(sanitize($_POST['tempat_lahir'] ?? ''));
    $pendidikan= trim(sanitize($_POST['pendidikan_terakhir'] ?? ''));
    $jurusan   = trim(sanitize($_POST['jurusan'] ?? ''));

    if (empty($nama)) $errors[] = 'Nama lengkap tidak boleh kosong.';
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Format email tidak valid.';

    if (empty($errors)) {
        db_update('guru', [
            'nama'               => $nama,
            'telepon'            => $telepon,
            'email'              => $email,
            'alamat'             => $alamat,
            'tanggal_lahir'      => $tglLahir ?: null,
            'tempat_lahir'       => $tmpLahir,
            'pendidikan_terakhir'=> $pendidikan,
            'jurusan'            => $jurusan,
        ], 'id=:id', ['id' => $guruId]);

        // Update nama di tabel users juga
        db_update('users',
            ['nama_lengkap' => $nama, 'email' => $email],
            'id=:id', ['id' => $guru['user_id']]
        );

        // Update nama di session
        $_SESSION['nama'] = $nama;

        setFlash('success', 'Profil berhasil diperbarui!');
        header('Location: profil.php');
        exit;
    }
}

// ── Handle ganti password ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_password'])) {
    $pwLama  = $_POST['pw_lama']   ?? '';
    $pwBaru  = $_POST['pw_baru']   ?? '';
    $pwUlang = $_POST['pw_ulang']  ?? '';

    // Ambil password dari users
    $userRow = db_fetch("SELECT password FROM users WHERE id=?", [$guru['user_id']]);

    if (!password_verify($pwLama, $userRow['password'])) {
        $errors[] = 'Password lama tidak sesuai.';
    } elseif (strlen($pwBaru) < 6) {
        $errors[] = 'Password baru minimal 6 karakter.';
    } elseif ($pwBaru !== $pwUlang) {
        $errors[] = 'Konfirmasi password tidak cocok.';
    }

    if (empty($errors)) {
        db_update('users',
            ['password' => password_hash($pwBaru, PASSWORD_DEFAULT)],
            'id=:id', ['id' => $guru['user_id']]
        );
        setFlash('success', 'Password berhasil diubah! Silakan login ulang.');
        header('Location: profil.php');
        exit;
    }
}

// Refresh data guru setelah POST
$guru = db_fetch(
    "SELECT g.*, u.username FROM guru g JOIN users u ON u.id=g.user_id WHERE g.id=?",
    [$guruId]
);

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

// Info wali kelas / BK
$pengaturan = getPengaturan();
$ta  = $pengaturan['tahun_ajaran_aktif'];
$sem = $pengaturan['semester_aktif'];
$kelasWali = db_fetch(
    "SELECT nama_kelas FROM kelas WHERE wali_kelas_id=? AND tahun_ajaran=? AND semester=? LIMIT 1",
    [$guruId, $ta, $sem]
);
$isBK = !empty($guru['is_bk']);
?>

<div style="display:grid;grid-template-columns:280px 1fr;gap:20px;align-items:start;">

  <!-- ── Kartu profil kiri ─────────────────────────────── -->
  <div>
    <!-- Avatar card -->
    <div class="card" style="text-align:center;padding:28px 20px;margin-bottom:16px;">
      <div style="width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,var(--primary-dark),var(--primary));color:#fff;display:flex;align-items:center;justify-content:center;font-size:32px;font-weight:800;margin:0 auto 14px;">
        <?= strtoupper(substr($guru['nama'], 0, 1)) ?>
      </div>
      <div style="font-size:16px;font-weight:700;margin-bottom:4px;"><?= htmlspecialchars($guru['nama']) ?></div>
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:10px;">
        @<?= htmlspecialchars($guru['username']) ?>
      </div>

      <!-- Badge peran -->
      <div style="display:flex;flex-wrap:wrap;gap:6px;justify-content:center;margin-bottom:14px;">
        <?php if ($isBK): ?>
        <span class="badge badge-warning"><i class="fas fa-user-md"></i> Guru BK</span>
        <?php endif; ?>
        <?php if ($kelasWali): ?>
        <span class="badge badge-success"><i class="fas fa-chalkboard-teacher"></i> Wali <?= htmlspecialchars($kelasWali['nama_kelas']) ?></span>
        <?php endif; ?>
        <?php if (!$isBK && !$kelasWali): ?>
        <span class="badge badge-blue"><i class="fas fa-chalkboard"></i> Guru Mapel</span>
        <?php endif; ?>
      </div>

      <div style="font-size:12px;color:var(--text-muted);border-top:1px solid var(--border);padding-top:12px;">
        <div style="margin-bottom:5px;">
          <i class="fas fa-id-card" style="width:16px;color:var(--primary);"></i>
          NIP: <strong><?= $guru['nip'] ?: '-' ?></strong>
        </div>
        <?php if ($guru['telepon']): ?>
        <div style="margin-bottom:5px;">
          <i class="fas fa-phone" style="width:16px;color:var(--primary);"></i>
          <?= htmlspecialchars($guru['telepon']) ?>
        </div>
        <?php endif; ?>
        <?php if ($guru['email']): ?>
        <div>
          <i class="fas fa-envelope" style="width:16px;color:var(--primary);"></i>
          <?= htmlspecialchars($guru['email']) ?>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Ganti password -->
    <div class="card">
      <div class="card-header">
        <span class="card-title" style="font-size:13px;">
          <i class="fas fa-lock" style="color:var(--warning);margin-right:6px;"></i>
          Ganti Password
        </span>
      </div>
      <div class="card-body">
        <?php if (!empty($errors) && isset($_POST['save_password'])): ?>
        <div class="alert alert-danger" style="font-size:12px;padding:10px 12px;margin-bottom:12px;">
          <?php foreach ($errors as $e): ?>
          <div><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($e) ?></div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <form method="POST">
          <input type="hidden" name="save_password" value="1">
          <div class="form-group" style="margin-bottom:10px;">
            <label class="form-label" style="font-size:12px;">Password Lama</label>
            <div style="position:relative;">
              <input type="password" name="pw_lama" id="pw_lama" class="form-control"
                     placeholder="••••••••" required autocomplete="current-password"
                     style="padding-right:36px;">
              <button type="button" onclick="togglePw('pw_lama',this)"
                      style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-muted);padding:0;">
                <i class="fas fa-eye"></i>
              </button>
            </div>
          </div>
          <div class="form-group" style="margin-bottom:10px;">
            <label class="form-label" style="font-size:12px;">Password Baru</label>
            <div style="position:relative;">
              <input type="password" name="pw_baru" id="pw_baru" class="form-control"
                     placeholder="Min. 6 karakter" required autocomplete="new-password"
                     style="padding-right:36px;" oninput="checkStrength(this.value)">
              <button type="button" onclick="togglePw('pw_baru',this)"
                      style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-muted);padding:0;">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <!-- Password strength bar -->
            <div style="margin-top:5px;height:4px;background:var(--border);border-radius:99px;overflow:hidden;">
              <div id="strengthBar" style="height:100%;width:0%;border-radius:99px;transition:all .3s;"></div>
            </div>
            <div id="strengthText" style="font-size:10px;color:var(--text-muted);margin-top:2px;"></div>
          </div>
          <div class="form-group" style="margin-bottom:14px;">
            <label class="form-label" style="font-size:12px;">Konfirmasi Password Baru</label>
            <div style="position:relative;">
              <input type="password" name="pw_ulang" id="pw_ulang" class="form-control"
                     placeholder="Ulangi password baru" required autocomplete="new-password"
                     style="padding-right:36px;" oninput="checkMatch()">
              <button type="button" onclick="togglePw('pw_ulang',this)"
                      style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-muted);padding:0;">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <div id="matchText" style="font-size:10px;margin-top:2px;"></div>
          </div>
          <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;">
            <i class="fas fa-lock"></i> Ganti Password
          </button>
        </form>
      </div>
    </div>
  </div>

  <!-- ── Form edit profil kanan ────────────────────────── -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-user-edit" style="color:var(--primary);margin-right:8px;"></i>
        Edit Profil
      </span>
      <a href="<?= BASE_URL ?>/guru.php" class="btn btn-outline btn-sm">
        <i class="fas fa-arrow-left"></i> Dashboard
      </a>
    </div>
    <div class="card-body">

      <?php if (!empty($errors) && isset($_POST['save_profil'])): ?>
      <div class="alert alert-danger" style="margin-bottom:16px;">
        <?php foreach ($errors as $e): ?>
        <div><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <form method="POST">
        <input type="hidden" name="save_profil" value="1">

        <!-- Nama -->
        <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($guru['nama']) ?>" required>
        </div>

        <!-- NIP + Username (readonly) -->
        <div class="form-row cols-2">
          <div class="form-group">
            <label class="form-label">NIP</label>
            <input type="text" class="form-control"
                   value="<?= htmlspecialchars($guru['nip'] ?? '') ?>"
                   readonly style="background:var(--surface-2);color:var(--text-muted);">
            <div style="font-size:11px;color:var(--text-muted);margin-top:3px;">
              <i class="fas fa-lock" style="font-size:9px;"></i> Hubungi admin untuk mengubah NIP
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Username</label>
            <input type="text" class="form-control"
                   value="<?= htmlspecialchars($guru['username']) ?>"
                   readonly style="background:var(--surface-2);color:var(--text-muted);">
            <div style="font-size:11px;color:var(--text-muted);margin-top:3px;">
              <i class="fas fa-lock" style="font-size:9px;"></i> Username tidak dapat diubah
            </div>
          </div>
        </div>

        <!-- JK + Tempat Lahir -->
        <div class="form-row cols-2">
          <div class="form-group">
            <label class="form-label">Jenis Kelamin</label>
            <input type="text" class="form-control"
                   value="<?= $guru['jenis_kelamin']==='L'?'Laki-laki':'Perempuan' ?>"
                   readonly style="background:var(--surface-2);color:var(--text-muted);">
          </div>
          <div class="form-group">
            <label class="form-label">Tempat Lahir</label>
            <input type="text" name="tempat_lahir" class="form-control"
                   value="<?= htmlspecialchars($guru['tempat_lahir'] ?? '') ?>"
                   placeholder="Kota kelahiran">
          </div>
        </div>

        <!-- Tanggal Lahir -->
        <div class="form-row cols-2">
          <div class="form-group">
            <label class="form-label">Tanggal Lahir</label>
            <input type="date" name="tanggal_lahir" class="form-control"
                   value="<?= htmlspecialchars($guru['tanggal_lahir'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Telepon / HP</label>
            <input type="text" name="telepon" class="form-control"
                   value="<?= htmlspecialchars($guru['telepon'] ?? '') ?>"
                   placeholder="08xx-xxxx-xxxx">
          </div>
        </div>

        <!-- Email -->
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="email" name="email" class="form-control"
                 value="<?= htmlspecialchars($guru['email'] ?? '') ?>"
                 placeholder="nama@email.com">
        </div>

        <!-- Pendidikan + Jurusan -->
        <div class="form-row cols-2">
          <div class="form-group">
            <label class="form-label">Pendidikan Terakhir</label>
            <select name="pendidikan_terakhir" class="form-control">
              <option value="">-- Pilih --</option>
              <?php foreach (['D3','S1','S2','S3'] as $p): ?>
              <option value="<?= $p ?>" <?= ($guru['pendidikan_terakhir']??'')===$p?'selected':'' ?>><?= $p ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Jurusan / Prodi</label>
            <input type="text" name="jurusan" class="form-control"
                   value="<?= htmlspecialchars($guru['jurusan'] ?? '') ?>"
                   placeholder="Contoh: Pendidikan Matematika">
          </div>
        </div>

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

        <div style="display:flex;gap:10px;justify-content:flex-end;padding-top:8px;border-top:1px solid var(--border);margin-top:8px;">
          <a href="<?= BASE_URL ?>/guru.php" class="btn btn-outline">Batal</a>
          <button type="submit" class="btn btn-primary">
            <i class="fas fa-save"></i> Simpan Profil
          </button>
        </div>
      </form>
    </div>
  </div>

</div>

<script>
// Toggle show/hide password
function togglePw(id, btn) {
    var inp = document.getElementById(id);
    var icon = btn.querySelector('i');
    if (inp.type === 'password') {
        inp.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        inp.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

// Password strength indicator
function checkStrength(val) {
    var bar  = document.getElementById('strengthBar');
    var text = document.getElementById('strengthText');
    var score = 0;
    if (val.length >= 6)  score++;
    if (val.length >= 10) score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;

    var levels = [
        {w:'0%',   c:'',         t:''},
        {w:'25%',  c:'#ef4444',  t:'Lemah'},
        {w:'50%',  c:'#f97316',  t:'Cukup'},
        {w:'75%',  c:'#eab308',  t:'Baik'},
        {w:'100%', c:'#22c55e',  t:'Kuat'},
    ];
    var lv = levels[Math.min(score, 4)];
    bar.style.width     = lv.w;
    bar.style.background= lv.c;
    text.textContent    = lv.t;
    text.style.color    = lv.c;
}

// Konfirmasi password match
function checkMatch() {
    var baru  = document.getElementById('pw_baru').value;
    var ulang = document.getElementById('pw_ulang').value;
    var el    = document.getElementById('matchText');
    if (!ulang) { el.textContent = ''; return; }
    if (baru === ulang) {
        el.textContent = '✓ Password cocok';
        el.style.color = '#16a34a';
    } else {
        el.textContent = '✗ Password tidak cocok';
        el.style.color = '#dc2626';
    }
}
</script>

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