@extends('template.master')

@section('content')
    @if ($canCreate)
        <x-primary-button class="mb-4" id="btn-tambah-lokasi">Add Location</x-primary-button>
    @endif
    <nav>
        <div class="nav nav-tabs" id="nav-tab" role="tablist">
            <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button"
                role="tab" aria-controls="nav-home" aria-selected="true">Lokasi Aktif</button>
            <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button"
                role="tab" aria-controls="nav-profile" aria-selected="false">Lokasi Hapus</button>

        </div>
    </nav>
    <div class="tab-content" id="nav-tabContent">
        <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
            <div class="card">
                <div class="card-body">
                    <table id="activeTable" 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>
        <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
            <div class="card">
                <div class="card-body">
                    <table id="trashTable" 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>
    </div>



    <div class="modal fade" id="modalTambahlokasi" tabindex="-1" aria-labelledby="modalTambahLokasiLabel"
        aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="{{ route('locations.store') }}" id="form-tambah-lokasi" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTambahLokasiLabel">Tambah Lokasi</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 Lokasi</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="modalEditlokasi" tabindex="-1" aria-labelledby="modalEditLokasiLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="form-edit-lokasi" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalEditLokasiLabel">Ubah Lokasi</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 Lokasi</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('modalTambahlokasi'));
            modal.show();
        @endif

        $(function() {
            var table = $('#activeTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('locations.index') }}",
                    data: (d) => {
                        d.option = "active"
                    }
                },
                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
                    },
                ]
            });
            var table2 = $('#trashTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('locations.index') }}",
                    data: (d) => {
                        d.option = "trash"
                    }
                },
                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-lokasi').on("submit", function(e) {
            e.preventDefault();

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

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

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

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

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

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

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

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

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

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

        $('#form-edit-lokasi').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) {
                    $('#modalEditlokasi').modal('hide');
                    $('.data-table').DataTable().ajax.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: 'Lokasi berhasil diperbarui',
                        timer: 2000,
                        showConfirmButton: false
                    });
                },
                error: function(xhr) {
                    handleValidationErrors(xhr, $('#form-edit-lokasi'));
                    console.log(xhr);

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

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


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

            let textConfirm =
                option == "restore" ?
                "Data lokasi akan dipulihkan." :
                option == "delete" ?
                "Data lokasi akan dihapus sementara (bisa dipulihkan kembali)." :
                "Data lokasi akan dihapus secara permanen dan tidak dapat dikembalikan!";

            let confirmBtnText =
                option == "restore" ?
                "Ya, pulihkan!" :
                option == "force-delete" ?
                "Ya, hapus permanen!" :
                "Ya, hapus!";

            let confirmBtnColor =
                option == "restore" ?
                "#ffae1f" :
                option == "force-delete" ?
                "#000" :
                "#d33";

            Swal.fire({
                title: "Apakah kamu yakin?",
                text: textConfirm,
                icon: "warning",
                showCancelButton: true,
                cancelButtonColor: "#3085d6",
                confirmButtonColor: confirmBtnColor,
                confirmButtonText: confirmBtnText,
                cancelButtonText: "Batal",
            }).then((result) => {
                if (result.isConfirmed) {
                    const deleteUrl = routeDeleteLocation.replace(":id", id);

                    $.ajax({
                        url: deleteUrl + "?option=" + option,
                        type: "POST",
                        data: {
                            _method: "DELETE",
                            _token: $('meta[name="csrf-token"]').attr("content"),
                        },
                        success: function(res) {
                            Swal.fire({
                                title: option == "restore" ?
                                    "Dipulihkan!" :
                                    option == "force-delete" ?
                                    "Dihapus Permanen!" :
                                    "Terhapus!",
                                text: res.message ?? "Proses berhasil dilakukan.",
                                icon: "success",
                                confirmButtonColor: "#3085d6",
                            });

                            $(".data-table").DataTable().ajax.reload();
                        },
                        error: function(xhr) {
                            console.log(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
