<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #eef5f9;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh; /* Ensure it takes full viewport height */
        }

        .container {
            max-width: 500px;
            background-color: #fff;
            padding: 30px 40px;
            border-radius: 12px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            width: 100%; /* Make it responsive */
        }

        h2 {
            text-align: center;
            color: #007bff;
            margin-bottom: 25px;
        }

        label {
            font-weight: bold;
            display: block;
            margin-bottom: 6px;
            color: #333;
        }

        input[type="text"],
        input[type="tel"],
        input[type="email"],
        input[type="password"],
        select {
            width: 100%;
            padding: 10px 12px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 6px;
            box-sizing: border-box;
            font-size: 1em; /* Ensure consistent font size */
        }

        button {
            width: 100%;
            background-color: #28a745;
            color: white;
            padding: 12px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #218838;
        }

        .login-link {
            text-align: center;
            margin-top: 20px;
        }

        .login-link a {
            color: #007bff;
            text-decoration: none;
            font-weight: bold;
        }

        .login-link a:hover {
            text-decoration: underline;
        }

        .error-message {
            color: #dc3545;
            text-align: center;
            margin-bottom: 15px;
            font-weight: bold;
        }

        .success-message {
            color: #28a745;
            text-align: center;
            margin-bottom: 15px;
            font-weight: bold;
        }

        /* Styles for OTP section - initially hidden */
        .otp-section {
            display: none;
            text-align: center;
            padding-top: 20px; /* Add some space above */
            border-top: 1px solid #eee; /* Separator */
            margin-top: 20px;
        }
        .otp-input {
            width: calc(100% - 24px); /* Adjust for padding and border */
            font-size: 1.2em;
            letter-spacing: 3px; /* Slightly reduce letter spacing */
            text-align: center; /* Center the OTP digits */
        }
        .resend-otp {
            margin-top: 15px;
            font-size: 0.9em;
        }
        .resend-otp a {
            color: #007bff;
            text-decoration: none;
        }
        .resend-otp a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>

    <div class="container">
        <h2>User Registration</h2>
        <c:if test="${not empty error}">
            <div class="error-message">
                <c:out value="${error}"/>
            </div>
        </c:if>
        <c:if test="${not empty successMessage}">
            <div class="success-message">
                <c:out value="${successMessage}"/>
            </div>
        </c:if>

        <%-- Registration Form (Stage 1) --%>
        <%-- The form's action is 'sendOtpForRegistration' --%>
        <form id="registrationForm" action="sendOtpForRegistration" method="post">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required value="${param.name}">

            <label for="mobileNumber">Mobile Number:</label>
            <input type="tel" id="mobileNumber" name="mobileNumber" placeholder="Ex: 9876543210" value="${param.mobileNumber}">

            <label for="emailId">Email Id:</label>
            <input type="email" id="emailId" name="emailId" required value="${param.emailId}">

            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>

            <label for="confirmPassword">Confirm Password:</label>
            <input type="password" id="confirmPassword" name="confirmPassword" required>

            <label for="role">Role:</label>
            <select id="role" name="role" required>
                <option value="USER" ${param.role == "USER" ? "selected" : ""}>User</option>
                <option value="ADMIN" ${param.role == "ADMIN" ? "selected" : ""}>Admin</option>
            </select>

             <button type="submit" onclick="showOtpSection()">Send OTP & Register</button>
        </form>
