<?php
session_start();
require_once __DIR__ . '/db.php';

// ===== Auth: admin =====
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
  header('Location: login.php'); exit;
}

// ===== CSRF =====
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf_token'];

// ===== Helper get/set config (mysqli) =====
function cfg_get(mysqli $conn, string $name, string $default){
  $stmt = $conn->prepare("SELECT value FROM password_reset_config WHERE name=? LIMIT 1");
  $stmt->bind_param("s", $name);
  $stmt->execute();
  $res = $stmt->get_result();
  $row = $res ? $res->fetch_assoc() : null;
  $stmt->close();
  return ($row && isset($row['value']) && $row['value'] !== '') ? (string)$row['value'] : $default;
}
function cfg_set(mysqli $conn, string $name, string $value){
  $stmt = $conn->prepare("INSERT INTO password_reset_config(name,value) VALUES(?,?)
                          ON DUPLICATE KEY UPDATE value=VALUES(value)");
  $stmt->bind_param("ss", $name, $value);
  $stmt->execute();
  $stmt->close();
}

// ===== Flash (untuk mesej berjaya/ralat) =====
$flash = $_SESSION['prc_flash'] ?? '';
unset($_SESSION['prc_flash']);
$flash_type = '';
if ($flash !== '') {
  // heuristik mudah: tentukan ralat jika mengandungi perkataan tertentu
  $s = strtolower($flash);
  $is_err = (strpos($s,'invalid')!==false) || (strpos($s,'error')!==false) || (strpos($s,'ralat')!==false) || (strpos($s,'gagal')!==false);
  $flash_type = $is_err ? 'error' : 'success';
}

// ===== Handle POST save settings (PRG) =====
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['act'] ?? '') === 'save_settings') {
  if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    $len = max(8,  min(64, (int)($_POST['temp_password_length'] ?? 12)));
    $hrs = max(1,  min(72, (int)($_POST['retain_hours'] ?? 4)));
    $max = max(0,  min(10, (int)($_POST['max_reveals'] ?? 3)));
    cfg_set($conn,'temp_password_length', (string)$len);
    cfg_set($conn,'retain_hours', (string)$hrs);
    cfg_set($conn,'max_reveals', (string)$max);
    $_SESSION['prc_flash'] = 'Settings saved.';
  } else {
    $_SESSION['prc_flash'] = 'Invalid token.';
  }
  header('Location: password-reset-center.php'); exit;
}

// ===== Read settings =====
$TEMP_LEN = (int)cfg_get($conn,'temp_password_length','12');
$RETAIN_H = (int)cfg_get($conn,'retain_hours','4');
$MAX_REV  = (int)cfg_get($conn,'max_reveals','3');

