@extends($variables['layout'])
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
@if(isset($print_data) && !empty($print_data))
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-center">
                        <h3 class="card-title m-0">{!! $variables['judul'] !!}</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table w-100 table-sm table-hover">
                                <thead class="bg-warning">
                                    <tr>
                                        <th>No</th>
                                        @foreach ($variables['f_columns'] as $key => $label)
                                        <th>{{ $label }}</th>
                                        @endforeach
                                    </tr>
                                </thead>
                                <tbody>
                                    {!! $print_data !!}
                                </tbody>
                            </table>
                        </div>
                    </div> <!-- /.card-body -->
                </div> <!-- /.card -->
            </div>
        </div>
    </div>
</section>
@else
{{-- Jika bukan print/export, tampilkan form filter + datatable --}}
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    {{-- Filter Header --}}
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-12">
                                <div id="filter-container">
                                    <div class="row filter-row mb-2">
                                        <div class="col-md-2">
                                            <select class="form-control form-control-sm form-control-sm filter-column" name="filter_column[]">
                                                <option value="">-- Select Column --</option>
                                                @foreach ($variables['f_columns'] as $key => $label)
                                                <option value="{{ $key }}">{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <select class="form-control form-control-sm form-control-sm filter-operator" name="filter_operator[]">
                                                @foreach ($variables['f_operators'] as $key => $label)
                                                <option value="{{ $label }}">{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-8">
                                            <input type="text" class="form-control form-control-sm form-control-sm filter-value" name="filter_value[]" placeholder="Value">
                                        </div>
                                        <div class="col-md-1">
                                            <button type="button" class="btn btn-danger btn-remove-filter btn-sm"><i class="fa fa-times"></i></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <button id="btn-add-filter" class="btn btn-sm btn-warning button-cek-permission" data-permission="reports.filter"><i class="fa fa-plus"></i> Add More</button>
                            </div>
                            <div class="col-md-8 text-end">
                                <div class="d-flex justify-content-end flex-wrap gap-2">
                                    <div class="col-auto">
                                        <label for="start_date" class="col-form-label">From</label>
                                    </div>
                                    <div class="col-auto">
                                        <input type="date" id="start_date" class="form-control form-control-sm form-control-sm" value="{{ date('Y-m-01') }}">
                                    </div>
                                    <div class="col-auto">
                                        <label class="col-form-label">Until</label>
                                    </div>
                                    <div class="col-auto">
                                        <input type="date" id="end_date" class="form-control form-control-sm form-control-sm" value="{{ date('Y-m-d') }}">
                                    </div>

                                    <div class="col">
                                        <button id="filter_button" class="btn btn-outline-info btn-sm button-cek-permission" data-permission="reports.search"><i class="fa fa-search"></i> Find</button>
                                        <button id="export_print_button" class="btn btn-outline-warning btn-sm button-cek-permission" data-permission="reports.print"><i class="fa fa-print"></i> Print</button>
                                        <button id="export_excel_button" class="btn btn-outline-success btn-sm button-cek-permission" data-permission="reports.export"><i class="fa fa-download"></i> Export Excel</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- DataTables --}}
                    <div class="card-body">
                        <table id="id_data_table" class="table w-100 table-sm table-hover">
                            <thead class="bg-warning">
                                <tr>
                                    <th>No</th>
                                    @foreach ($variables['f_columns'] as $key => $label)
                                    <th>{{ $label }}</th>
                                    @endforeach
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>
</section>

<script>
    $(function() {
        //buat trugger agar sidebar di hide/collapse
        $('body').addClass('sidebar-collapse')
        // Ambil key-key kolom dari Laravel
        const link_ = @json($variables['link_']);
        const columnKeys = @json($variables['column_keys']);
        const columnClassMap = @json($variables['f_column_class_name']);

        const dataTableColumns = [{
                data: 0,
                className: 'text-center',
                orderable: false,
                searchable: false
            },
            ...columnKeys.map((key, index) => ({
                data: index + 1,
                name: key,
                className: columnClassMap[key] ?? '' // kasih class kalau ada
            }))
        ];
        // console.log(dataTableColumns);
        const table = $('#id_data_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: link_,
                data: function(d) {
                    d.type = 'list';
                    d.start_date = $('#start_date').val();
                    d.end_date = $('#end_date').val();

                    // Loop semua filter
                    d.filters = [];
                    $('#filter-container .filter-row').each(function() {
                        let column = $(this).find('.filter-column').val();
                        let operator = $(this).find('.filter-operator').val();
                        let value = $(this).find('.filter-value').val();

                        if (column && operator && value) {
                            d.filters.push({
                                column: column,
                                operator: operator,
                                value: value
                            });
                        }
                    });
                }
            },
            columns: dataTableColumns,
            order: [
                [0, 'default_']
            ],
            responsive: true,
            lengthChange: true,
            autoWidth: false,
            drawCallback: function(settings) {
                $('[data-toggle="tooltip"]').tooltip();
            }
        });

        // Filter actions
        $('#filter_button').click(function() {
            table.ajax.reload();
        });

        $('#btn-add-filter').click(function() {
            let clone = $('#filter-container .filter-row:first').clone();
            clone.find('input, select').val('');
            $('#filter-container').append(clone);
        });

        $('#filter-container').on('click', '.btn-remove-filter', function() {
            if ($('#filter-container .filter-row').length > 1) { //sisain satu untuk copy saat click "add more"
                $(this).closest('.filter-row').remove();
            }
        });


        $('#export_excel_button, #export_print_button').click(function() {
            const type = $(this).attr('id') === 'export_excel_button' ? 'excel_all' : 'print_all';
            const start_date = $('#start_date').val();
            const end_date = $('#end_date').val();
            const filters = [];

            $('#filter-container .filter-row').each(function() {
                let column = $(this).find('.filter-column').val();
                let operator = $(this).find('.filter-operator').val();
                let value = $(this).find('.filter-value').val();
                if (column && operator && value) {
                    filters.push({
                        column,
                        operator,
                        value
                    });
                }
            });

            postToNewTab(link_, {
                type,
                start_date,
                end_date,
                filters
            });
        });

        function postToNewTab(url, data) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = url;
            form.target = '_blank';

            // CSRF token
            const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            const csrf = document.createElement('input');
            csrf.type = 'hidden';
            csrf.name = '_token';
            csrf.value = token;
            form.appendChild(csrf);

            // Semua data
            for (const key in data) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = typeof data[key] === 'object' ? JSON.stringify(data[key]) : data[key];
                form.appendChild(input);
            }

            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
    });
</script>
@endif
@endsection