@extends('layouts.admin')
@section('content')
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">Create Genetic Disease</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Home</a></li>
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Genetic Diseases</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($geneticDisease->id)) ? 'Update Genetic Disease' : 'Create Genetic Disease' }}</li>
                </ol>
            </div>
        </div>
    </div>
</div>
<!-- end page title -->

<div class="row">
    <div class="col-lg-12">
        <div class="card" id="orderList">
            <div class="card-body">
                <form class="tablelist-form {{ !empty($geneticDisease->id) ? 'edit-form' : '' }}" autocomplete="off" name="geneticDiseaseForm" id="geneticDiseaseForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.genetic_diseases.store') }}">
                   <input type="hidden" name="id" id="id" value="{{ (!empty($geneticDisease->id)) ? $geneticDisease->id : '' }}" />
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label for="name-field" class="form-label">Genetic Disease Name</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Enter Genetic Disease Name" required value="{{ (!empty($geneticDisease->name)) ? $geneticDisease->name : '' }}" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="name_ar-field" class="form-label">Genetic Disease Name (Arabic)</label>
                            <input type="text" id="name_ar" name="name_ar" dir="rtl" class="form-control" placeholder="Enter Genetic Disease Name" required value="{{ (!empty($geneticDisease->name_ar)) ? $geneticDisease->name_ar : '' }}" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="status-field" class="form-label">Status</label>
                            <select class="form-select js-example-basic-single status-select" data-placeholder="Select Status" name="status" id="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($geneticDisease->id) && $geneticDisease->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($geneticDisease->id) && $geneticDisease->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="plan-variant-wrapper">
                        @foreach ($geneticDisease->variants??[] as $key => $variant)
                            <div class="row pricing-varient-element">
                                <input type="hidden" name="variants[{{ $key+1 }}][id]" value="{{ $variant->id }}" />
                                <div class="col-lg-4 mb-3">
                                    <label for="customername-field" class="form-label">Variant Name</label>
                                    <input type="text" id="varient_name" name="variants[{{ $key+1 }}][name]" class="form-control" placeholder="Enter Variant Name" required value="{{ $variant->name }}" />
                                </div>
                                <div class="col-lg-4 mb-3">
                                    <label for="customername-field" class="form-label">Variant Name (Arabic)</label>
                                    <input type="text" id="varient_name_ar" name="variants[{{ $key+1 }}][name_ar]" dir="rtl" class="form-control" placeholder="Enter Variant Name" required value="{{ $variant->name_ar }}" />
                                </div>
                                <div class="col-lg-4 mb-3 d-flex align-items-end">
                                    <button type="button" class="btn btn-danger remove-variant">Remove</button>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <button class="btn btn-success" id="addNewVarient">Add Disease Varient</button>

                    <div class="hstack gap-2 justify-content-between">
                    <a href="{{ route('admin.genetic_diseases') }}" class="btn btn-success">Back</a> 
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($geneticDisease->id)) ? 'Update Genetic Disease' : 'Create Genetic Disease' }} </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div> 

<div class="pricing-varient-element-wrapper" style="display: none;">
    <div class="row pricing-varient-element">
        <div class="col-lg-4 mb-3">
            <label for="customername-field" class="form-label">Variant Name</label>
            <input type="text" id="varient_name" name="variants[][name]" class="form-control" placeholder="Enter Variant Name" required value="" />
        </div>
        <div class="col-lg-4 mb-3">
            <label for="customername-field" class="form-label">Variant Name (Arabic)</label>
            <input type="text" id="varient_name" name="variants[][name_ar]" class="form-control" placeholder="Enter Variant Name" required value="" />
        </div>
        <div class="col-lg-4 mb-3 d-flex align-items-end">
            <button type="button" class="btn btn-danger remove-variant">Remove</button>
        </div>
    </div>
</div>

@endsection
@section('script')
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#geneticDiseaseForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 3,
                    },
                    name_ar: {
                        required: true,
                        minlength: 3,
                    },
                    status: {
                        required: true,
                    },
                },
                messages: {
                    name: {
                        required: "Please enter the genetic disease name.",
                        minlength: "Genetic disease name must be at least 3 characters.",
                    },
                    name_ar: {
                        required: "Please enter the genetic disease name in Arabic.",
                        minlength: "Genetic disease name in Arabic must be at least 3 characters.",
                    },
                    status: {
                        required: "Please select the status.",
                    },
                },
                onkeyup: function (element) {
                    $(element).valid(); // Real-time validation on keyup
                },
                onfocusout: function (element) {
                    $(element).valid(); // Validate when focus is lost
                },
                errorPlacement: function (error, element) {
                    if (element.is("select")) {
                        error.insertAfter(element.next('.select2')); 
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function (form) {
                    let formData = new FormData(form);

                    // AJAX submission
                    $.ajax({
                        url: form.action,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                        },
                        success: function (response) {
                            Swal.fire({
                                iconHtml: `<img src="{{ asset('assets/images/success-circle.svg') }}" class="img-fluid">`,
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.genetic_diseases') }}";
                            });
                        },
                        error: function (xhr) {
                            if (xhr.status === 422) {
                                let errors = xhr.responseJSON.errors;

                                // Display validation errors from the server
                                $.each(errors, function (key, value) {
                                    let field = $(`[name="${key}"]`);
                                    field.addClass("error");
                                    field.after(`<label class="error">${value[0]}</label>`);
                                });
                            } else {
                                Swal.fire({
                                    text: "Something went wrong. Please try later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK",
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm'
                                    }
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                },
                invalidHandler: function(event, validator) {
                    var firstInvalidField = $(validator.errorList[0].element);
                    
                    $('html, body').animate({
                        scrollTop: firstInvalidField.offset().top - 100 
                    }, 500); 
                }
            });

            // Initially hide the button if no type is selected
        if ($('#type').val() === '') {
            $('#addNewVarient').hide();
        }
        $(document).on('click', '#addNewVarient', function (e) {
            e.preventDefault();
            var html = $('.pricing-varient-element-wrapper').html();
            if ($('#type').val() == 'free' && $('.plan-variant-wrapper .row').length >= 1) {
                Swal.fire({
                    text: "For Free plans, only one variant is allowed.",
                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                    confirmButtonText: "OK",
                    customClass: {
                        confirmButton: 'custom-ok-button-class w-sm'
                    }
                });
                return;
            }
            let counter = $('.plan-variant-wrapper .row').length;
            counter++;
            console.log(counter);
            var new_html = `<div class="row pricing-varient-element">
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Variant Name</label>
                            <input type="text" id="varient_name" name="variants[${counter}][name]" class="form-control" placeholder="Enter Variant Name" required value="" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Variant Name (Arabic)</label>
                            <input type="text" id="varient_name" name="variants[${counter}][name_ar]" dir="rtl" class="form-control" placeholder="Enter Variant Name" required value="" />
                        </div>
                        <div class="col-lg-4 mb-3 d-flex align-items-end">
                            <button type="button" class="btn btn-danger remove-variant">Remove</button>
                        </div>
                    </div>`;
            $('.plan-variant-wrapper').append(new_html);
        });

        $(document).on('click', '.remove-variant', function (e) {
            e.preventDefault();
            $(this).closest('.pricing-varient-element').remove();
            $('#submitBtn').prop('disabled', false);
        });
        $('#type').on('change', function () {
            if ($(this).val() !== '') {
            $('#addNewVarient').show();
            } else {
            $('#addNewVarient').hide();
            }
        });
        });
    </script>
@endsection
