$(document).ready(function () {
    console.log($.fn.jquery);
    const today = moment();
    const startDate = moment(today).startOf('day').format('DD-MM-YYYY 00:00');
    const endDate =  moment(today).endOf('day').format('DD-MM-YYYY 23:59');

    $('.tambah-member').validate({
        rules: {
            nama: {
                required: true,
            },
        },
        messages: {
            nama: {
                required: 'Masukkan nama member',
            },
        },
        // errorElement: 'span',
        // errorPlacement: function (error, element) {
        //     error.addClass('invalid-feedback');
        //     // element.closest('.form-group').append(error);
        // },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass('is-invalid');
        }
    });

    $('.input-daterange-timepicker').daterangepicker({
        // singleDatePicker: true,
        timePicker: true,
        locale: {
            format: 'DD-MM-YYYY HH:mm'
        },
        timePicker24Hour: true,
        timePickerSeconds: false,
        buttonClasses: ['btn', 'btn-sm'],
        applyClass: 'btn-danger',
        cancelClass: 'btn-inverse',
        startDate: startDate,
        endDate: endDate,
    }, function (startDate, endDate) {
        console.log(`Range selected: ${startDate.format('DD-MM-YYYY HH:mm')} s/d ${endDate.format('DD-MM-YYYY HH:mm')}`);
        $('.input-daterange-timepicker').val(`${startDate.format('DD-MM-YYYY HH:mm')} s/d ${endDate.format('DD-MM-YYYY HH:mm')}`);
        // $('.awal').val(`${startDate.format('DD-MM-YYYY HH:mm')}`);
        // $('.akhir').val(`${endDate.format('DD-MM-YYYY HH:mm')}`);
    });

    // Set nilai awal dan akhir di input
    $('.input-daterange-timepicker').val(`${startDate} - ${endDate}`);
    // $('.awal').val(startDate);
    // $('.akhir').val(endDate);

    $('#jenisVehicle').on('change', function () {
        var jenisMembers = member;
        var vehicleSelected = $(this).val();
        var $jenisMember = $('#jenis-member');
        // console.log(jenisMembers);

        $jenisMember.empty();
        $jenisMember.append('<option selected value="">Pilih Jenis</option>');

        jenisMembers.forEach((item) => {
            if (item.id_mobil === vehicleSelected) {
                if (item.id_mobil !== 0 ) {
                    $jenisMember.append(
                        `<option value="${item.tarif}">${item.jenis_langganan} - ${item.tarif} </option>`
                    );
                    console.log($jenisMember);
                } else {
                    $jenisMember.append(
                        `<option value="">Tidak ada Pilihan </option>`
                    );
                }
            } 
        });
    });


    $('#nopol-add').on('click', function() {
        var nopol = $('.nopol-add').val().trim();
        console.log(nopol);
        // var vehicle = $('#jenisVehicle option:selected').text();
        var vehicle = $('#jenisVehicle').val();
        var vehicleName = $('#jenisVehicle option:selected').text();
        var member = $('#jenis-member option:selected').text();
        var merk = $('.merk').val().trim();
        $('.nopol-add').removeClass('is-invalid'); // Hapus kelas jika ada sebelumnya
        $('.nopol-add').next('.invalid-feedback').hide();

        if (!vehicle) {
            alert('Wajib pilih jenis kendaraan');
            return;
        }

        $.ajax ({
            url: 'member/checkField',
            type: 'POST',
            data: { nopol: nopol },
            headers: {'X-CSRF-token': $('meta[name="csrf-token"]').attr('content')},
            success: function (r) {
                if (r.response === true) {
                    var rowhtml = `
                        <tr>
                            <td class="text-center">${nopol}</td>
                            <td class="text-center" data-value="${vehicle}"">${vehicleName}</td>
                            <td class="text-center">${member}</td>
                            <td class="text-center">${merk}</td>
                            <td class="text-center p-1" style="text-align: center;">
                                <button class="btn btn-danger btn-xs delete-row">Hapus<buttion>
                            </td>
                        </tr>
                    `;
                    $('#list-nopol').append(rowhtml);
                    console.log('Berhasil menambahkan ' + nopol)

                    $('.nopol-add').val('');
                    $('#jenisVehicle').val('');
                    $('#jenis-member').val('');
                    $('.merk').val('');
                } else {
                    // var warn = `<div class="invalid-feedback">Nopol sudah ada</div>`;
                    $('.nopol-add').addClass('is-invalid'); // Tambahkan kelas invalid
                    $('.nopol-add').next('.invalid-feedback').text(r.message).show(); // Tampilkan pesan error
                    console.log(r.message);
                }
            },
            error: function () {
                alert('Terjadi kesalahan saat memeriksa nopol');
            }
        });
    });

    $('.kartu').on('keydown', function (e) {
        var kartu = $('.kartu').val().trim();

        if (e.key === 'Enter') {
            // $.ajax ({
            //     url: 'member/checkField',
            //     type: 'POST',
            //     data: {nocard: kartu},
            //     headers: {'X-CSRF-token': $('meta[name="csrf-token"]').attr('content')},
            //     success: function (r) {
                    // if (r.response === true) {
                        e.preventDefault();
                        $('.nourut').focus();
                    // }
            //     }
            // });
        }
    });

    $('.nourut').on('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();

            var nocard = $('.kartu').val().trim();
            var nourut = $('.nourut').val().trim();

            var rowHtml = `
                <tr>
                    <td class="text-center strong">${nocard}</td>
                    <td class="text-center strong">${nourut}</td>
                    <td class="text-center p-2" >
                        <button class="btn btn-danger btn-xs delete-row">Hapus<buttion>
                    </td>                            
                </tr>
            `;
            $('#list-card').append(rowHtml);
            $('.kartu').val('');
            $('.nourut').val('');
        }
    });


    $('#list-card').on('click', '.delete-row', function () {
        $(this).closest('tr').remove(); // Hapus baris yang diklik
    });

    $('.simpan').on('click', function () {
        var tombol = $(this);
        var formCollect = $('#add-member').serialize();
        var collectNopol = [];
        var cardCollect = [];

        $('#list-nopol tr').each(function () {
            var row = $(this);
            var rowData = {
                nopol: row.find('td:nth-child(1)').text().trim(),
                vehicle: row.find('td:nth-child(2)').data('value'),
                member: row.find('td:nth-child(3)').text().trim(),
                merk: row.find('td:nth-child(4)').text().trim(),
            };
            collectNopol.push(rowData);
        });

        console.log(collectNopol);

        $('#list-card tr').each(function () {
            var row = $(this);
            var rowCard = {
                nocard: row.find('td:nth-child(1)').text(),
                nourut: row.find('td:nth-child(2)').text(),
            };
            cardCollect.push(rowCard);
        });

        console.log(cardCollect);

        const formDataString = formCollect;

        // Mengonversi query string menjadi objek
        const formDataObj = {};
        const searchParams = new URLSearchParams(formDataString);

        searchParams.forEach((value, key) => {
            formDataObj[key] = value;
        });

        console.log(formDataObj);

        var allData = {
            formData: formDataObj,
            nopolData: collectNopol,
            cardNumber: cardCollect,
        };

        if($('.tambah-member').valid()) {
            $.ajax({
                url: $('#add-member').attr('action'),
                type: 'POST',
                data: allData,
                headers: {'X-CSRF-token': $('meta[name="csrf-token"]').attr('content')},
                beforeSend: function () {
                    tombol.attr('disabled',true);
                },
                success: function (r) {
                    // alert('Data berhasil dikirim');
                    $('#modal-member').modal('hide');
                    if (r.response == true) {
                        Swal.fire(
                            { 
                            title: "Berhasil!!", 
                            text: "Member anda telah terdaftar !!", 
                            timer: 5000, showConfirmButton: !1 
                            }
                        ).then(function() {
                            // Reload halaman setelah SweetAlert ditutup
                            location.reload(); // Ini akan me-reload halaman
                        });                
                    } else if (r.response == false) {
                        Swal.fire("Oops...", "Terjadi kendala !!", "silahkan hubungi admin", "error");
                    }
                    console.log(r);
                },
                error: function (xhr, status, error) {
                    alert('Terjadi kesalahan: ' + error);
                }
            });
        }
    });
});