@extends('layouts.master')

@section('styles')
    <style>
        .card-body label {
            font-size: 13px;
            color: #6c757d;
        }

        .card-body .form-control,
        .card-body .form-select {
            font-size: 14px;
        }

        #search-button {
            font-weight: 600;
            letter-spacing: .3px;
        }

        .table-selectable tbody tr {
            cursor: pointer;
            transition: 0.15s;
        }

        .table-selectable tbody tr:hover {
            background-color: #f2f6ff;
        }

        .table-selectable tbody tr.selected {
            background-color: #0d6efd !important;
            color: #fff;
        }

        .table-selectable tbody tr.selected td {
            color: #fff !important;
        }
    </style>
@endsection

@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 shadow-sm h-100">
                            <div class="card-body">

                                <h5 class="card-title mb-4">Metode Pencarian Transaksi</h5>

                                <!-- DASAR PENCARIAN -->
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Dasar Pencarian</label>

                                    <select class="form-select mb-2" id="search-by">
                                        <option selected value="">Pencarian Data... (Semua)</option>
                                        <option value="nama">Nama</option>
                                        <option value="alamat">Alamat</option>
                                        <option value="nopol">No. Polisi</option>
                                        <option value="nocard">No. Card</option>
                                        <option value="notrans">No. Transaksi</option>
                                    </select>

                                    <input type="text" class="form-control" id="search-value" placeholder="Masukkan kata kunci...">
                                </div>

                                <hr class="my-3">

                                <!-- JENIS LANGGANAN -->
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Jenis Langganan</label>
                                    <select class="form-select" id="member-type">
                                        <option value="">Semua</option>
                                        @foreach ($memberSelect as $jenisLangganan)
                                            <option value="{{ $jenisLangganan->id }}">
                                                {{ $jenisLangganan->nama }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <!-- UNIT KERJA -->
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Unit Kerja</label>
                                    <select class="form-select" id="department">
                                        <option value="">Semua</option>
                                        @foreach ($departmentSelect as $jeniStiker)
                                            <option value="{{ $jeniStiker->kode }}">
                                                {{ $jeniStiker->nama }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <!-- KENDARAAN -->
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Kendaraan</label>
                                    <select class="form-select" id="vehicle">
                                        <option value="">Semua</option>
                                        @foreach ($vehicleSelect as $vehicle)
                                            <option value="{{ $vehicle->id }}">
                                                {{ $vehicle->nama }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <!-- KATEGORI -->
                                {{-- <div class="mb-4">
                                    <label class="form-label fw-semibold">Kategori</label>
                                    <input type="text"
                                        class="form-control"
                                        id="category"
                                        placeholder="Masukkan kategori...">
                                </div> --}}

                                <!-- BUTTON -->
                                <div class="d-grid">
                                    <button type="button" id="search-button" class="btn btn-primary">
                                        <i class="fa fa-search me-2"></i> 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">Transaksi Stiker / Langganan</h4>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div>
                                    <button class="btn btn-primary btn-sm add-button" data-bs-toggle="modal" data-bs-target=".bd-example-modal-lg">Tambah</button>
                                </div>
                                <div id="rowActions" class="d-none">
                                    <button class="btn btn-warning btn-sm edit-button" id="btnEdit" data-bs-toggle="modal" data-bs-target=".bd-ubah-modal-lg">Edit</button>
                                    <button class="btn btn-danger btn-sm" id="btnDelete">Hapus</button>
                                    <button class="btn btn-info btn-sm" id="btnDetail">Detail</button>
                                </div>
                            </div>
                            <div class="table-responsive pt-3">
                                <table class="table table-bordered table-selectable" 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 style="text-align: center;">No. Kartu</th>
                                            {{-- <th width="11%" style="text-align: center;">Action</th> --}}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        </tbody>
                                </table>
                            </div>
                                <!-- ADD MEMMBER MODAL -->
                                    @include('stiker.tambah-stiker')
                                    @include('stiker.ubah-stiker')
                                <!-- END MEMMBER MODAL -->
                            </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);

            let selectedRowData = null;

            $('#example tbody').on('click', 'tr', function () {

                const notrans = $(this).data('notrans');

                // hapus semua highlight
                $('#example tbody tr').removeClass('selected');

                // highlight semua row dalam 1 grup
                $(`#example tbody tr[data-notrans="${notrans}"]`).addClass('selected');

                // ambil data dari row pertama grup
                const firstRow = $(`#example tbody tr[data-notrans="${notrans}"]`).first();

                selectedRowData = {
                    notrans : firstRow.data('notrans')
                };

                console.log('Selected transaksi:', selectedRowData);

                $('#rowActions').removeClass('d-none');
            });

            $(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);
                    },
                });
            });

            $(document).on('click', '.edit-button', function () {
                let id = selectedRowData;
                $('#edit-member').attr('action', '/transaksi/member/' + id);
                $('#ubah-member').modal('show');
                // console.log(selectedRowData);
                // console.log(id);
                $.get(`/transaksi/member/${selectedRowData}`, function(res){

                    fillMemberModal(res);

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

                });
            });
            // $('#btnEdit').on('click', function(){

            //     if(!selectedRowData) {
            //         alert('Pilih data dulu');
            //         return;
            //     }
            //     console.log(selectedRowData);

            //     $.get(`/member/${selectedRowData.notrans}`, function(res){

            //         fillMemberModal(res);

            //         $('#modal-member').modal('show');

            //     });
            // });

            function fillMemberModal(res){

                let m = res.member;

                // TAB 1 - DATA PENGUNJUNG
                $('[name="nama"]').val(m.nama);
                $('[name="address"]').val(m.alamat);
                $('[name="daterange"]').val(m.awal + ' - ' + m.akhir);
                $('[name="member"]').val(m.jenis_langganan).trigger('change');
                $('[name="depart"]').val(m.dept).trigger('change');
                $('[name="note"]').val(m.note);
                $('[name="harga"]').val(m.harga);

                // =========================
                // TAB 2 - KENDARAAN
                // =========================
                $('#list-nopol').empty();

                res.kendaraan.forEach(v => {
                    $('#list-nopol').append(`
                        <tr>
                            <td>${v.nopol}</td>
                            <td>${v.jenis}</td>
                            <td>${v.merk}</td>
                            <td>${v.member}</td>
                            <td>
                                <button class="btn btn-danger btn-sm remove-nopol" data-id="${v.id}">Hapus</button>
                            </td>
                        </tr>
                    `);
                });

                // =========================
                // TAB 3 - KARTU
                // =========================
                $('#list-card').empty();

                res.kartu.forEach(k => {
                    $('#list-card').append(`
                        <tr>
                            <td>${k.kartu}</td>
                            <td>${k.nourut}</td>
                            <td>
                                <button class="btn btn-danger btn-sm remove-card" data-id="${k.id}">Hapus</button>
                            </td>
                        </tr>
                    `);
                });

            }

            $('#modal-member').on('hidden.bs.modal', function () {
                $(this).find('form')[0].reset();
                $('#list-nopol').empty();
                $('#list-card').empty();
            });
        });

    </script>
@endsection