<?php
session_start();
header('Content-Type: application/json');
include('includes/dbconnection.php');

if(isset($_POST['otp']) && isset($_POST['newpassword']) && isset($_POST['mobilenumber'])) {
    
    $entered_otp = $_POST['otp'];
    $mobilenumber = $_POST['mobilenumber'];
    $newpassword = md5($_POST['newpassword']);
    
    // Check if OTP session exists
    if(!isset($_SESSION['forgot_otp']) || !isset($_SESSION['forgot_mobile'])) {
        echo json_encode(['status' => 'error', 'message' => 'OTP session expired. Please request a new OTP.']);
        exit;
    }
    
    // Check OTP expiry (5 minutes = 300 seconds)
    if(time() - $_SESSION['forgot_otp_timestamp'] > 300) {
        unset($_SESSION['forgot_otp']);
        unset($_SESSION['forgot_mobile']);
        unset($_SESSION['forgot_user_id']);
        unset($_SESSION['forgot_otp_timestamp']);
        echo json_encode(['status' => 'error', 'message' => 'OTP has expired. Please request a new OTP.']);
        exit;
    }
    
    // Verify mobile number matches
    if($_SESSION['forgot_mobile'] !== $mobilenumber) {
        echo json_encode(['status' => 'error', 'message' => 'Mobile number mismatch. Please request a new OTP.']);
        exit;
    }
    
    // Verify OTP
    if($_SESSION['forgot_otp'] != $entered_otp) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid OTP. Please try again.']);
        exit;
    }
    
    // OTP verified - Update password
    $userId = $_SESSION['forgot_user_id'];
    $query = mysqli_query($con, "UPDATE tbluser SET Password='$newpassword' WHERE ID='$userId' AND MobileNumber='$mobilenumber'");
    
    if($query) {
        // Clear OTP session
        unset($_SESSION['forgot_otp']);
        unset($_SESSION['forgot_mobile']);
        unset($_SESSION['forgot_user_id']);
        unset($_SESSION['forgot_otp_timestamp']);
        
        echo json_encode(['status' => 'success', 'message' => 'Password reset successful! You can now login with your new password.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to reset password. Please try again.']);
    }
    
} else {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
}
?>
