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

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

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { header("Location: dashboard.php"); exit; }

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

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

$adminId = (int)($_SESSION['user']['id'] ?? 0);

// Update status -> rejected
$upd = $conn->prepare("UPDATE password_reset_requests SET status='rejected', handled_by=?, handled_at=NOW(), admin_note='Ditolak oleh admin' WHERE id=? AND status='pending' LIMIT 1");
$upd->bind_param("ii", $adminId, $reqId);
$upd->execute();
$ok = $upd->affected_rows > 0;
$upd->close();

// Audit
if ($ok && function_exists('write_audit')) {
  $q=$conn->prepare("SELECT member_id FROM password_reset_requests WHERE id=?");
  $q->bind_param("i",$reqId); $q->execute();
  $mid=(int)($q->get_result()->fetch_assoc()['member_id']??0); $q->close();
  @write_audit($conn, $adminId, $mid, "PASSWORD_RESET_REQUEST_REJECTED");
}

// Balik dashboard
header("Location: dashboard.php");
exit;
