<?php
/**
 * Reset & tetapkan kata laluan sementara untuk seorang ahli.
 * - Auth: admin sahaja
 * - CSRF: wajib
 * - Guna setting dari jadual password_reset_config
 * - Simpan salinan encrypted (AES-256-GCM) + expiry + max reveal
 * - Papar sekali melalui SESSION (modal di dashboard)
 */
session_start();
require_once __DIR__ . '/db.php';

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

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

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

// ===== Helpers =====
function cfg(mysqli $conn, string $name, string $default): string {
  $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 enc_str(string $plain): array {
  // AES-256-GCM dengan kunci auto dari db.php (dis_crypto_key)
  $cipher = 'aes-256-gcm';
  $key    = dis_crypto_key();       // <<— tiada APP_KEY diperlukan
  $iv     = random_bytes(12);
  $tag    = '';
  $ct     = openssl_encrypt($plain, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
  return [ base64_encode($ct), base64_encode($iv), base64_encode($tag) ];
}
function gen_temp_password(int $len): string {
  $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%';
  $out=''; $max = strlen($alphabet)-1;
  for ($i=0; $i<$len; $i++) { $out .= $alphabet[random_int(0,$max)]; }
  return $out;
}

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

if (!$req || $req['status'] !== 'pending' || empty($req['mid'])) {
  header("Location: dashboard.php"); exit;
}

// ===== Baca setting & clamp =====
$len       = (int)cfg($conn, 'temp_password_length', '12');
$retainHrs = (int)cfg($conn, 'retain_hours', '4');
$maxReveal = (int)cfg($conn, 'max_reveals', '3');

$len       = max(8,  min($len, 64));
$retainHrs = max(1,  min($retainHrs, 72));
$maxReveal = max(0,  min($maxReveal, 10));

// ===== Jana password sementara + update member =====
$temp = gen_temp_password($len);
$hash = password_hash($temp, PASSWORD_DEFAULT);
$mid  = (int)$req['mid'];

$upd = $conn->prepare("UPDATE members SET password_hash=?, must_change_password=1 WHERE id=? LIMIT 1");
$upd->bind_param("si", $hash, $mid);
$upd->execute();
$upd->close();

// ===== Simpan salinan encrypted + expiry + max reveal di request =====
list($ct, $iv, $tag) = enc_str($temp);
$adminId = (int)($_SESSION['user']['id'] ?? 0);

$upd2 = $conn->prepare("
  UPDATE password_reset_requests
  SET status='completed',
      handled_by=?, handled_at=NOW(),
      admin_note=?,
      temp_password_enc=?, temp_password_iv=?, temp_password_tag=?,
      temp_password_expires_at = DATE_ADD(NOW(), INTERVAL ? HOUR),
      temp_password_views = 0,
      temp_password_max_views = ?
  WHERE id=? LIMIT 1
");
$note = "Password reset oleh admin ID ".$adminId;
$upd2->bind_param("issssiii", $adminId, $note, $ct, $iv, $tag, $retainHrs, $maxReveal, $reqId);
$upd2->execute();
$upd2->close();

// ===== Audit (jika helper wujud) =====
if (function_exists('write_audit')) {
  @write_audit($conn, $adminId, $mid, "PASSWORD_RESET_BY_ADMIN", ['request_id'=>$reqId]);
}

// ===== Papar sekali melalui SESSION (modal di dashboard) =====
$_SESSION['temp_password']     = $temp;
$_SESSION['temp_password_for'] = $req['full_name'] ?: ($req['email'] ?: $req['staff_number']);

// ===== Balik ke dashboard (senarai embedded) =====
header("Location: dashboard.php");
exit;
