@extends('layouts.template')

@section('content')
    @include('components.notification')

    <form action="">
        <div class="row">
            <div class="col-md-3">
                <label for="">Dari Tanggal</label>
                {{-- Use request()->get() with a default value to avoid 'Undefined index' --}}
                <input type="date" name="dari" id="" class="form-control"
                    value="{{ request()->get('dari', date('Y-m-d')) }}">
            </div>
            <div class="col-md-3">
                <label for="">Sampai Tanggal</label>
                {{-- Use request()->get() with a default value --}}
                <input type="date" name="sampai" id="" class="form-control"
                    value="{{ request()->get('sampai', date('Y-m-d')) }}">
            </div>
            <div class="col-md-3">
                <label for="">Cabang</label>
                <select class='form-control select2' name='branch'> {{-- Changed name to 'branch' for consistency with controller --}}
                    <option value=''>Semua Cabang</option>
                    @foreach ($branch as $item)
                        <option value='{{ $item->id }}' {{ request()->get('branch') == $item->id ? 'selected' : '' }}>
                            {{ $item->cabang }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label for="">Tipe Member</label>
                {{-- Add ID for JavaScript targeting --}}
                <select class='form-control select2' name='kategori_member' id="kategori_member_select">
                    <option value=''>Semua Kategori</option>
                    <option value="komunitas" {{ request()->get('kategori_member') == 'komunitas' ? 'selected' : '' }}>
                        Komunitas</option>
                    <option value="universitas" {{ request()->get('kategori_member') == 'universitas' ? 'selected' : '' }}>
                        Universitas</option>
                    <option value="corporate" {{ request()->get('kategori_member') == 'corporate' ? 'selected' : '' }}>
                        Corporate</option>
                    <option value="sekolah" {{ request()->get('kategori_member') == 'sekolah' ? 'selected' : '' }}>Sekolah
                    </option>
                </select>
            </div>
        </div>

        {{-- Dynamic Fields Container: These will be shown/hidden by JavaScript --}}
        {{-- <div class="row mt-3">
            <div class="col-md-3" id="komunitas_field" style="display:none;">
                <label for="nama_komunitas">Nama Komunitas</label>
                <input type="text" name="nama_komunitas" id="nama_komunitas" class="form-control"
                    value="{{ request()->get('nama_komunitas', '') }}">
            </div>

            <div class="col-md-3" id="universitas_field" style="display:none;">
                <label for="nama_universitas">Nama Universitas</label>
                <input type="text" name="nama_universitas" id="nama_universitas" class="form-control"
                    value="{{ request()->get('nama_universitas', '') }}">
            </div>
            <div class="col-md-3" id="himpunan_field" style="display:none;">
                <label for="nama_himpunan">Nama Himpunan</label>
                <input type="text" name="nama_himpunan" id="nama_himpunan" class="form-control"
                    value="{{ request()->get('nama_himpunan', '') }}">
            </div>

            <div class="col-md-3" id="corporate_field" style="display:none;">
                <label for="nama_perusahaan">Nama Perusahaan</label>
                <input type="text" name="nama_perusahaan" id="nama_perusahaan" class="form-control"
                    value="{{ request()->get('nama_perusahaan', '') }}">
            </div>

            <div class="col-md-3" id="sekolah_field" style="display:none;">
                <label for="nama_sekolah">Nama Sekolah</label>
                <input type="text" name="nama_sekolah" id="nama_sekolah" class="form-control"
                    value="{{ request()->get('nama_sekolah', '') }}">
            </div>
        </div> --}}

        <div class="row mt-3">
            <div class="col">
                <button type="submit" class="btn btn-primary"><span class="fa fa-filter"></span> Filter</button>
                {{-- Example of export button with proper query parameter handling --}}
                @if (request()->has('dari'))
                    {{-- Check if 'dari' exists before showing export --}}
                    <a href="{{ url('transaction/redeem/export?dari=' . request()->get('dari') . '&sampai=' . request()->get('sampai') . '&branch=' . request()->get('branch', '') . '&kategori_member=' . request()->get('kategori_member', '') . '&nama_komunitas=' . request()->get('nama_komunitas', '') . '&nama_universitas=' . request()->get('nama_universitas', '') . '&nama_himpunan=' . request()->get('nama_himpunan', '') . '&nama_perusahaan=' . request()->get('nama_perusahaan', '') . '&nama_sekolah=' . request()->get('nama_sekolah', '')) }}"
                        class="btn btn-success"><span class="fa fa-file-excel"></span> Export</a>
                @endif
            </div>
        </div>
    </form>

    <br>
    {{-- Conditionally include the table if filters are applied, or always show if you prefer --}}
    @if (request()->has('dari'))
        <div class="table-responsive">
            <table class="table table-hover myTable">
                <thead>
                    <tr class="table-primary">
                        <th class="text-center">#</th>
                        <th>No Nota</th>
                        <th>Nama Member</th>
                        <th>Tanggal Transaksi</th>
                        <th>Cabang</th>
                        <th>Kode Voucher</th>
                        <th>Nominal Voucher</th>
                        <th>Nominal Transaksi (Before PB1 10%)</th>
                        {{-- <th>Poin Didapat</th> --}}
                        <th>Keterangan</th> {{-- Re-added as 'tipe' column --}}
                        <th>Tipe Member</th> {{-- New Column Header --}}
                        <th>Detail Tipe Member</th> {{-- New Column Header --}}
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    {{-- Data will be loaded by DataTables --}}
                </tbody>
            </table>
        </div>
    @endif
@endsection

@push('custom-script')
    {{-- This DataTables script block should only run if 'dari' is set, to prevent errors on initial load --}}
    @if (request()->has('dari'))
        <script type="text/javascript">
            $(function() {
                // Build the AJAX URL safely by checking for each parameter
                let ajaxUrl = "<?= url('redeem') ?>?"; // Ensure this URL points to your redeem method
                const params = {
                    dari: "<?= request()->get('dari', date('Y-m-d')) ?>",
                    sampai: "<?= request()->get('sampai', date('Y-m-d')) ?>",
                    branch: "<?= request()->get('branch', '') ?>", // Use 'branch' for consistency
                    kategori_member: "<?= request()->get('kategori_member', '') ?>",
                    nama_komunitas: "<?= request()->get('nama_komunitas', '') ?>",
                    nama_universitas: "<?= request()->get('nama_universitas', '') ?>",
                    nama_himpunan: "<?= request()->get('nama_himpunan', '') ?>",
                    nama_perusahaan: "<?= request()->get('nama_perusahaan', '') ?>",
                    nama_sekolah: "<?= request()->get('nama_sekolah', '') ?>",
                };

                // Filter out empty parameters and build the query string
                const queryStrings = Object.keys(params)
                    .filter(key => params[key] !== '') // Only include non-empty parameters
                    .map(key => `${key}=${params[key]}`)
                    .join('&');

                ajaxUrl += queryStrings;

                var table = $('.myTable').DataTable({
                    processing: true,
                    serverSide: true,
                    orderable: false,
                    ajax: ajaxUrl, // Use the safely constructed URL
                    columns: [{
                            data: 'DT_RowIndex',
                            name: 'DT_RowIndex',
                            className: 'text-center'
                        }, // #
                        {
                            data: 'trx_code',
                            name: 'trx_code'
                        }, // No Nota
                        {
                            data: 'nama',
                            name: 'customer.nama'
                        }, // Nama Member
                        {
                            data: 'tgl_trx',
                            name: 'tgl_trx',
                            render: function(data, type, row) {
                                return indoDate(data);
                            }
                        }, // Tanggal Transaksi
                        {
                            data: 'cabang',
                            name: 'branch.cabang',
                            render: function(data, type, row) {
                                return data === '' || data === null ? 'Semua Cabang' : data;
                            }
                        }, // Cabang
                        {
                            data: 'voucher_code',
                            name: 'voucher_code',
                            render: function(data, type, row) {
                                return data === '' || data === null ? '-' : data;
                            }
                        }, // Kode Voucher
                        {
                            data: 'voucher_price',
                            name: 'voucher_price',
                            render: function(data, type, row) {
                                return row.voucher_code === '' || row.voucher_code === null ? '-' :
                                    new Intl.NumberFormat("id-ID", {
                                        style: "currency",
                                        currency: "IDR"
                                    }).format(data);
                            }
                        }, // Nominal Voucher
                        {
                            data: 'amount',
                            name: 'amount',
                            render: function(data, type, row) {
                                return new Intl.NumberFormat("id-ID", {
                                    style: "currency",
                                    currency: "IDR"
                                }).format(data);
                            }
                        }, // Nominal Transaksi (Before PB1 10%)
                        // { data: 'poin_earned', name: 'poin_earned' }, // Poin Didapat (commented out in HTML and here)
                        {
                            data: 'tipe',
                            name: 'tipe'
                        }, // Keterangan (from DB::raw in controller)
                        {
                            data: 'kategori_member',
                            name: 'customer.kategori_member',
                            orderable: false,
                            searchable: false
                        }, // Tipe Member
                        {
                            data: 'specific_member_data',
                            name: 'specific_member_data',
                            orderable: false,
                            searchable: false
                        }, // Detail Tipe Member
                        {
                            data: 'action',
                            name: 'action',
                            orderable: false,
                            searchable: false
                        } // Aksi
                    ],
                    order: [
                        [0, 'asc']
                    ],
                });
            });

            function indoDate(newDate) {
                const today = new Date(newDate);
                const yyyy = today.getFullYear();
                let mm = today.getMonth() + 1; // Months start at 0!
                let dd = today.getDate();
                let hh = newDate.substr(11, 2);
                let ii = newDate.substr(14, 2);

                if (dd < 10) dd = '0' + dd;
                if (mm < 10) mm = '0' + mm;

                const formattedToday = dd + '-' + mm + '-' + yyyy + ' ' + hh + ':' + ii;
                return formattedToday
            }
        </script>
    @endif {{-- End of conditional script for DataTables --}}

    {{-- This script handles dynamic field visibility and should always run --}}
    <script type="text/javascript">
        $(document).ready(function() {
            function toggleMemberFields() {
                const selectedType = $('#kategori_member_select').val();

                // Hide all specific member fields first using a combined selector
                $('#komunitas_field, #universitas_field, #himpunan_field, #corporate_field, #sekolah_field').hide();

                // Show fields based on the selected type
                if (selectedType === 'komunitas') {
                    $('#komunitas_field').show();
                } else if (selectedType === 'universitas') {
                    $('#universitas_field').show();
                    $('#himpunan_field').show(); // Himpunan is also related to Universitas
                } else if (selectedType === 'corporate') {
                    $('#corporate_field').show();
                } else if (selectedType === 'sekolah') {
                    $('#sekolah_field').show();
                }
            }

            // Call the function on page load to set initial state based on request parameters
            toggleMemberFields();

            // Attach change event listener to the select box
            $('#kategori_member_select').change(function() {
                toggleMemberFields();
            });
        });
    </script>
@endpush
