<?php
/**
 * SisPen Snesaka - Reset Password Guru (Admin only)
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Reset Password Guru';
$activeMenu = 'guru';

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

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

$errors  = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['do_reset'])) {
    $mode    = $_POST['mode'] ?? 'manual';
    $pwBaru  = '';

    if ($mode === 'auto') {
        // Generate password acak 8 karakter
        $chars  = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789@#!';
        $pwBaru = '';
        for ($i = 0; $i < 8; $i++) {
            $pwBaru .= $chars[random_int(0, strlen($chars)-1)];
        }
    } else {
        $pwBaru  = $_POST['pw_baru']  ?? '';
        $pwUlang = $_POST['pw_ulang'] ?? '';

        if (strlen($pwBaru) < 6) {
            $errors[] = 'Password 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']]
        );
        $success = true;
        // Simpan password baru sementara untuk ditampilkan
        $_SESSION['_pw_reset_info'] = [
            'nama'     => $guru['nama'],
            'username' => $guru['username'],
            'password' => $pwBaru,
        ];
        setFlash('success', 'Password guru <strong>'.htmlspecialchars($guru['nama']).'</strong> berhasil direset.');
        header('Location: reset_password.php?id='.$id.'&done=1');
        exit;
    }
}

// Tampilkan info password yang baru direset (sekali saja)
$resetInfo = null;
if (isset($_GET['done']) && isset($_SESSION['_pw_reset_info'])) {
    $resetInfo = $_SESSION['_pw_reset_info'];
    unset($_SESSION['_pw_reset_info']);
}

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

<div style="max-width:520px;">

  <!-- Info guru -->
  <div style="display:flex;align-items:center;gap:14px;padding:16px 20px;background:var(--surface);border:1px solid var(--border);border-radius:10px;margin-bottom:20px;">
    <div style="width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,var(--primary-dark),var(--primary));color:#fff;display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:800;flex-shrink:0;">
      <?= strtoupper(substr($guru['nama'],0,1)) ?>
    </div>
    <div>
      <div style="font-weight:700;font-size:15px;"><?= htmlspecialchars($guru['nama']) ?></div>
      <div style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-user" style="width:14px;"></i> Username: <code><?= htmlspecialchars($guru['username']) ?></code>
        &nbsp;&bull;&nbsp;
        <i class="fas fa-id-card" style="width:14px;"></i> NIP: <?= $guru['nip'] ?: '-' ?>
      </div>
    </div>
  </div>

  <?php if ($resetInfo): ?>
  <!-- Tampilkan hasil reset password SEKALI -->
  <div style="background:linear-gradient(135deg,#dcfce7,#bbf7d0);border:1px solid #86efac;border-radius:12px;padding:20px 24px;margin-bottom:20px;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;">
      <div style="width:36px;height:36px;background:#16a34a;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:16px;flex-shrink:0;">
        <i class="fas fa-check"></i>
      </div>
      <div>
        <div style="font-weight:700;color:#15803d;font-size:14px;">Password Berhasil Direset!</div>
        <div style="font-size:12px;color:#166534;">Catat dan sampaikan ke guru yang bersangkutan</div>
      </div>
    </div>

    <div style="background:#fff;border:1px solid #86efac;border-radius:8px;padding:14px 18px;">
      <table style="font-size:13px;width:100%;border-collapse:collapse;">
        <tr>
          <td style="padding:5px 0;color:#475569;width:110px;"><i class="fas fa-user" style="width:16px;color:#16a34a;"></i> Username</td>
          <td style="padding:5px 0;font-weight:700;">
            <code style="background:#f0fdf4;padding:3px 8px;border-radius:4px;font-size:13px;">
              <?= htmlspecialchars($resetInfo['username']) ?>
            </code>
          </td>
        </tr>
        <tr>
          <td style="padding:5px 0;color:#475569;"><i class="fas fa-key" style="width:16px;color:#16a34a;"></i> Password Baru</td>
          <td style="padding:5px 0;font-weight:700;">
            <code style="background:#f0fdf4;padding:3px 10px;border-radius:4px;font-size:15px;letter-spacing:1px;color:#15803d;">
              <?= htmlspecialchars($resetInfo['password']) ?>
            </code>
            <button type="button" onclick="copyPw('<?= htmlspecialchars($resetInfo['password'], ENT_QUOTES) ?>')"
                    style="margin-left:8px;background:none;border:1px solid #86efac;border-radius:6px;padding:3px 8px;cursor:pointer;font-size:11px;color:#15803d;">
              <i class="fas fa-copy"></i> Salin
            </button>
          </td>
        </tr>
      </table>
    </div>

    <div style="margin-top:10px;font-size:11px;color:#166534;">
      <i class="fas fa-exclamation-triangle"></i>
      Informasi ini hanya ditampilkan <strong>sekali</strong>. Segera catat dan sampaikan ke guru.
    </div>
  </div>

  <div style="display:flex;gap:10px;">
    <a href="list.php" class="btn btn-primary">
      <i class="fas fa-arrow-left"></i> Kembali ke Daftar Guru
    </a>
    <a href="reset_password.php?id=<?= $id ?>" class="btn btn-outline">
      <i class="fas fa-redo"></i> Reset Lagi
    </a>
  </div>

  <script>
  function copyPw(pw) {
    navigator.clipboard.writeText(pw).then(function(){
      var btn = event.target.closest('button');
      btn.innerHTML = '<i class="fas fa-check"></i> Tersalin!';
      btn.style.background = '#bbf7d0';
      setTimeout(function(){ btn.innerHTML = '<i class="fas fa-copy"></i> Salin'; btn.style.background=''; }, 2000);
    });
  }
  </script>

  <?php else: ?>
  <!-- Form reset password -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-key" style="color:var(--warning);margin-right:8px;"></i>
        Reset Password
      </span>
      <a href="list.php" class="btn btn-outline btn-sm">
        <i class="fas fa-arrow-left"></i> Batal
      </a>
    </div>
    <div class="card-body">

      <?php if (!empty($errors)): ?>
      <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" id="resetForm">
        <input type="hidden" name="do_reset" value="1">

        <!-- Pilih mode -->
        <div class="form-group" style="margin-bottom:18px;">
          <label class="form-label">Metode Reset</label>
          <div style="display:flex;gap:10px;flex-wrap:wrap;">

            <label style="flex:1;min-width:200px;cursor:pointer;">
              <input type="radio" name="mode" value="auto" id="modeAuto" checked
                     onchange="toggleMode()" style="display:none;">
              <div class="mode-card" id="cardAuto"
                   style="padding:14px 16px;border:2px solid var(--primary);border-radius:10px;background:rgba(26,74,122,.05);transition:all .2s;">
                <div style="display:flex;align-items:center;gap:10px;">
                  <div style="width:36px;height:36px;background:var(--primary);border-radius:8px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:16px;">
                    <i class="fas fa-magic"></i>
                  </div>
                  <div>
                    <div style="font-weight:700;font-size:13px;">Generate Otomatis</div>
                    <div style="font-size:11px;color:var(--text-muted);">Sistem buat password acak 8 karakter</div>
                  </div>
                </div>
              </div>
            </label>

            <label style="flex:1;min-width:200px;cursor:pointer;">
              <input type="radio" name="mode" value="manual" id="modeManual"
                     onchange="toggleMode()" style="display:none;">
              <div class="mode-card" id="cardManual"
                   style="padding:14px 16px;border:2px solid var(--border);border-radius:10px;transition:all .2s;">
                <div style="display:flex;align-items:center;gap:10px;">
                  <div style="width:36px;height:36px;background:var(--text-muted);border-radius:8px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:16px;">
                    <i class="fas fa-pen"></i>
                  </div>
                  <div>
                    <div style="font-weight:700;font-size:13px;">Input Manual</div>
                    <div style="font-size:11px;color:var(--text-muted);">Admin tentukan password sendiri</div>
                  </div>
                </div>
              </div>
            </label>

          </div>
        </div>

        <!-- Form manual (tersembunyi default) -->
        <div id="manualFields" style="display:none;">
          <div class="form-group" style="margin-bottom:12px;">
            <label class="form-label">Password Baru</label>
            <div style="position:relative;">
              <input type="password" name="pw_baru" id="pw_baru" class="form-control"
                     placeholder="Min. 6 karakter" autocomplete="new-password"
                     style="padding-right:40px;" 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);">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <div style="margin-top:4px;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:18px;">
            <label class="form-label">Konfirmasi Password Baru</label>
            <div style="position:relative;">
              <input type="password" name="pw_ulang" id="pw_ulang" class="form-control"
                     placeholder="Ulangi password" autocomplete="new-password"
                     style="padding-right:40px;" 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);">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <div id="matchText" style="font-size:10px;margin-top:2px;"></div>
          </div>
        </div>

        <!-- Warning -->
        <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:8px;padding:10px 14px;margin-bottom:16px;font-size:12px;color:#92400e;display:flex;gap:8px;align-items:flex-start;">
          <i class="fas fa-exclamation-triangle" style="margin-top:1px;flex-shrink:0;"></i>
          <div>Password lama guru <strong><?= htmlspecialchars($guru['nama']) ?></strong> akan <strong>langsung diganti</strong>. Guru harus login ulang dengan password baru.</div>
        </div>

        <div style="display:flex;gap:10px;">
          <button type="submit" class="btn btn-primary" style="flex:1;justify-content:center;">
            <i class="fas fa-key"></i> Reset Password Sekarang
          </button>
          <a href="list.php" class="btn btn-outline">Batal</a>
        </div>
      </form>
    </div>
  </div>

  <script>
  function toggleMode() {
    var isAuto   = document.getElementById('modeAuto').checked;
    var cardAuto = document.getElementById('cardAuto');
    var cardMan  = document.getElementById('cardManual');
    var fields   = document.getElementById('manualFields');
    var baru     = document.getElementById('pw_baru');
    var ulang    = document.getElementById('pw_ulang');

    if (isAuto) {
      cardAuto.style.border = '2px solid var(--primary)';
      cardAuto.style.background = 'rgba(26,74,122,.05)';
      cardMan.style.border  = '2px solid var(--border)';
      cardMan.style.background = '';
      fields.style.display  = 'none';
      if (baru)  baru.removeAttribute('required');
      if (ulang) ulang.removeAttribute('required');
    } else {
      cardMan.style.border  = '2px solid var(--primary)';
      cardMan.style.background = 'rgba(26,74,122,.05)';
      cardAuto.style.border = '2px solid var(--border)';
      cardAuto.style.background = '';
      fields.style.display  = 'block';
      if (baru)  baru.setAttribute('required','required');
      if (ulang) ulang.setAttribute('required','required');
    }
  }

  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'; }
  }

  function checkStrength(val) {
    var bar = document.getElementById('strengthBar');
    var txt = document.getElementById('strengthText');
    var s = 0;
    if (val.length >= 6)  s++;
    if (val.length >= 10) s++;
    if (/[A-Z]/.test(val)) s++;
    if (/[0-9]/.test(val)) s++;
    if (/[^A-Za-z0-9]/.test(val)) s++;
    var lv = [
      {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 l = lv[Math.min(s,4)];
    bar.style.width = l.w; bar.style.background = l.c;
    txt.textContent = l.t; txt.style.color = l.c;
  }

  function checkMatch() {
    var b = document.getElementById('pw_baru').value;
    var u = document.getElementById('pw_ulang').value;
    var el = document.getElementById('matchText');
    if (!u) { el.textContent=''; return; }
    if (b === u) { el.textContent='✓ Password cocok'; el.style.color='#16a34a'; }
    else         { el.textContent='✗ Tidak cocok';     el.style.color='#dc2626'; }
  }
  </script>
  <?php endif; ?>

</div>

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