<?php
require_once __DIR__.'/db.php'; session_start();
if($_SERVER['REQUEST_METHOD']!=='POST'){ header('Location: forgot-password.php'); exit; }
if(!hash_equals($_SESSION['csrf_token']??'', $_POST['csrf_token']??'')){
  header("Location: forgot-password.php?type=error&msg=".urlencode('Token tidak sah.')); exit;
}
$staff=trim($_POST['staff_number']??''); $email=trim($_POST['email']??'');
$ic4=trim($_POST['ic_last4']??''); $phone=trim($_POST['phone']??'');
if($staff===''||$email===''||!preg_match('/^\d{4}$/',$ic4)){
  header("Location: forgot-password.php?type=error&msg=".urlencode('Sila isi semua medan bertanda *.')); exit;
}

$stmt=$conn->prepare("SELECT id, ic_number FROM members WHERE staff_number=? AND email=? LIMIT 1");
$stmt->bind_param("ss",$staff,$email); $stmt->execute();
$mem=$stmt->get_result()->fetch_assoc(); $stmt->close();
if(!$mem){ header("Location: forgot-password.php?type=error&msg=".urlencode('Tiada akaun ditemui.')); exit; }
if(substr((string)$mem['ic_number'],-4)!==$ic4){
  header("Location: forgot-password.php?type=error&msg=".urlencode('Pengesahan IC tidak sepadan.')); exit;
}

$chk=$conn->prepare("SELECT id FROM password_reset_requests WHERE staff_number=? AND email=? AND status='pending' LIMIT 1");
$chk->bind_param("ss",$staff,$email); $chk->execute();
$dup=$chk->get_result()->fetch_assoc(); $chk->close();
if($dup){ header("Location: forgot-password.php?type=success&msg=".urlencode('Permintaan sebelum ini masih sedang diproses.')); exit; }

$ins=$conn->prepare("INSERT INTO password_reset_requests (member_id,staff_number,email,ic_last4,phone) VALUES (?,?,?,?,?)");
$mid=(int)$mem['id']; $ins->bind_param("issss",$mid,$staff,$email,$ic4,$phone); $ins->execute(); $ins->close();

if(function_exists('write_audit')){ @write_audit($conn,0,$mid,"RESET_REQUEST_SUBMITTED"); }
header("Location: forgot-password.php?type=success&msg=".urlencode('Permintaan berjaya dihantar. Pihak admin akan memproses permintaan anda.'));
