@extends('back.layout.page-layout')
@section('pageTitle', 'Carousel Image Manager')

@section('content')
<div class="card">
    <div class="card-body">
        <form id="carouselUploadForm" action="{{ route('admin.carouselphoto.list') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
                <label>Upload Carousel Images</label>
                <input type="file" name="photos[]" class="form-control" multiple required>
                <span class="text-danger photos_error"></span>
            </div>
            <button class="btn btn-primary mt-2">Upload</button>
        </form>

        <hr>

        @livewire('admin.carousel-image')
    </div>
</div>
@endsection

@push('scripts')
<script>
    window.addEventListener('confirmDeleteCarouselImage', function(event) {
        const id = event.detail[0].id;

        Swal.fire({
            title: 'Delete image?',
            text: 'This action is permanent.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it',
            cancelButtonText: 'Cancel',
        }).then((result) => {
            if (result.isConfirmed) {
                Livewire.dispatch('deleteCarouselImageAction', { id });
            }
        });
    });

    $(document).ready(function () {
        $('#carouselUploadForm').submit(function (e) {
            e.preventDefault();

            let form = this;
            let formData = new FormData(form);

            $.ajax({
                url: $(form).attr('action'),
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function () {
                    $('.photos_error').text('');
                },
                success: function (res) {
                    if (res.status === 1) {
                        form.reset();
                        toastr.success(res.message);
                        Livewire.dispatch('refreshCarousel');
                    } else {
                        toastr.error(res.message);
                    }
                },
                error: function (err) {
                    $.each(err.responseJSON.errors, function (key, val) {
                        if (key.startsWith('photos')) {
                            $('.photos_error').text(val[0]);
                        }
                    });
                }
            });
        });
    });
</script>
@endpush
