@extends('layouts.master')

@section('content')
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="row">
                    <div class="col-md-2 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Daftar Transaksi Langganan</h4>
                                <div class="form-group">
                                    <label>Dasar Pencarian</label>
                                    <div class="row">
                                        <div class="col-md-9">
                                            <select name="" id="">
                                                <option value="">Alamat</option>
                                            </select>
                                        </div>
                                        <div class="col-md-9">
                                            <input type="text" class="form-control form-control-lg" placeholder="Username" aria-label="Username">
                                        </div>
                                    </div>
                                </div>
                                </hr>
                                <div class="form-group">
                                    <label>Jenis Langganan</label>
                                    <input type="text" class="form-control" placeholder="Username" aria-label="Username">
                                </div>
                                <div class="form-group">
                                    <label>Unit Kerja</label>
                                    <input type="text" class="form-control form-control-sm" placeholder="Username" aria-label="Username">
                                </div>
                                <div class="form-group">
                                    <label>Kendaraan</label>
                                    <input type="text" class="form-control" placeholder="Username" aria-label="Username">
                                </div>
                                <div class="form-group">
                                    <label>Kategori</label>
                                    <input type="text" class="form-control form-control-sm" placeholder="Username" aria-label="Username">
                                </div>
                                <div class="form-group">
                                    <button type="button" id="search-button" class="btn btn-primary">Cari Data</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-10 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-body">
                            <h4 class="card-title">Bordered table</h4>
                            <div class="table-responsive pt-3">
                                <table class="table table-bordered" id="example" data-url="{{ route('getMember') }}">
                                    <thead>
                                        <tr>
                                            <th class="p-3" style="text-align: center;">No.</th>
                                            <th style="text-align: center;">No. Transaksi</th>
                                            <th style="text-align: center;">Nama</th>
                                            <th style="text-align: center;">Alamat</th>
                                            <th style="text-align: center;">Telepone</th>
                                            <th style="text-align: center;">Jenis Langganan</th>
                                            <th style="text-align: center;">Departement</th>
                                            <th style="text-align: center;">Periode</th>
                                            <th style="text-align: center;">Details Kendaraan</th>
                                            <th width="130"  style="text-align: center;">No. Kartu</th>
                                            <th width="11%" style="text-align: center;">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        </tbody>
                                </table>
                            </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('javascript')
<!--********* Scripts *********-->
    <!-- Datatable -->
    <!--********* Scripts *********-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/metisMenu/3.0.7/metisMenu.min.js"></script>
    <script src="{{asset ('vendor/moment/moment.min.js') }}"></script>
    <script src="{{asset ('vendor/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
	<script src="{{asset ('vendor/bootstrap-select/dist/js/bootstrap-select.min.js') }}"></script>
    <script src="{{asset ('vendor/sweetalert2/dist/sweetalert2.min.js') }}"></script>
    <script src="{{asset ('js/custom.min.js') }}"></script>
	<script src="{{asset ('js/dlabnav-init.js') }}"></script>
    <script src="{{asset ('js/member/index.js') }}"></script>
    <script>
        var member = @json($jenisStiker);
    </script>
    <script src="{{asset ('js/member/member-register.js') }}"></script>
    <script>
        $(document).ready(function () {
            var vehicle = @json($vehicleSelect);

            $(document).on('click', '.extend-button', function () {
                var rawId = $(this).data('id');
                let id = rawId.substring(0, rawId.indexOf('/'));
                var kendaraan = vehicle;
                console.log('Data ID : ', id);

                var actionUrl = '{{ route("member.show", ":id") }}';
                actionUrl = actionUrl.replace(':id', id);
                console.log('Action URL : ', actionUrl);
                // $('#extend-member').attr('action'), actionUrl;
                $.ajax({
                    url: actionUrl,
                    type: 'GET',
                    success: function (r) {
                        if (r) {
                            $('#extend-member').val('');
                            $('#list-nopol-ext').empty();
                            $('#list-card-ext').empty();
                            console.log(r.nama);
                            $('#notransnya').val(r.notrans);
                            $('#namanya').val(r.nama);
                            $('#address').val(r.alamat);
                            $('#periode').val(`${moment(r.awal).format('DD-MM-YYYY HH:mm')} - ${moment(r.akhir).format('DD-MM-YYYY HH:mm')}`);
                            $('#member-ext').val(r.unit_kerja);
                            $('#department-ext').val(r.jenis_langganan);
                            var rows = r.stiker_details;
                            if (rows.length !== 0) {
                                rows.forEach(row => {
                                var vehicleName = vehicle.find(v => v.id === row.jenis_mobil)?.nama || 'Unknown';
                                $('#list-nopol-ext').append(`
                                <tr>
                                    <td class="text-center p-2">${row.nopol}</td>
                                        <td class="text-center p-2" data-value="${row.jenis_mobil}">${vehicleName}</td>
                                        <td class="text-center p-2">${row.merk}</td>
                                        <td class="text-center p-2">${row.jenis_member}</td>
                                    </tr>
                                `);
                                });
                            } else {
                                $('#list-nopol-ext').append(`
                                    <tr>
                                        <td class="text-center p-2">Tidak ada data</td>
                                        <td class="text-center p-2">Tidak ada data</td>
                                        <td class="text-center p-2">Tidak ada data</td>
                                        <td class="text-center p-2">Tidak ada data</td>
                                    </tr>
                                `);
                            }
                            
                            var rowss = r.member_card;
                            if (rowss.length !== 0) {
                                rowss.forEach(ro => {
                                    $('#list-card-ext').append(`
                                        <tr>
                                            <td class="text-center p-2">${ro.no_card}</td>
                                            <td class="text-center p-2">${ro.no_urut}</td>
                                        </tr>
                                    `);
                                });
                            } else {
                                $('#list-card-ext').append(`
                                    <tr>
                                        <td class="text-center p-2">Tidak ada data</td>
                                        <td class="text-center p-2">Tidak ada data</td>
                                    </tr>
                                `);
                            }
                            console.log('Data : ', r);
                        }
                    },
                    error: function (xhr) {
                        console.error('Error : ', xhr);
                    },
                });

                $('#modal-member-extend').modal('show');
            });

            $('.extend').on('click', function () {
                // $('#modal-member-extend').modal('show');
                var url = $('#extend-member').attr('action').replace(":notrans",$("#extend-member").data('notrans'));
                var extend = $(this);
                var formExtend = $('#extend-member').serialize();
                var nopolData = [];
                var cardData = [];

                $('#list-nopol-ext 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(),
                    };
                    nopolData.push(rowData);
                });

                console.log(nopolData);

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

                const stringDataExt = formExtend;

                // Mengonversi query string menjadi objek
                const formDataExt = {};
                const searchExtend = new URLSearchParams(stringDataExt);

                searchExtend.forEach((value, key) => {
                    formDataExt[key] = value;
                });

                // console.log(formDataExt);

                var extData = {
                    formData: formDataExt,
                    nopolData: nopolData,
                    cardNumber: cardData,
                };
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: extData,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    berforeSend: function () {
                        extend.text('Loading...');
                    },
                    success: function (data) {
                        if (data.response === true) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil',
                                text: data.message,
                            });
                            $('#modal-member-extend').modal('hide');
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal',
                                text: data.message,
                            });
                        }
                        console.log(data);
                    },
                    error: function (xhr) {
                        console.error('Error : ', xhr);
                    },
                });
            });
        });
    </script>
@endsection