<div class="modal-header">
    <h5 class="modal-title" id="subCategoryModalLabel">Sub Categories</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <form action="{{ route('category.save-subcategory') }}" method="POST" id="subCategoryForm">
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="category_id" value="{{ $category_id ?? 0 }}">
        @csrf

        @foreach($subcategories as $subcategory)
        <div class="row">
            <div class="col-11">
                <div class="form-group" id="existing-subcategory-names-container">
                    <input type="text" name="existingNames[{{ $subcategory->id }}]" class="form-control" data-id="{{ $subcategory->id }}" 
                        placeholder="Enter Sub Category Name"
                        value="{{ $subcategory->name }}" required>
                </div>
            </div>
            <div class="col-1">
                <a data-toggle="modal" data-target="#subCategoryDeletePopup" data-url="{{route('sub_category.destroy',$subcategory->id)}}"  data-id="{{$subcategory->id}}" 
                    onclick="subCategoryDeletePopup(this)">
                    <button class="btn btn-danger btn-sm" data-toggle="tooltip" data-placement="right" title="Delete ">
                        <i class="fas fa-trash" aria-hidden="true"></i>
                    </button>
                </a>
            </div>
        </div>
        @endforeach

        <div class="form-group" id="modal-category-names-container">
            <label for="">Sub Category Name</label>
            <input type="text" name="name[]" class="form-control" id="" placeholder="Enter Sub Category Name"
                value="{{ old('name') }}">
            @if($errors->has('name'))
                <div class="form-text text-danger">{{ $errors->first('name') }}</div>
            @endif
        </div>
       
        <div class="card-footer">
            <div class="col-md-4 mt-30 append-buttons float-right">
                <div class="clearfix">
                    <button type="button" id="modal-add-button" class="btn btn-success float-left text-uppercase shadow-sm">
                        <i class="fa fa-plus fa-fw"></i>Add
                    </button>
                    <button type="button" id="modal-remove-button" class="btn btn-danger float-left text-uppercase ml-1" disabled>
                        <i class="fa fa-minus fa-fw"></i>Remove
                    </button>
                </div>
            </div>
            <button type="submit" class="btn btn-primary" >Save</button>
        </div>
    </form>
</div>

<script>
    $(document).ready(function() {
        var categoryCount = 1; // Start with one input field for category name

        // Handle Add button click event
        $('#modal-add-button').click(function() {
            categoryCount++;

            // Clone the first input field and update the name attribute
            var newInput = $('#modal-category-names-container input:first').clone();
            newInput.val(''); // Clear the value of the cloned input field

            newInput.removeAttr('required');
            // Update the name attribute to ensure all inputs are part of the 'name[]' array
            newInput.attr('name', 'name[]');

            // Append the cloned input field to the container
            $('#modal-category-names-container').append(newInput);

            // Enable remove button after adding a new input field
            $('#modal-remove-button').prop('disabled', false);
        });

        // Handle Remove button click event
        $('#modal-remove-button').click(function() {
            if (categoryCount > 1) {
                // Remove the last input field
                $('#modal-category-names-container input').last().remove();
                categoryCount--;
            }

            // Disable remove button if only one input field is left
            if (categoryCount <= 1) {
                $('#modal-remove-button').prop('disabled', true);
            }
        });
    });
</script>

<script>
    function subCategoryDeletePopup(elm) {
        $("#overlay").fadeIn(300);
        let id = $(elm).data('id');
        let url = $(elm).data('url');
        swal({
            title: 'Are you sure!',
            icon: 'error',
            dangerMode: true,
            buttons: true,
            confirm: "Confirm",
        }).then(function(isConfirm) {
            if (isConfirm === true) {
                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'json',
                    success: function(response) {
                        if (response.status) {
                            swal({
                                title: "Success!",
                                text: response.message,
                                icon: "success"
                            });
                        }
                        $('#subCategoryContent').html(response.html);
                        setTimeout(function() {
                            $("#overlay").fadeOut(300);
                        }, 500);
                        // window.location.reload();
                        // console.log(data);
                    },
                    error: function(data) {
                        console.log(data);
                    }
                });
            }
        });
    }
    $(document).ready(function() {
    
        $('#subCategoryForm').validate({
            rules: {
                existingNames: {
                    required: true,
                }
            },
            errorPlacement: function(error, element) {
                error.insertAfter(element);
            },
            submitHandler: function(form) {
                $("#overlay").fadeIn(300);
                // alert('ajax call');
                // return;
                // console.log($('#subCategoryForm').serialize()); return false;
                $.ajax({
                    url: "{{ route('category.save-subcategory') }}",
                    type: "POST",
                    data: $('#subCategoryForm').serialize(),
                    success: function(response) {
                        // console.log(response.status);
                        if (response.status) {
                            swal({
                                title: "Success!",
                                text: response.message,
                                icon: "success"
                            });
                        }else{
                            swal({
                                title: "Error!",
                                text: response.message,
                                icon: "error"
                            });
                        }
                        $('#subCategoryContent').html(response.html);
                        setTimeout(function() {
                            $("#overlay").fadeOut(300);
                        }, 500);
                    },
                    error: function(data) {
                        console.log(data);
                        setTimeout(function() {
                            $("#overlay").fadeOut(300);
                        }, 500);
                    }
                });
            }
        });

    });
</script>