<?php
$token = $_POST["token"] ?? null;
$password = $_POST["password"] ?? null;
$confirm_password = $_POST["confirm_password"] ?? null;

if (!$token || !$password || !$confirm_password) {
    die("All fields are required.");
}

if ($password !== $confirm_password) {
    die("Passwords must match.");
}

if (strlen($password) < 8) {
    die("Password must be at least 8 characters.");
}

if (!preg_match("/[a-z]/i", $password)) {
    die("Password must contain at least one letter.");
}

if (!preg_match("/[0-9]/", $password)) {
    die("Password must contain at least one number.");
}

$token_hash = hash("sha256", $token);

$mysqli = require __DIR__ . "/database.php";

// Find the token in password_resets
$sql = "SELECT * FROM password_resets WHERE reset_token_hash = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $token_hash);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();

if (!$record) {
    die("Token not found.");
}

if (strtotime($record["reset_token_expires_at"]) <= time()) {
    die("Token has expired.");
}

$student_id = $record["student_id"];

// Hash the new password
$password_hash = password_hash($password, PASSWORD_DEFAULT);

// Update the adminstudent table
$sql = "UPDATE adminstudent SET pword = ? WHERE student_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("si", $password_hash, $student_id);
$stmt->execute();

// Delete the used token from password_resets
$sql = "DELETE FROM password_resets WHERE student_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $student_id);
$stmt->execute();

header("Location: ../studentpanel/Student_Dashboard.php?success=" . urlencode("Password updated! You can now login."));
exit;
?>