// ===== History (last 100 handled) =====
$stmt = $conn->prepare("
  SELECT r.id, r.member_id, r.staff_number, r.email, r.ic_last4, r.phone,
         r.status, r.requested_at, r.handled_at, r.handled_by,
         r.temp_password_expires_at, r.temp_password_views, r.temp_password_max_views,
         r.temp_password_enc, r.temp_password_iv, r.temp_password_tag,
         m.full_name, u.full_name AS admin_name
  FROM password_reset_requests r
  LEFT JOIN members m ON m.id=r.member_id
  LEFT JOIN members u ON u.id=r.handled_by
  WHERE r.status IN ('completed','rejected')
  ORDER BY r.handled_at DESC
  LIMIT 100
");
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ===== Build content untuk layout.php =====
ob_start();
?>
<style>
/* Self-contained styles */
.card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
.card-header{padding:14px 16px;border-bottom:1px solid #f0f0f0;font-weight:700}
.card-body{padding:14px 16px}
.tabs{display:flex;gap:8px;margin-bottom:12px}
.tab{padding:8px 12px;border-radius:8px;background:#e5e7eb;text-decoration:none;color:#111}
.tab.active{background:#2563eb;color:#fff}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
label{display:block;font-weight:700;margin-bottom:6px}
input[type=number]{width:100%;padding:10px;border:1px solid #ddd;border-radius:8px}
button{padding:10px 14px;border-radius:8px;border:1px solid #2563eb;background:#2563eb;color:#fff;cursor:pointer}
table{width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden}
th,td{padding:10px 12px;border-bottom:1px solid #eee;text-align:left}
th{background:#fafafa;font-size:13px;text-transform:uppercase;color:#4b5563}
.muted{color:#6b7280;font-size:12px}
.actions button{padding:6px 10px;border-radius:8px;border:0;cursor:pointer}
.btn-reveal{background:#16a34a;color:#fff}
.btn-disabled{background:#e5e7eb;color:#666;cursor:not-allowed}
.badge{display:inline-block;padding:3px 8px;border-radius:9999px;font-size:12px;font-weight:600}
.badge-ok{background:#ecfdf5;color:#065f46;border:1px solid #a7f3d0}
.badge-exp{background:#fee2e2;color:#991b1b;border:1px solid #fecaca}
.badge-rej{background:#f1f5f9;color:#475569;border:1px solid #e2e8f0}

/* ===== Flash (centered message + close + auto-hide) ===== */
.flash{
  position:relative;
  display:flex; align-items:flex-start; gap:10px;
  padding:12px 40px 12px 12px; border-radius:12px; margin:0 0 14px;
  border:1px solid; box-shadow:0 2px 8px rgba(2,6,23,.06);
}
.flash.success{ background:#ecfdf5; border-color:#a7f3d0; color:#065f46; }
.flash.error  { background:#fef2f2; border-color:#fecaca; color:#991b1b; }
.flash .msg{ flex:1; text-align:center; }
.flash .close{
  position:absolute; top:8px; right:10px;
  border:0; background:transparent; font-size:18px; cursor:pointer; line-height:1;
}
</style>

<div class="content">
  <h2 class="m-0">🔐 Password Reset Center</h2>

  <div class="tabs">
    <a class="tab active" href="#">Settings</a>
    <a class="tab" href="#history" onclick="document.getElementById('history').scrollIntoView({behavior:'smooth'})">History</a>
  </div>

  <div class="card">
    <div class="card-header">Settings</div>
    <div class="card-body">
      <?php if ($flash): ?>
        <div class="flash <?= htmlspecialchars($flash_type ?: 'success') ?>" id="flashBox" role="alert" aria-live="<?= $flash_type==='error'?'assertive':'polite' ?>">
          <div class="msg">
            <strong><?= $flash_type==='error' ? 'Error:' : 'Success:' ?></strong>
            <span><?= htmlspecialchars($flash) ?></span>
          </div>
          <button class="close" aria-label="Close" onclick="this.parentElement.remove()">×</button>
        </div>
      <?php endif; ?>

      <form method="post">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
        <input type="hidden" name="act" value="save_settings">
        <div class="grid">
          <div>
            <label>Panjang password sementara</label>
            <input type="number" name="temp_password_length" min="8" max="64" value="<?= (int)$TEMP_LEN ?>">
            <div class="muted">8–64 aksara</div>
          </div>
          <div>
            <label>Tempoh simpan (jam)</label>
            <input type="number" name="retain_hours" min="1" max="72" value="<?= (int)$RETAIN_H ?>">
            <div class="muted">Berapa lama salinan boleh direveal semula</div>
          </div>
          <div>
            <label>Maksimum “Reveal”</label>
            <input type="number" name="max_reveals" min="0" max="10" value="<?= (int)$MAX_REV ?>">
            <div class="muted">0 = tak simpan salinan (disyorkan ≥1)</div>
          </div>
        </div>
        <div style="margin-top:12px"><button type="submit">Simpan</button></div>
      </form>
    </div>
  </div>

  <h3 id="history" style="margin:18px 0 10px">History</h3>
  <div class="card">
    <div class="card-body" style="padding:0">
      <table>
        <thead>
          <tr>
            <th>Handled At</th>
            <th>Nama</th>
            <th>Staff/Email</th>
            <th>Status</th>
            <th>Reveal</th>
            <th>Tindakan</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="6" class="muted" style="text-align:center">Tiada rekod.</td></tr>
          <?php else: foreach($rows as $r):
            $expired = ($r['temp_password_expires_at'] && strtotime($r['temp_password_expires_at']) < time());
            $done    = ($r['status'] === 'completed');
            $left    = (int)$r['temp_password_max_views'] - (int)$r['temp_password_views'];
          ?>
            <tr>
              <td><?= htmlspecialchars($r['handled_at'] ?: '-') ?><br>
                  <span class="muted">by <?= htmlspecialchars($r['admin_name'] ?: '-') ?></span></td>
              <td><?= htmlspecialchars($r['full_name'] ?: '-') ?><br>
                  <span class="muted">IC(4): <?= htmlspecialchars($r['ic_last4'] ?: '-') ?></span></td>
              <td><?= htmlspecialchars($r['staff_number'] ?: '-') ?><br>
                  <a class="muted" href="mailto:<?= htmlspecialchars($r['email']) ?>"><?= htmlspecialchars($r['email']) ?></a></td>
              <td>
                <?php if ($r['status']==='completed'): ?>
                  <span class="badge <?= $expired?'badge-exp':'badge-ok' ?>"><?= $expired?'Expired':'Completed' ?></span><br>
                  <span class="muted">Exp: <?= htmlspecialchars($r['temp_password_expires_at'] ?: '-') ?></span><br>
                  <span class="muted">Views: <?= (int)$r['temp_password_views'] ?>/<?= (int)$r['temp_password_max_views'] ?></span>
                <?php else: ?>
                  <span class="badge badge-rej">Rejected</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if ($done && !$expired && $left>0 && $r['temp_password_enc']): ?>
                  Boleh reveal (<?= $left ?>x tinggal)
                <?php elseif ($done && $expired): ?>
                  <span class="muted">Expired</span>
                <?php elseif ($done && $left<=0): ?>
                  <span class="muted">Max reveal reached</span>
                <?php else: ?>
                  —
                <?php endif; ?>
              </td>
              <td>
                <?php if ($done && !$expired && $left>0 && $r['temp_password_enc']): ?>
                  <form method="post" action="admin-password-reveal.php" style="display:inline">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
                    <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
                    <button class="btn-reveal" type="submit">Reveal</button>
                  </form>
                <?php else: ?>
                  <button class="btn-disabled" type="button" disabled>Reveal</button>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php if (!empty($_SESSION['temp_password'])):
  $tmp = $_SESSION['temp_password'];
  $who = $_SESSION['temp_password_for'] ?? '';
  unset($_SESSION['temp_password'], $_SESSION['temp_password_for']);
?>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
    const tmpPass = <?= json_encode($tmp) ?>;
    const who     = <?= json_encode($who) ?>;
    Swal.fire({
      title: 'Kata laluan sementara',
      html: `
        <div style="text-align:left">
          ${who ? `<div style="font-size:13px;margin-bottom:6px;color:#555">Untuk: <b>${who}</b></div>` : ``}
          <div style="font-size:13px;margin-bottom:10px;color:#555">Sila salin dan serahkan melalui saluran rasmi.</div>
          <div style="display:flex;gap:8px;align-items:center;margin:10px 0">
            <input id="tmpPassInput" type="text" value="${tmpPass}" readonly
                   style="flex:1;padding:10px;border:1px solid #ddd;border-radius:8px">
            <button id="copyBtn" class="swal2-confirm swal2-styled">Copy</button>
          </div>
          <label style="font-size:12px"><input type="checkbox" id="maskToggle"> Sembunyikan</label>
        </div>
      `,
      showConfirmButton: true,
      confirmButtonText: 'Tutup',
      allowOutsideClick: false,
      allowEscapeKey: false,
      didOpen: () => {
        const inp = document.getElementById('tmpPassInput');
        const btn = document.getElementById('copyBtn');
        const tog = document.getElementById('maskToggle');
        inp.focus(); inp.select();
        btn.addEventListener('click', async () => {
          try { await navigator.clipboard.writeText(inp.value); btn.textContent='Disalin'; }
          catch(e){ inp.select(); document.execCommand('copy'); btn.textContent='Disalin'; }
        });
        tog.addEventListener('change', e => { inp.type = e.target.checked ? 'password' : 'text'; });
      }
    });
  </script>
<?php endif; ?>

<script>
// Auto-hide flash + scroll to top jika wujud
(function(){
  const fb = document.getElementById('flashBox');
  if (fb){
    window.scrollTo({top:0,behavior:'smooth'});
    setTimeout(()=>{ if(fb){ fb.style.transition='opacity .4s'; fb.style.opacity='0';
      setTimeout(()=>fb.remove(), 400); } }, 4000);
  }
})();
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
