{% extends 'base_structure/layout/base_template.html' %}
{% load static %}
{% block stylesheet %}
<!-- include required css cdn link through html here -->
{% include "cdn_through_html/filepond_cdn_css.html" %}
{% include "cdn_through_html/flatpicker_cdn_css.html" %}

{% endblock %}

{% block content %}

<div class="row layout-top-spacing">
    <div class="col-lg-12">
        <div class="row mb-2">
            <div class="col">
                <a onclick="history.back()" style="height: fit-content;width: fit-content;display: inline-block;">
                <h3 class="card-title m-2 d-flex align-items-center gap-2" style="width: fit-content;"><span class="fw-bold material-symbols-outlined">
                    arrow_back
                    </span><span>Edit Profile</span></h3>
                </a>
            </div>
        </div>

        <div class="row layout-spacing">
            <div class="col-xl-12 col-lg-12 col-md-12 layout-spacing">
                <div class="statbox widget box box-shadow">
                    <div class="widget-content widget-content-area">
                        <form method="POST" enctype="multipart/form-data" id="profileEditForm">
                            {% csrf_token %}
                            {% include 'base_structure/includes/dynamic_template_form.html' with form=form %}
                            <div class="mt-4 mb-0">
                                <div class="d-grid"><button class="btn btn-primary btn-block" type="submit">Submit</button></div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

{% endblock content %}

{% block javascript %}

<!-- include required css cdn link through html here -->
{% include "cdn_through_html/filepond_cdn_js.html" %}
{% include "cdn_through_html/flatpicker_cdn_js.html" %}


<script>
    /**
     * ==================
     * Single File Upload
     * ==================
    */

    // We register the plugins required to do 
    // image previews, cropping, resizing, etc.
    FilePond.registerPlugin(
            FilePondPluginImagePreview,
            FilePondPluginImageExifOrientation,
            FilePondPluginFileValidateSize,
            // FilePondPluginImageEdit
    );

    // Select the file input and use 
    // create() to turn it into a pond
    const inputElement = document.getElementById('id_profile_photo');
    const pond = FilePond.create(inputElement, {
        storeAsFile: true,
        dropOnPage: true
    });
    // Get the profile photo URL using Django template syntax
    const profilePhotoUrl = "{% if form.profile_photo.value %}{{ form.profile_photo.value.url }}{% endif %}";

    if (profilePhotoUrl) {
        // If the URL exists, add the profile photo to FilePond
        pond.addFile(profilePhotoUrl);
    }

    $(document).ready(function() {
        // Initialize datetime picker
        var today = new Date().toISOString().split("T")[0];
        $('#id_date_of_birth').flatpickr({
            format: 'YYYY-MM-DD', // Set the date format to match your validation rule
            maxDate: today
        });

        $.validator.addMethod("noSpace", function(value, element) { 
            return value.indexOf(" ") < 0 && value != ""; 
          }, "Spaces are not allowed.");
          
        
        // Add custom validation method to check for special characters
        $.validator.addMethod("noSpecialChars", function(value, element) {
            return /^[a-zA-Z\s]*$/.test(value); // Allow only letters and whitespace
        }, "Please enter only letters and spaces.");

        // Add custom validation method to check for starting with a letter
        $.validator.addMethod("startsWithLetter", function(value, element) {
            return /^[a-zA-Z]/.test(value); // Check if the value starts with a letter
        }, "Please start with a letter.");

        // Initialize form validation
        $("#profileEditForm").validate({
            rules: {
                first_name: {
                    required: true,
                    minlength: 2,
                    maxlength:15,
                    noSpecialChars: true,
                    startsWithLetter: true,
                    noSpace: true
                },
                last_name: {
                    required: true,
                    minlength: 2,
                    maxlength: 15,
                    noSpecialChars: true,
                    startsWithLetter: true,
                    noSpace: true
                },
                date_of_birth: {
                    required: true,
                    date: true,
                    dateISO: true, // Check for ISO date format (YYYY-MM-DD)
                },
                gender: {
                    required: true
                },
                phone_no: {
                    required: true,
                    digits: true,
                    minlength: 10,
                    maxlength: 10
                }
            },
            messages: {
                first_name: {
                    required: "Please enter your first name.",
                    minlength: "First name must be at least 2 characters.",
                    maxlength: "First name must not exceed 20 characters.",
                    noSpecialChars: "Please enter only letters and spaces.",
                    startsWithLetter: "First name must start with a letter."
                },
                last_name: {
                    required: "Please enter your last name.",
                    minlength: "Last name must be at least 2 characters.",
                    maxlength: "First name must not exceed 20 characters.",
                    noSpecialChars: "Please enter only letters and spaces.",
                    startsWithLetter: "Last name must start with a letter."
                },
                date_of_birth: {
                    required: "Please enter your date of birth.",
                    date: "Please enter a valid date in the format YYYY-MM-DD.",
                    dateISO: "Please enter a valid date in the format YYYY-MM-DD.",
                },
                gender: {
                    required: "Please select your gender."
                },
                phone_no: {
                    required: "Please enter your phone number.",
                    digits: "Please enter only digits.",
                    minlength: "Phone number must be 10 digits long.",
                    maxlength: "Phone number must be 10 digits long."
                }
            },
            errorElement: 'div',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                $(element).closest('.form-group').append(error);
            },
            highlight: function(element, errorClass, validClass) {
                $(element).addClass('is-invalid').removeClass('is-valid');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass('is-invalid').addClass('is-valid');
            },
            submitHandler: function(form) {
                // Disable the submit button to prevent multiple submissions
                $('button[type="submit"]').prop('disabled', true);
                form.submit();
            }
        });
    });

</script>
{% endblock %}