<?php
session_start();
include __DIR__ . '/../db_connect.php'; // Adjust if your db file is outside both folders

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../frontend/verify-otp.php');
    exit();
}

if (!isset($_SESSION['otp'], $_SESSION['reset_email'])) {
    echo "<script>
        alert('Session expired. Please request a new OTP.');
        window.location.href='../frontend/forgot-password.php';
    </script>";
    exit();
}

$user_otp = trim($_POST['otp']);
$session_otp = $_SESSION['otp'];
$otp_time = $_SESSION['otp_time'] ?? 0;
$expiry_time = 10 * 60; // 10 minutes

if (time() - $otp_time > $expiry_time) {
    unset($_SESSION['otp'], $_SESSION['otp_time']);
    echo "<script>
        alert('OTP expired. Please request a new one.');
        window.location.href='../frontend/forgot-password.php';
    </script>";
    exit();
}

if ($user_otp == $session_otp) {
    $_SESSION['otp_verified'] = true;
    echo "<script>
        alert('OTP verified successfully!');
        window.location.href='../frontend/reset-password.php';
    </script>";
    exit();
} else {
    echo "<script>
        alert('Invalid OTP. Please try again.');
        window.location.href='../frontend/verify-otp.php';
    </script>";
    exit();
}
?>
