<?php
require_once __DIR__.'/_bootstrap.php';
$token = $_GET['token']??'';
$valid = false; $sid=0;
if($token!==''){
  $st = mysqli_prepare($conn,"SELECT student_id,expires_at,used FROM password_resets WHERE token=? LIMIT 1");
  mysqli_stmt_bind_param($st,"s",$token);
  mysqli_stmt_execute($st);
  $res = mysqli_stmt_get_result($st);
  $row = mysqli_fetch_assoc($res);
  mysqli_stmt_close($st);
  if($row && !$row['used'] && strtotime($row['expires_at'])>time()){
    $valid = true; $sid = (int)$row['student_id'];
  }
}
if($_SERVER['REQUEST_METHOD']==='POST' && $valid){
  $new = $_POST['new']??''; $cnf=$_POST['confirm']??'';
  if($new===$cnf && strlen($new)>=6){
    $hash = password_hash($new, PASSWORD_DEFAULT);
    $up = mysqli_prepare($conn,"UPDATE students SET portal_password_hash=?, portal_enabled=1, portal_force_reset=0 WHERE id=?");
    mysqli_stmt_bind_param($up,"si",$hash,$sid); mysqli_stmt_execute($up); mysqli_stmt_close($up);
    $done = mysqli_prepare($conn,"UPDATE password_resets SET used=1 WHERE token=?");
    mysqli_stmt_bind_param($done,"s",$token); mysqli_stmt_execute($done); mysqli_stmt_close($done);
    $ok='Password reset. You can login now.'; $valid=false;
  } else { $err='Passwords must match and be >= 6 chars.'; }
}
?>
<?php if(!$valid): ?>
  <div>Invalid or expired link. <a href="user_forgot.php">Try again</a></div>
  <?php if(!empty($ok)) echo "<div style='color:#166534'>$ok</div>"; ?>
<?php else: ?>
<form method="post">
  <label>New Password</label><input type="password" name="new" required>
  <label>Confirm</label><input type="password" name="confirm" required>
  <button>Set Password</button>
  <?php if(!empty($err)) echo "<div style='color:#b91c1c'>$err</div>"; ?>
</form>
<?php endif; ?>
