@extends("template.master")

@section("content")
    @if ($canCreate)
        <x-primary-button class="mb-4" id="btn-tambah-manufaktur">Tambah Pabrikan</x-primary-button>
    @endif
    <div class="card">
        <div class="card-body">
            <table class="table table-striped data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    <div class="modal fade" id="modalTambahmanufaktur" tabindex="-1" aria-labelledby="modalTambahLokasiLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="{{ route('manufactures.store') }}" id="form-tambah-manufaktur" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTambahLokasiLabel">Tambah Pabrikan</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="location-name" class="form-label">Nama Pabrikan</label>
                            <input type="text" class="form-control @error('name') is-invalid @enderror" id="location-name"
                                name="name" value="{{ old('name') }}" required>
                            @error('name')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                        <button type="submit" id="submit-tambah" class="btn btn-primary">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalEditmanufaktur" tabindex="-1" aria-labelledby="modalEditLokasiLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-edit-manufaktur" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalEditLokasiLabel">Ubah Pabrikan</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="edit-id">
                        <div class="mb-3">
                            <label for="edit-name" class="form-label">Nama Pabrikan</label>
                            <input type="text" class="form-control" id="edit-name" name="name" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                        <button type="submit" id="submit-edit" class="btn btn-primary">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

@endsection



@push("extraJS")
    <script type="text/javascript">

        @if(session('success'))
            Swal.fire({
                icon: 'success',
                title: 'Berhasil!',
                text: '{{ session('success') }}',
                showConfirmButton: false,
                timer: 2000
            });
        @endif

        @if(session('error'))
            Swal.fire({
                icon: 'error',
                title: 'Gagal!',
                text: '{{ session('error') }}'
            });
        @endif

            @if ($errors->any())
                const modal = new bootstrap.Modal(document.getElementById('#modalTambahmanufaktur'));
                modal.show();
            @endif

        $(function () {
            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('manufactures.index') }}",
                columnDefs: [
                    { width: "50px", targets: 0 }
                ],
                columns: [
                    {
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        className: 'text-center',
                        orderable: false,
                        searchable: false
                    },
                    { data: 'name', name: 'name' },
                    { data: 'action', name: 'action', orderable: false, searchable: false },
                ]
            });

        });

        $('#form-tambah-manufaktur').on("submit", function (e) {
            e.preventDefault();

            let formData = $(this).serialize();

            $.ajax({
                url: "{{ route('manufactures.store') }}",
                type: "POST",
                data: formData,
                success: function (res) {
                    $('#modalTambahmanufaktur').modal('hide');
                    $('.data-table').DataTable().ajax.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Pabrikan berhasil ditambahkan',
                        timer: 2000,
                        showConfirmButton: false
                    });
                    $('#location-name').val('');
                },
                error: function (xhr) {
                    handleValidationErrors(xhr, $('#form-tambah-manufaktur'));

                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: 'Harap periksa kembali input Anda.'
                    });
                }
            });
        });

        let routeUpdateLocation = "{{ route('manufactures.update', ':id') }}";
        let routeDeleteLocation = "{{ route('manufactures.destroy', ':id') }}";

        $(document).on('click', '.edit', function () {
            let id = $(this).data('id');
            let name = $(this).data('name');

            clearFormErrors('#form-edit-manufaktur');

            $('#edit-id').val(id);
            $('#edit-name').val(name);

            let updateUrl = routeUpdateLocation.replace(':id', id);

            $('#form-edit-manufaktur').attr('action', updateUrl);

            const modal = new bootstrap.Modal(document.getElementById('modalEditmanufaktur'));
            modal.show();
        });

        $('#form-edit-manufaktur').on("submit", function (e) {
            e.preventDefault();


            let formData = $(this).serialize();
            let updateUrl = $(this).attr('action');
            console.log(updateUrl);

            $.ajax({
                url: updateUrl,
                type: 'POST',
                data: formData,
                success: function (res) {
                    $('#modalEditmanufaktur').modal('hide');
                    $('.data-table').DataTable().ajax.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Pabrikan berhasil diperbarui',
                        timer: 2000,
                        showConfirmButton: false
                    });
                },
                error: function (xhr) {
                    handleValidationErrors(xhr, $('#form-edit-manufaktur'));

                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: 'Harap periksa kembali input Anda.'
                    });
                }
            });
        });

        $(document).ready(function () {
            $('#btn-tambah-manufaktur').on('click', function () {
                $('#modalTambahmanufaktur').modal('show');
                clearFormErrors('#form-tambah-manufaktur');
            });
        });


        $(document).on('click', '.delete', function () {
            let id = $(this).data('id');

            Swal.fire({
                title: 'Yakin ingin menghapus Pabrikan ini?',
                text: "Data tidak dapat dikembalikan setelah dihapus.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e3342f',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    const deleteUrl = routeDeleteLocation.replace(':id', id);

                    $.ajax({
                        url: deleteUrl,
                        type: 'POST',
                        data: {
                            _method: 'DELETE',
                            _token: '{{ csrf_token() }}'
                        },
                        success: function () {
                            $('.data-table').DataTable().ajax.reload();
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: 'Pabrikans berhasil dihapus',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        },
                        error: function (xhr) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal!',
                                text: xhr.responseJSON?.message ?? 'Data tidak bisa dihapus karena sedang digunakan.'
                            });
                        }
                    });
                }
            });
        });

        function clearFormErrors(formSelector) {
            $(formSelector).find('.is-invalid').removeClass('is-invalid');
            $(formSelector).find('.invalid-feedback').remove();
        }

        function handleValidationErrors(xhr, form) {
            if (xhr.status === 422) {
                let errors = xhr.responseJSON.errors;
                console.log(errors);
                for (let field in errors) {
                    let input = form.find(`[name="${field}"]`);
                    if (input.length === 0 && field.includes('.')) {
                        // For array fields like roles[0]
                        let nameAttr = field.replace(/\.\d+/, '[]');
                        input = form.find(`[name="${nameAttr}"]`);
                    }
                    input.addClass('is-invalid');
                    input.after(`<div class="invalid-feedback d-block">${errors[field][0]}</div>`);
                }
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan pada server.'
                });
            }
        }
    </script>

@endpush
