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

if(isset($_POST['otp']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['mobilenumber']) && isset($_POST['email']) && isset($_POST['password'])) {
    
    $entered_otp = $_POST['otp'];
    $fname = $_POST['firstname'];
    $lname = $_POST['lastname'];
    $contno = $_POST['mobilenumber'];
    $email = $_POST['email'];
    $password = md5($_POST['password']);
    
    // Check if OTP session exists
    if(!isset($_SESSION['registration_otp']) || !isset($_SESSION['registration_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['otp_timestamp'] > 300) {
        unset($_SESSION['registration_otp']);
        unset($_SESSION['registration_mobile']);
        unset($_SESSION['otp_timestamp']);
        echo json_encode(['status' => 'error', 'message' => 'OTP has expired. Please request a new OTP.']);
        exit;
    }
    
    // Verify mobile number matches
    if($_SESSION['registration_mobile'] !== $contno) {
        echo json_encode(['status' => 'error', 'message' => 'Mobile number mismatch. Please request a new OTP.']);
        exit;
    }
    
    // Verify OTP
    if($_SESSION['registration_otp'] != $entered_otp) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid OTP. Please try again.']);
        exit;
    }
    
    // OTP verified - Check again if user already exists
    $ret = mysqli_query($con, "SELECT Email FROM tbluser WHERE Email='$email' OR MobileNumber='$contno'");
    $result = mysqli_fetch_array($ret);
    if($result) {
        echo json_encode(['status' => 'error', 'message' => 'This email or mobile number is already registered']);
        exit;
    }
    
    // Insert user into database
    $query = mysqli_query($con, "INSERT INTO tbluser(FirstName, LastName, MobileNumber, Email, Password) VALUES('$fname', '$lname', '$contno', '$email', '$password')");
    
    if($query) {
        // Clear OTP session
        unset($_SESSION['registration_otp']);
        unset($_SESSION['registration_mobile']);
        unset($_SESSION['otp_timestamp']);
        
        echo json_encode(['status' => 'success', 'message' => 'Registration successful! You can now login.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Registration failed. Please try again.']);
    }
    
} else {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required']);
}
?>
