<?php
session_start();
include __DIR__ . '/../db_connect.php';

if (!isset($_SESSION['otp_verified'], $_SESSION['reset_email']) || !$_SESSION['otp_verified']) {
    echo "<script>alert('Unauthorized access.'); window.location.href='../frontend/forgot-password.php';</script>";
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_pass = mysqli_real_escape_string($conn, $_POST['new_password']);
    $confirm_pass = mysqli_real_escape_string($conn, $_POST['confirm_password']);

    if ($new_pass !== $confirm_pass) {
        echo "<script>alert('Passwords do not match'); window.location.href='../frontend/reset-password.php';</script>";
        exit();
    }

    // store plain
    $email = $_SESSION['reset_email'];
    $query = "UPDATE users SET password='$new_pass' WHERE email='$email'";
    if (mysqli_query($conn, $query)) {
        unset($_SESSION['otp_verified'], $_SESSION['otp'], $_SESSION['otp_time'], $_SESSION['reset_email']);
        echo "<script>alert('Password updated successfully! Please login again.'); window.location.href='../frontend/login.php';</script>";
    } else {
        echo "<script>alert('Error updating password. Try again.'); window.location.href='../frontend/reset-password.php';</script>";
    }
}
?>
