@extends('layouts.admin')
@section('content') 

<!-- start page title -->
<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 Category Atribute Value</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);">Category Atribute Values</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($categoryatribute->id)) ? 'Update Category Atribute Value' : 'Create Category Atribute Value'  }}</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($categoryatribute->id) ? 'edit-form' : '' }}" autocomplete="off" name="categoryatributeForm" id="categoryatributeForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.category_atributes_value.store') }}">
                   <input type="hidden" name="id" id="id" value="{{ (!empty($categoryatribute->id)) ? $categoryatribute->id : '' }}" />
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Category Name</label>
                            <select class="form-select js-example-basic-single" data-placeholder="Select Category" name="category_id" id="category_id">
                                <option value=""></option>
                                @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{ (!empty($categoryatribute->category_id) && $categoryatribute->category_id == $category->id) ? 'selected' : '' }}>{{ $category->parent->name.' > '.$category->name }}</option>
                                @endforeach
                                
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="service-attribute-field" class="form-label">Category Attribute Name</label>
                            <select class="form-select" name="attribute_id" id="service_attributes" disabled>
                                <option value="">Select Attribute</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Category Atribute Value</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Enter Atribute Value" required value="{{ (!empty($categoryatribute->name)) ? $categoryatribute->name : '' }}" name="name" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Category Atribute Value (Arabic)</label>
                            <input type="text" id="name_ar" name="name_ar" dir="rtl" class="form-control" placeholder="Enter Atribute Value (Arabic)" required value="{{ (!empty($categoryatribute->name_ar)) ? $categoryatribute->name_ar : '' }}" name="name" />
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Status</label>
                            <select class="form-select js-example-basic-single status-select" data-placeholder="Select Status" id="status" name="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($categoryatribute->status) && $categoryatribute->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($categoryatribute->status) && $categoryatribute->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="hstack gap-2 justify-content-between">
                        <a href="{{ route('admin.category_atributes') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($categoryatribute->id)) ? 'Update Category Atribute Value' : 'Create Category Atribute Value'  }} </button>

                    </div>
                </form>
            </div>
        </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 () {
            $("#categoryatributeForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 1,
                    },
                    name_ar: {
                        required: true,
                        minlength: 1,
                    },
                    status: {
                        required: true,
                    },
                    category_id: {
                        required: true,
                    },
                    attribute_id: {
                        required: true,
                    },
                    price: {
                        required: true,
                        number: true,
                        min: 0 
                    },
                },
                messages: {
                    name: {
                        required: "Please enter the Atribute name.",
                        minlength: "Atribute name must be at least 1 characters.",
                    },
                    status: {
                        required: "Please select the status.",
                    },
                    category_id: {
                        required: "Please select the Service.",
                    },
                    attribute_id: {
                        required: "Please select the Attribute.",
                    },
                    price: {
                        required: "Please enter the price.",
                        number: "Price must be a number.",
                        min: "Price cannot be negative."
                    },
                },
                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">`,
                               // title: "Success!",
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.category_atributes_value') }}"; // Redirect to company list
                            });
                        },
                        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"); // Add error class to the field
                                    field.after(`<label class="error">${value[0]}</label>`); // Add error message
                                });
                            } else { 
                                Swal.fire({
                                    text: "Something went wrong. Please try later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK", // Optional: Change the text of the button
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                    }
                                });
                            }
                        }
                    });

                    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); 
                }
            });
        });

        $(document).ready(function() {
            
            $('#category_id').change(function() {
                var category_id = $(this).val();

                // Make AJAX request to fetch attributes
                if(category_id) {
                    $.ajax({
                        url: "{{ route('admin.get_category_atributes') }}?category_id=" + category_id,
                        type: 'GET',
                        dataType: 'json',
                        success: function(data) {
                            $('#service_attributes').prop('disabled', false);

                            // Clear the existing options
                            $('#service_attributes').empty();
                            $('#service_attributes').append('<option value="">Select Attribute</option>');

                            // Populate the select options with the fetched attributes
                            $.each(data, function(key, value) {
                                // Pre-select the option if it matches the existing attribute_id
                                var selected = '{{ old('attribute_id', $categoryatribute->attribute_id ?? '') }}' == value.id ? 'selected' : '';
                                $('#service_attributes').append('<option value="' + value.id + '" ' + selected + '>' + value.name + '</option>');
                            });
                        }
                    });
                } else {
                    // If no service is selected, disable the attributes select
                    $('#service_attributes').prop('disabled', true);
                    $('#service_attributes').empty();
                    $('#service_attributes').append('<option value="">Select Attribute</option>');
                }
            });
            // Trigger change event on page load if category_id is already set
            if ($('#category_id').val()) {
                $('#category_id').trigger('change');
            }
        });

    </script>
    
@endsection
