{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <title>signup</title>
    <link rel="stylesheet" href="{% static 'accounts/css/signup.css' %}">
    <link rel="stylesheet" href="{% static '/device/css/add_device.css' %}">
    <script src="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css" rel="stylesheet" />
    <script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.min.js"></script>
    <link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   </head>
<body>
    <div class="container">
      <div class="content">
        <div class="box-header">
            {% comment %} <h1>X-SYS</h1> {% endcomment %}
            <img src="{% static '/assets/x-phy-new-logo-white.png' %}" alt="" id="logo"/>
            <div>
                <span class="email-details">>.  Encryption</span>
                <span class="email-details">>.  Support</span>
            </div>
        </div>
            
        
        
                <div class="login-title-box">
                <h2 class="login-text">Get started</h2>
                <p class="login-url">Already have an account? <a href="{% url 'login' %}">Login</a></p>
                </div>
                
                <form method="post" id="registrationForm" onsubmit="return false;">
                {% csrf_token %}
                <div class="user-details">        
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Email</span>
                        <span class="details">...</span>
                    </div>
                    <input type="email" name="email" maxlength="254" id="id_email"  />
                    </div>
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Password</span>
                        <span class="details">...</span>
                    </div>
                    <input type="password" name="password" id="id_password"  />
                    </div>
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Phone Number</span>
                        <span class="details">...</span>
                    </div>
                    <input type="text" name="phone_number" maxlength="15"  id="id_phone_number"/>
                    </div>
                    <div class="input-box">
                        <div>
                            <span class="details">>. OTP Verification</span>
                            <span class="details">...</span>
                        </div>
                        <input type="text" name="otp_code" maxlength="20" id="id_otp_code" required />
                    </div>          
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Company name</span>
                        <span class="details">...</span>
                    </div>
                    <input type="text" name="company_name" maxlength="20"  id="id_company_name"/>
                    </div>          
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Country</span>
                        <span class="details">...</span>
                    </div>
                    <input type="text" name="country" maxlength="50"  id="id_country"/>
                    </div>
                    <div class="input-box">
                    <div>
                        <span class="details">>.  State</span>
                        <span class="details">...</span>
                    </div>
                    <input type="text" name="state" maxlength="50"  id="id_state"/>
                    </div>
                    <div class="input-box">
                    <div>
                        <span class="details">>.  Postal Code</span>
                        <span class="details">...</span>
                    </div>
                    <input type="text" name="postal_code" maxlength="10"  id="id_postal_code"/>
                    </div>
                    <div class="input-box" style="width: 738px;">
                    <div>
                        <span class="details">>.  Full Address</span>
                        <span class="details">...</span>
                    </div>
                    <input name="full_address" cols="40" rows="10"  id="id_full_address"/>
                    </div>
                    <h2 class='add-device-tittle'></h2>
                    <div class="form-group">
                        <div>
                            <span>>. Identifier name</span>
                            <span>...</span>
                        </div>
                        <input type="text" name="identifier_name"  value="{{ form.identifier_name.value|default_if_none:'' }}" maxlength="50"  id="id_identifier_name">
                    </div>
                    <div class="form-group">
                        <div>
                            <span>>. Device name</span>
                            <span>...</span>
                        </div>
                        <input type="text" name="device_name" value="{{ form.device_name.value|default_if_none:'' }}" maxlength="50"  id="id_device_name">
                    </div>
                    <div class="form-group">
                        <div>
                            <span>>. Operating system</span>
                            <span>...</span>
                        </div>
                        <input type="text" name="operating_system" maxlength="50" value="{{ form.operating_system.value|default_if_none:'' }}" id="id_operating_system">
                    </div>
                    <div class="form-group">
                        <div>
                            <span>>. Department</span>
                            <span>...</span>
                        </div>
                        <input type="text" name="department"  value="{{ form.department.value|default_if_none:'' }}" maxlength="50"  id="id_department">
                    </div>
                </div>
                <div class="form-group">
                    <div>
                        <span>>. Zone</span>
                        <span>...</span>
                    </div>
                    <input type="text" name="zone" value="{{ form.zone.value|default_if_none:'' }}" maxlength="50"  id="id_zone">
                </div>
                <div class="form-group">
                    <div>
                        <span>>. Continents</span>
                        <span>...</span>
                    </div>
                    <input type="text" name="continents" value="{{ form.continents.value|default_if_none:'' }}" maxlength="50"  id="id_continents">
                    
                </div>
                <div class="form-group">
                    <div>
                        <span>>. Region</span>
                        <span>...</span>
                    </div>
                    <input type="text" name="region" value="{{ form.region.value|default_if_none:'' }}" maxlength="50" id="id_region">               
                </div>
                <div class="form-group">
                    <div>
                        <span>>. Cluster</span>
                        <span>...</span>
                    </div>
                    <input type="text" name="cluster" value="{{ form.cluster.value|default_if_none:'' }}" maxlength="50" id="id_cluster">                
                </div>        
                <div class="form-group">
                    <div>
                        <span>>. Pod</span>
                        <span>...</span>
                    </div>
                    <input type="text" name="pod"  id="id_pod" class="podTextInput">
                    <div id="geocoder-container" ></div>
                </div>

                <div class="button">
                    <input type="submit" id="registerButton" value="Register">
                </div>
               
                  
                </form>
               
                
               
        </div>
    </div>
    <script src="{% static 'navbar/js/jquery-3.7.0.js' %}"></script>
   
   <!-- <script>
    mapboxgl.accessToken = '{{ mapbox_access_token }}';
        var geocoder = new MapboxGeocoder({
            accessToken: mapboxgl.accessToken,
            types: 'address,neighborhood,locality,place,region,postcode', 
            placeholder: ' ',
        });
        geocoder.addTo('#geocoder-container');
        geocoder.on('result', function(event) {
            var address = event.result.place_name;
            document.getElementById('id_pod').value = address;
        });
    document.addEventListener("DOMContentLoaded", function() {
        attachValidationHandlers();
    });

    function attachValidationHandlers() {
        $('#registerButton').click(function() {
            // Clear any previous error classes
            $(".input-box").removeClass("error-class");
            checkValidation();

            var errorCount = $(".error-class").length;
            if (errorCount === 0) {
                // Proceed to submit the form data
                submitForm();
            }
        });
    }

    function checkValidation() {
        let id_email = $("#id_email").val();
        let id_password = $("#id_password").val();

        if (id_email.length <= 0) {
            $("#id_email").parent().addClass("error-class");
        }
        if (id_password.length <= 0) {
            $("#id_password").parent().addClass("error-class");
        }
    }

    function submitForm() {

        $(".input-box").removeClass("error-class");
        let formData = {
            email: $("#id_email").val(),
            otp_code: $("#id_otp_code").val(),
            password: $("#id_password").val(),
            phone_number: $("#id_phone_number").val(),
            company_name: $("#id_company_name").val(),
            country: $("#id_country").val(),
            state: $("#id_state").val(),
            postal_code: $("#id_postal_code").val(),
            full_address: $("#id_full_address").val(),
            identifier_name: $("#id_identifier_name").val(), // Add this
            device_name: $("#id_device_name").val(),         // Add this
            operating_system: $("#id_operating_system").val(), // Add this
            department: $("#id_department").val(),           // Add this
            zone: $("#id_zone").val(),                        // Add this
            continents: $("#id_continents").val(),          // Add this
            region: $("#id_region").val(),                    // Add this
            cluster: $("#id_cluster").val(),                  // Add this
            pod: $("#id_pod").val()                           // Add this
        };

        $.ajax({
            type: "POST",
            url: "{% url 'verify_otp' %}", // Adjust this path as needed
            data: formData,
            success: function(response) {
                alert("OTP verified successfully!");
                console.log("OTP verification response:", response);
                // Call the registration API after OTP verification
                registerUser(formData);
            },
            error: function(xhr) {
                console.error("OTP verification error:", xhr);
                alert(xhr.responseJSON.error || "An error occurred. Please try again.");
            }
        });
    }

    // function registerUser(formData) {
    //   $.ajax({
    //       type: "POST",
    //       url: "{% url 'signup' %}", // Adjust this path to your signup view
    //       data: formData,
    //       headers: {
    //           'X-CSRFToken': '{{ csrf_token }}'  // Include CSRF token
    //       },
    //       success: function(response) {
    //           alert("Registration successful!");
    //           console.log("Registration response:", response);

    //           // Call the second OTP generation after registration
    //           generateSecondOTP(formData.email);
    //         //   generateSecondOTP(formData.email, response.user_id);

    //           const redirectUrl = "{% url 'login' %}";
    //           console.log("Redirecting to:", redirectUrl);
    //       },
    //       error: function(xhr) {
    //           console.error("Registration error:", xhr);
    //           alert(xhr.responseJSON.error || "An error occurred during registration.");
    //       }
    //   });
    // } 
    function registerUser(formData) {
    $.ajax({
        type: "POST",
        url: "{% url 'signup' %}", // Adjust this path to your signup view
        data: formData,
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'  // Include CSRF token
        },
        success: function(response) {
            console.log("Registration response:", response);
            // Check if the response indicates success (HTTP 200)
            if (response.status === 200) {
                alert("Registration successful!");
                
                
                // Call the second OTP generation after registration
                generateSecondOTP(formData.email);
                
                // Optional: redirect to login page
                const redirectUrl = "{% url 'login' %}";
                // console.log("Redirecting to:", redirectUrl);
                window.location.href = redirectUrl; // Uncomment to enable redirect
            } else {
                // Handle non-200 responses
                alert("Registration failed. Please try again.");
                console.error("Error response:", response);
            }
        },
        error: function(xhr) {
            console.error("Registration error:", xhr);
            alert(xhr.responseJSON.error || "An error occurred during registration.");
        }
    });
}

    function generateSecondOTP() {
      const email = $("#id_email").val();  // Get the email from the form

      $.ajax({
          type: "POST",
          url: "{% url 'generate_second_otp' %}",  // Adjust this path to your generate_second_otp API
          data: {
              email: email,
             
              csrfmiddlewaretoken: '{{ csrf_token }}'  // Ensure CSRF token is included
          },
          success: function(response) {
            alert("Second OTP generated successfully! Verify this OTP on installer  Your OTP is: " + response.second_otp);
              console.log("Second OTP response:", response);

              window.pywebview.api.show_otp_verification_window(email); // This will call the Python function
              
          },
          error: function(xhr) {
              console.error("Error generating second OTP:", xhr);
              alert(xhr.responseJSON.error || "An error occurred while generating second OTP.");
          }
      });
  }

      
    </script> -->
    {% comment %} <script src="{% static '/device/js/devices1.js' %}"></script> {% endcomment %}
    <!-- <script>
        mapboxgl.accessToken = '{{ mapbox_access_token }}';
        var geocoder = new MapboxGeocoder({
            accessToken: mapboxgl.accessToken,
            types: 'address,neighborhood,locality,place,region,postcode', 
            placeholder: ' ',
        });
        geocoder.addTo('#geocoder-container');
        geocoder.on('result', function(event) {
            var address = event.result.place_name;
            document.getElementById('id_pod').value = address;
        });

        document.addEventListener("DOMContentLoaded", function() {
            attachValidationHandlers()   
        });
        function attachValidationHandlers() {
            $('#btnSubmit').click(function(){
                $("#id_identifier_name").parent().removeClass("error-class");
                $("#id_device_name").parent().removeClass("error-class");
                $("#id_operating_system").parent().removeClass("error-class"); 
                $("#id_department").parent().removeClass("error-class"); 
                $("#id_used_by").parent().removeClass("error-class"); 
                $("#id_zone").parent().removeClass("error-class"); 
                $("#id_continents").parent().removeClass("error-class"); 
                $("#id_region").parent().removeClass("error-class"); 
                $("#id_cluster").parent().removeClass("error-class"); 
                $("#id_pod").parent().removeClass("error-class"); 
                checkValidation()
                
                var errorCount = $(".error-class").length;
                if(errorCount == 0){
                    $('#btnSubmit').attr('type','submit')
                    $("#formDevice").submit()
                }else{
                    $('#btnSubmit').attr('type','button')
                }
            });
        }

    function checkValidation(){
        let id_identifier_name=$("#id_identifier_name").val();
        let id_device_name=$("#id_device_name").val();
        let id_operating_system=$("#id_operating_system").val();       
        let id_department=$("#id_department").val();       
        let id_used_by=$("#id_used_by").val();       
        let id_zone=$("#id_zone").val();       
        let id_continents=$("#id_continents").val();       
        let id_region=$("#id_region").val();       
        let id_cluster=$("#id_cluster").val();       
        let id_pod=$("#id_pod").val();       

        if(id_identifier_name.length <= 0){
            $("#id_identifier_name").parent().addClass("error-class");
        }else if(id_device_name.length <= 0){
            $("#id_device_name").parent().addClass("error-class");
        }else if(id_operating_system.length <= 0){
            $("#id_operating_system").parent().addClass("error-class");
        }else if(id_department.length <= 0){
            $("#id_department").parent().addClass("error-class");
        }else if(id_used_by.length <= 0){
            $("#id_used_by").parent().addClass("error-class");
        }else if(id_zone.length <= 0){
            $("#id_zone").parent().addClass("error-class");
        }else if(id_continents.length <= 0){
            $("#id_continents").parent().addClass("error-class");
        }else if(id_region.length <= 0){
            $("#id_region").parent().addClass("error-class");
        }else if(id_cluster.length <= 0){
            $("#id_cluster").parent().addClass("error-class");
        }else if(id_pod.length <= 0){
            $("#id_pod").parent().addClass("error-class");
        }
    }
    </script> -->

    <script>
        document.addEventListener("DOMContentLoaded", function() {
        // Prevent form from submitting normally
        $("#registrationForm").on('submit', function(e) {
            e.preventDefault();
            return false;
        });
        
        attachValidationHandlers();
    });
        mapboxgl.accessToken = '{{ mapbox_access_token }}';
        var geocoder = new MapboxGeocoder({
            accessToken: mapboxgl.accessToken,
            types: 'address,neighborhood,locality,place,region,postcode', 
            placeholder: ' ',
        });
        geocoder.addTo('#geocoder-container');
        geocoder.on('result', function(event) {
            var address = event.result.place_name;
            document.getElementById('id_pod').value = address;
        });
    
        // document.addEventListener("DOMContentLoaded", function() {
        //     attachValidationHandlers();
        // });
    
        function attachValidationHandlers() {
            $('#registerButton').click(function() {
                // Clear any previous error classes
                $(".input-box").removeClass("error-class");
                checkValidation();
    
                var errorCount = $(".error-class").length;
                if (errorCount === 0) {
                    // Proceed to submit the form data
                    submitForm();
                }
            });
        }
    
        function checkValidation() {
            let id_email = $("#id_email").val();
            let id_password = $("#id_password").val();
    
            if (id_email.length <= 0) {
                $("#id_email").parent().addClass("error-class");
            }
            if (id_password.length <= 0) {
                $("#id_password").parent().addClass("error-class");
            }
        }
    
        function submitForm() {
            $(".input-box").removeClass("error-class");
            let formData = {
                email: $("#id_email").val(),
                otp_code: $("#id_otp_code").val(),
                password: $("#id_password").val(),
                phone_number: $("#id_phone_number").val(),
                company_name: $("#id_company_name").val(),
                country: $("#id_country").val(),
                state: $("#id_state").val(),
                postal_code: $("#id_postal_code").val(),
                full_address: $("#id_full_address").val(),
                identifier_name: $("#id_identifier_name").val(), // Add this
                device_name: $("#id_device_name").val(),         // Add this
                operating_system: $("#id_operating_system").val(), // Add this
                department: $("#id_department").val(),           // Add this
                zone: $("#id_zone").val(),                        // Add this
                continents: $("#id_continents").val(),          // Add this
                region: $("#id_region").val(),                    // Add this
                cluster: $("#id_cluster").val(),                  // Add this
                pod: $("#id_pod").val()                           // Add this
            };
    
            $.ajax({
                type: "POST",
                url: "{% url 'verify_otp' %}", // Adjust this path as needed
                data: formData,
                success: function(response) {
                    alert("OTP verified successfully!");
                    console.log("OTP verification response:", response);
                    // Call the registration API after OTP verification
                    registerUser(formData);
                },
                error: function(xhr) {
                    console.error("OTP verification error:", xhr);
                    const errorMessage = xhr.responseJSON ? xhr.responseJSON.error : "An error occurred during OTP verification.";
                    alert(errorMessage);
                }
            });
        }
    
        function registerUser(formData) {
    $.ajax({
        type: "POST",
        url: "{% url 'signup' %}",
        data: formData,
        dataType: 'json',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}'
        },
        success: function(response) {
            try {
                // Parse response if it's a string
                const result = typeof response === 'string' ? JSON.parse(response) : response;
                console.log("Registration response:", result);
                
                // Show success message
                alert("Registration successful!");
                
                // Generate second OTP after delay
                setTimeout(function() {
                    generateSecondOTP(formData.email);
                }, 500);
                
                // Redirect after another delay
                //setTimeout(function() {
                    //window.location.href = "{% url 'login' %}";
                //}, 1500);
                
            } catch (e) {
                console.error("Error parsing response:", e);
                alert("Registration completed but encountered an error processing the response");
            }
        },
        error: function(xhr) {
            console.error("Registration error:", xhr);
            const errorMessage = xhr.responseJSON ? xhr.responseJSON.error : "An error occurred during registration.";
            alert(errorMessage);
        }
    });
}
                
        function generateSecondOTP(email) {
            $.ajax({
                type: "POST",
                url: "{% url 'generate_second_otp' %}",  // Adjust this path to your generate_second_otp API
                data: {
                    email: email,
                    csrfmiddlewaretoken: '{{ csrf_token }}'  // Ensure CSRF token is included
                },
                success: function(response) {
                    alert("Second OTP generated successfully! Verify this OTP on installer. Your OTP is: " + response.second_otp);
                    console.log("Second OTP response:", response);
                    
                    // Call the Python function to show the OTP verification window
                    window.pywebview.api.show_otp_verification_window(email);
                },
                error: function(xhr) {
                    console.error("Error generating second OTP:", xhr);
                    const errorMessage = xhr.responseJSON ? xhr.responseJSON.error : "An error occurred while generating second OTP.";
                    alert(errorMessage);
                }
            });
        }
    </script>
    
</body>
</html>
