<?php
/**
 * Reveal semula kata laluan sementara (selagi belum expired & belum capai max views).
 * - Auth: admin
 * - CSRF: wajib
 * - Decrypt AES-256-GCM menggunakan dis_crypto_key() dari db.php
 * - Rekod views dan last_viewed_at
 * - Papar melalui SESSION (modal di password-reset-center.php)
 */
session_start();
require_once __DIR__ . '/db.php';

// ===== Auth: admin sahkan =====
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
  header("Location: password-reset-center.php"); exit;
}

// ===== Method & CSRF =====
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { header("Location: password-reset-center.php"); exit; }
$csrf = $_POST['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'] ?? '', $csrf)) {
  header("Location: password-reset-center.php"); exit;
}

// ===== Input =====
$reqId = (int)($_POST['request_id'] ?? 0);
if ($reqId <= 0) { header("Location: password-reset-center.php"); exit; }

// ===== Helper decrypt =====
function dec_str(string $ct_b64, string $iv_b64, string $tag_b64): ?string {
  $cipher = 'aes-256-gcm';
  $key    = dis_crypto_key();   // <<— kunci auto dari db.php
  $ct  = base64_decode($ct_b64);
  $iv  = base64_decode($iv_b64);
  $tag = base64_decode($tag_b64);
  $pt  = openssl_decrypt($ct, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
  return ($pt === false) ? null : $pt;
}

// ===== Ambil rekod request =====
$stmt = $conn->prepare("
  SELECT r.*, m.full_name
  FROM password_reset_requests r
  LEFT JOIN members m ON m.id = r.member_id
  WHERE r.id=? AND r.status='completed' LIMIT 1
");
$stmt->bind_param("i", $reqId);
$stmt->execute();
$r = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$r) { header("Location: password-reset-center.php"); exit; }

// ===== Semak expiry & views =====
$expired = (!empty($r['temp_password_expires_at']) && strtotime($r['temp_password_expires_at']) < time());
$views   = (int)$r['temp_password_views'];
$maxv    = (int)$r['temp_password_max_views'];

if ($expired || $views >= $maxv || empty($r['temp_password_enc'])) {
  header("Location: password-reset-center.php"); exit;
}

// ===== Decrypt =====
$plain = dec_str((string)$r['temp_password_enc'], (string)$r['temp_password_iv'], (string)$r['temp_password_tag']);
if ($plain === null) { header("Location: password-reset-center.php"); exit; }

// ===== Update views =====
$upd = $conn->prepare("UPDATE password_reset_requests SET temp_password_views=temp_password_views+1, temp_password_last_viewed_at=NOW() WHERE id=? LIMIT 1");
$upd->bind_param("i", $reqId);
$upd->execute();
$upd->close();

// ===== Audit (jika helper wujud) =====
if (function_exists('write_audit')) {
  $adminId = (int)($_SESSION['user']['id'] ?? 0);
  @write_audit($conn, $adminId, (int)$r['member_id'], "PASSWORD_TEMP_REVEALED", ['request_id'=>$reqId]);
}

// ===== Papar melalui SESSION (modal di PRC) =====
$_SESSION['temp_password']     = $plain;
$_SESSION['temp_password_for'] = $r['full_name'] ?: ($r['email'] ?: $r['staff_number']);

header("Location: password-reset-center.php");
exit;