<%-- 
         OTP Verification Section (Stage 2)
        <div id="otpVerificationSection" class="otp-section">
            <h3>OTP Verification</h3>
            <p>An OTP has been sent to your email address: <strong><span id="otpEmailDisplay"></span></strong></p>
            <p>Please enter the OTP below to complete your registration.</p>
            <form action="verifyOtpAndRegister" method="post">
                <label for="otp">Enter OTP:</label>
                <input type="text" id="otp" name="otp" class="otp-input" required maxlength="6" pattern="\d{6}">
                Hidden fields to pass necessary data back to the server for verification
                <input type="hidden" id="hiddenEmail" name="emailId" value="">
                <input type="hidden" id="hiddenRole" name="role" value="">

                <button type="submit">Verify OTP & Complete Registration</button>
            </form>
            <div class="resend-otp">
                <p>Didn't receive the OTP? <a href="#" id="resendOtpLink">Resend OTP</a></p>
            </div>
        </div>
 --%>
        
    </div>
      <div id="otpSection" style="display: none;">
            <h3>OTP Verification</h3>
            <p>An OTP has been sent to your email address: <strong><span id="otpEmailDisplay"></span></strong></p>
               <form action="verifyOtpAndRegister" method="post">
       <label for="otp">Enter OTP:</label>
       <input type="text" id="otp" name="otp" class="otp-input" required maxlength="6" pattern="\d{6}">
       <input type="hidden" id="hiddenEmail" name="emailId" value="">
       <input type="hidden" id="hiddenRole" name="role" value="${param.role}">
       <button type="submit">Verify OTP & Complete Registration</button>
   </form>

        </div>
    </div>
<div class="login-link">
            <p>Already a user? <a href="login">Login</a></p>
        </div>
    <script>
    function showOtpSection() {
        const emailField = document.getElementById('emailId');
        const hiddenEmail = document.getElementById('hiddenEmail');

        if (emailField && hiddenEmail) {
            hiddenEmail.value = emailField.value; // Copy email from registration form
        }

        document.getElementById('registrationForm').style.display = 'none';
        document.getElementById('otpSection').style.display = 'block';
    }

    </script>
<!-- 
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const registrationForm = document.getElementById('registrationForm');
            const otpVerificationSection = document.getElementById('otpVerificationSection');
            const otpEmailDisplay = document.getElementById('otpEmailDisplay');
            const hiddenEmail = document.getElementById('hiddenEmail');
            const hiddenRole = document.getElementById('hiddenRole');
            const resendOtpLink = document.getElementById('resendOtpLink');

            // Determine if the OTP section should be shown on page load
            // This happens if the server redirects with 'showOtpSection=true' and emailId/role params
            const urlParams = new URLSearchParams(window.location.search);
            const showOtpSectionParam = urlParams.get('showOtpSection');
            const emailFromParam = urlParams.get('emailId');
            const roleFromParam = urlParams.get('role');

            if (showOtpSectionParam === 'true' && emailFromParam) {
                registrationForm.style.display = 'none';
                otpVerificationSection.style.display = 'block';
                otpEmailDisplay.textContent = emailFromParam;
                hiddenEmail.value = emailFromParam;
                hiddenRole.value = roleFromParam;
            }

            // Handle Resend OTP link click
            resendOtpLink.addEventListener('click', function(event) {
                event.preventDefault(); // Prevent default link behavior (navigating to '#')

                const email = hiddenEmail.value; // Get email from the hidden field
                const role = hiddenRole.value;   // Get role from the hidden field

                if (email) {
                    // Send an AJAX request to resend OTP
                    fetch('resendOtpForRegistration', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        // FIX: Using string concatenation instead of template literals
                        // to avoid potential misinterpretation by JSP's EL engine.
                        body: 'emailId=' + encodeURIComponent(email) + '&role=' + encodeURIComponent(role)
                    })
                    .then(response => response.json()) // Assuming your server returns JSON
                    .then(data => {
                        if (data.success) {
                            alert('New OTP has been sent!');
                            // You might want to disable resend button for a short period
                            // to prevent spamming OTP requests.
                        } else {
                            alert('Failed to resend OTP: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error resending OTP:', error);
                        alert('An error occurred while trying to resend OTP.');
                    });
                } else {
                    alert('Email information missing. Please go back and fill the registration form.');
                }
            });
        });
    </script> -->

</body>
</html>