@extends('admin.layout.template')
@section('title', 'Category')
@section('content')

<div class="page-content">
    <div class="container-xxl">

        <!-- Add Category Card -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title d-flex align-items-center gap-1">
                            <iconify-icon icon="solar:settings-bold-duotone" class="text-primary fs-20"></iconify-icon>
                            Add Category
                        </h4>
                    </div>
                    <div class="card-body">
                        <form id="addCategoryForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-lg-4">
                                    <div class="mb-3">
                                        <label class="form-label">Category</label>
                                        <input type="text" name="name" class="form-control" placeholder="Enter category name" required>
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="mb-3">
                                        <label class="form-label">Country</label>

                                        <select class="form-control" id="choices-multiple-remove-button" data-choices data-choices-removeItem name="country[]" multiple>
                                            @foreach(App\Models\Country::get() as $country)
                                            <option value="{{ $country->id }}"
                                                {{ isset($category) && $category->countries->contains($country->id) ? 'selected' : '' }}>
                                                {{ $country->name }}
                                            </option>
                                            @endforeach
                                        </select>



                                        <!-- <select class="form-control" name="country" required>
                                            @foreach(App\Models\Country::get() as $item)
                                                <option value="{{$item->id}}">{{$item->name}}</option>
                                            @endforeach
                                        </select> -->
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="mb-3">
                                        <label class="form-label">Image</label>
                                        <input type="file" name="photo" class="form-control" required>
                                    </div>
                                </div>
                            </div>
                            <div class="text-end">
                                <button type="submit" class="btn btn-success">Save Change</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Category Table -->
        <div class="row">
            <div class="col-xl-12">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table align-middle mb-0 table-hover table-centered">
                                <thead class="bg-light-subtle">
                                    <tr>
                                        <th>SL.NO</th>
                                        <th>Category</th>
                                        <th>Country</th>
                                        <th>Image</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
    // Pass countries as JSON
    var countries = @json(App\Models\Country::get(['id', 'name']));

    $(document).ready(function() {

        // Initialize DataTable
        var table = $('.table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('get-category') }}",
            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex'
                },
                {
                    data: 'name',
                    name: 'name'
                },

                {
                    data: 'country',
                    name: 'country'
                },
                {
                    data: 'image',
                    name: 'image'
                },
                {
                    data: 'action',
                    name: 'action'
                },

            ],
            "select": {
                'style': 'multi',
                'selector': 'td:first-child' //only checkbox can select row 
            },
        });

        // Add Category via AJAX
        $('#addCategoryForm').submit(function(e) {
            e.preventDefault();
            var formData = new FormData(this);
            $.ajax({
                url: "{{ route('add-category') }}",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Category Added!',
                        text: response.success,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    $('#addCategoryForm')[0].reset();
                    table.ajax.reload();
                },
                error: function(xhr) {
                    let errors = xhr.responseJSON.errors;
                    let errMsg = '';
                    $.each(errors, function(key, val) {
                        errMsg += val + '\n';
                    });
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops!',
                        text: errMsg,
                    });
                }
            });
        });

        // Delete Category
        $(document).on('click', '.deletecategory', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                customClass: {
                    popup: 'rounded-3 shadow-lg'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "{{ url('delete-category') }}/" + id,
                        type: 'DELETE',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(response) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Deleted!',
                                text: response.success,
                                showConfirmButton: false,
                                timer: 1500
                            });
                            table.ajax.reload();
                        }
                    });
                }
            });
        });

        // Cancel inline edit
        $(document).on('click', '.cancelEdit', function() {
            table.ajax.reload();
        });
        // Inline Edit
        $(document).on('click', '.editcategory', function(e) {
            e.preventDefault();

            var row = $(this).closest('tr');
            var id = $(this).data('id');
            var name = row.find('td:eq(1)').text();

            // Get multiple country IDs
            var countryIds = [];
            row.find('td:eq(2) span').each(function() {
                countryIds.push($(this).data('id'));
            });

            var imgSrc = row.find('td:eq(3) img').attr('src');

            // Name input
            row.find('td:eq(1)').html('<input type="text" class="form-control form-control-sm" value="' + name + '">');

            // Country multi-select using Choices.js
            var countrySelect = '<select class="form-control form-control-sm country-select" ' +
                'id="choices-select-' + id + '" data-choices data-choices-removeItem name="country[]" multiple>';

            countries.forEach(function(c) {
                var selected = countryIds.includes(c.id) ? 'selected' : '';
                countrySelect += '<option value="' + c.id + '" ' + selected + '>' + c.name + '</option>';
            });

            countrySelect += '</select>';

            row.find('td:eq(2)').html(countrySelect);

            // Image input
            row.find('td:eq(3)').html(
                '<input type="file" class="form-control form-control-sm" name="photo">' +
                '<img src="' + imgSrc + '" style="height:50px;margin-top:5px;">'
            );

            // Change buttons
            $(this).replaceWith(
                '<button class="btn btn-sm btn-success savecategory" data-id="' + id + '">Save</button> ' +
                '<button class="btn btn-sm btn-secondary cancelEdit">Cancel</button>'
            );

            // Initialize Choices.js AFTER appending the select
            new Choices('#choices-select-' + id, {
                removeItemButton: true, // allows removing
                searchEnabled: true
            });
        });




        // Save inline edit
        $(document).on('click', '.savecategory', function() {
            var id = $(this).data('id');
            var row = $(this).closest('tr');
            var name = row.find('td:eq(1) input').val();
            var country = row.find('td:eq(2) select').val(); // Choices returns array
            var photoFile = row.find('td:eq(3) input[type=file]')[0].files[0];

            var formData = new FormData();
            formData.append('_token', '{{ csrf_token() }}');
            formData.append('_method', 'PUT');
            formData.append('name', name);

            // Append countries as array
            country.forEach(function(id) {
                formData.append('country[]', id);
            });

            if (photoFile) {
                formData.append('photo', photoFile);
            }

            $.ajax({
                url: "{{ url('update-category') }}/" + id,
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Updated!',
                        text: response.success,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    table.ajax.reload();
                },
                error: function(xhr) {
                    let errors = xhr.responseJSON.errors;
                    let errMsg = '';
                    $.each(errors, function(k, v) {
                        errMsg += v + '\n';
                    });
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops!',
                        text: errMsg
                    });
                }
            });
        });


    });
</script>

@endsection