@extends('layouts.main')

@section('breadcrumbs')
    {{ Breadcrumbs::render('bucok') }}
@endsection

@section('content')
    <div class="grid">
        <div class="min-w-full border card border-agi-100 card-grid" data-datatable="false" data-datatable-page-size="10" data-datatable-state-save="false" id="bucok-table" data-api-url="{{ route('bucok.datatables') }}">
            <div class="flex-wrap py-5 card-header bg-agi-50">
                <h3 class="card-title">
                    Data Bucok
                </h3>
                <div class="flex flex-wrap gap-2 lg:gap-5">
                    <div class="flex">
                        <label class="input input-sm">
                            <i class="ki-filled ki-magnifier"></i>
                            <input placeholder="Search Bucok" id="search" type="text" value="">
                        </label>
                    </div>
                    <div class="flex flex-wrap gap-2.5">
                        <div class="h-[24px] border border-r-gray-200"></div>

                        <!-- Filter Tahun -->
                        <select class="select select-sm" id="year-filter">
                            <option value="">Semua Tahun</option>
                            @for($year = date('Y'); $year >= 2020; $year--)
                                <option value="{{ $year }}">{{ $year }}</option>
                            @endfor
                        </select>

                        <!-- Filter Bulan -->
                        <select class="select select-sm" id="month-filter">
                            <option value="">Semua Bulan</option>
                            @for($month = 1; $month <= 12; $month++)
                                <option value="{{ $month }}">{{ DateTime::createFromFormat('!m', $month)->format('F') }}</option>
                            @endfor
                        </select>

                        <!-- Filter Status Penyelesaian -->
                        <select class="select select-sm" id="completion-status-filter">
                            <option value="">Semua Status</option>
                            <option value="1">Selesai</option>
                            <option value="0">Belum Selesai</option>
                        </select>

                        <!-- Import Excel -->
                        <button class="btn btn-sm btn-success" data-modal-toggle="#import-modal">
                            <i class="ki-filled ki-file-up"></i> Import Excel
                        </button>

                        <a class="btn btn-sm btn-light" href="#" id="export-excel">
                            <i class="ki-filled ki-file-down"></i> Export Excel
                        </a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="scrollable-x-auto">
                    <table class="table text-sm font-medium text-gray-700 align-middle table-auto table-border" data-datatable-table="true">
                        <thead>
                        <tr>
                            <th class="w-14">
                                <input class="checkbox checkbox-sm" data-datatable-check="true" type="checkbox"/>
                            </th>
                            <th class="min-w-[80px]" data-datatable-column="no">
                                <span class="sort">
                                    <span class="sort-label">No</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[100px]" data-datatable-column="tanggal">
                                <span class="sort">
                                    <span class="sort-label">Tanggal</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[120px]" data-datatable-column="nomor_tiket">
                                <span class="sort">
                                    <span class="sort-label">Nomor Tiket</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[100px]" data-datatable-column="nomor_coa">
                                <span class="sort">
                                    <span class="sort-label">Nomor COA</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[150px]" data-datatable-column="nama_coa">
                                <span class="sort">
                                    <span class="sort-label">Nama COA</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[200px]" data-datatable-column="deskripsi">
                                <span class="sort">
                                    <span class="sort-label">Deskripsi</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[120px]" data-datatable-column="nominal">
                                <span class="sort">
                                    <span class="sort-label">Nominal</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[100px]" data-datatable-column="cost_center">
                                <span class="sort">
                                    <span class="sort-label">Cost Center</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[100px]" data-datatable-column="status_penyelesaian">
                                <span class="sort">
                                    <span class="sort-label">Status</span>
                                    <span class="sort-icon"></span>
                                </span>
                            </th>
                            <th class="min-w-[50px] text-center" data-datatable-column="actions">Aksi</th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <div class="flex-col gap-3 justify-center font-medium text-gray-600 card-footer md:justify-between md:flex-row text-2sm">
                    <div class="flex gap-2 items-center">
                        Show
                        <select class="w-16 select select-sm" data-datatable-size="true" name="perpage"> </select> per page
                    </div>
                    <div class="flex gap-4 items-center">
                        <span data-datatable-info="true"> </span>
                        <div class="pagination" data-datatable-pagination="true">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Import Excel -->
    <div class="modal" data-modal="true" id="import-modal">
        <div class="modal-content max-w-[500px] top-[15%]">
            <div class="modal-header">
                <h3 class="modal-title">Import Data Bucok</h3>
                <button class="btn btn-sm btn-icon btn-light btn-clear shrink-0" data-modal-dismiss="true">
                    <i class="ki-filled ki-cross"></i>
                </button>
            </div>
            <form action="{{ route('bucok.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="flex flex-col gap-5">
                        <div class="flex flex-col gap-2.5">
                            <label class="text-gray-900 form-label">File Excel</label>
                            <input type="file" name="file" class="file-input" accept=".xlsx,.xls,.csv" required>
                            <div class="text-gray-600 text-2sm">
                                Format yang didukung: .xlsx, .xls, .csv (Maksimal 10MB)
                            </div>
                        </div>
                        <div class="p-3 bg-yellow-100 rounded border border-yellow-300">
                            <div class="text-sm text-yellow-800">
                                <strong>Catatan:</strong>
                                <ul class="mt-1 list-disc list-inside">
                                    <li>Data akan dimulai dari baris ke-5</li>
                                    <li>File Excel tidak perlu header</li>
                                    <li>Data akan di-update jika nomor tiket sudah ada</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="flex gap-4">
                        <button type="button" class="btn btn-light" data-modal-dismiss="true">Batal</button>
                        <button type="submit" class="btn btn-primary">Import</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        /**
         * Fungsi untuk menghapus data Bucok
         * @param {number} data - ID data yang akan dihapus
         */
        function deleteData(data) {
            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: "Data yang dihapus tidak dapat dikembalikan!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        }
                    });

                    $.ajax(`bucok/${data}`, {
                        type: 'DELETE'
                    }).then((response) => {
                        Swal.fire('Terhapus!', 'Data Bucok berhasil dihapus.', 'success').then(() => {
                            window.location.reload();
                        });
                    }).catch((error) => {
                        Swal.fire('Error!', error.responseJSON.message, 'error');
                    });
                }
            })
        }
    </script>

    <script type="module">
        /**
         * Inisialisasi DataTable untuk Bucok menggunakan KTDataTable
         */
        document.addEventListener('DOMContentLoaded', function() {
            const element = document.querySelector('#bucok-table');
            const searchInput = document.getElementById('search');
            const yearFilter = document.getElementById('year-filter');
            const monthFilter = document.getElementById('month-filter');
            const completionStatusFilter = document.getElementById('completion-status-filter');

            const apiUrl = element.getAttribute('data-api-url');

            // Konfigurasi DataTable menggunakan KTDataTable
            const dataTableOptions = {
                apiEndpoint: apiUrl,
                pageSize: 10,
                columns: {
                    select: {
                        render: (item, data, context) => {
                            const checkbox = document.createElement('input');
                            checkbox.className = 'checkbox checkbox-sm';
                            checkbox.type = 'checkbox';
                            checkbox.value = data.id.toString();
                            checkbox.setAttribute('data-datatable-row-check', 'true');
                            return checkbox.outerHTML.trim();
                        },
                    },
                    no: {
                        title: 'No',
                    },
                    tanggal: {
                        title: 'Tanggal',
                    },
                    nomor_tiket: {
                        title: 'Nomor Tiket',
                    },
                    nomor_coa: {
                        title: 'Nomor COA',
                    },
                    nama_coa: {
                        title: 'Nama COA',
                    },
                    deskripsi: {
                        title: 'Deskripsi',
                        render: (item, data) => {
                            const desc = data.deskripsi || '-';
                            return desc.length > 50 ? desc.substring(0, 50) + '...' : desc;
                        },
                    },
                    nominal: {
                        title: 'Nominal',
                    },
                    cost_center: {
                        title: 'Cost Center',
                    },
                    status_badge: {
                        title: 'Status',
                        render: (item, data) => {
                            return data.status_badge || '-';
                        },
                    },
                    actions: {
                        title: 'Aksi',
                        render: (item, data) => {
                            return data.actions || '';
                        },
                    }
                },
            };

            // Inisialisasi DataTable
            let dataTable = new KTDataTable(element, dataTableOptions);
            dataTable.showSpinner();

            // Fungsi pencarian
            searchInput.addEventListener('input', function () {
                const searchValue = this.value.trim();
                dataTable.search(searchValue, true);
            });

            // Filter berdasarkan tahun
            yearFilter.addEventListener('change', function() {
                const yearValue = this.value;
                // Implementasi filter tahun - perlu disesuaikan dengan API endpoint
                dataTable.setParam('year', yearValue);
                dataTable.reload();
            });

            // Filter berdasarkan bulan
            monthFilter.addEventListener('change', function() {
                const monthValue = this.value;
                // Implementasi filter bulan - perlu disesuaikan dengan API endpoint
                dataTable.setParam('month', monthValue);
                dataTable.reload();
            });

            // Filter berdasarkan status penyelesaian
            completionStatusFilter.addEventListener('change', function() {
                const statusValue = this.value;
                // Implementasi filter status - perlu disesuaikan dengan API endpoint
                dataTable.setParam('completion_status', statusValue);
                dataTable.reload();
            });

            // Export Excel functionality
            document.getElementById('export-excel').addEventListener('click', function(e) {
                e.preventDefault();

                // Build export URL with current filters
                const params = new URLSearchParams();
                if (searchInput.value) params.append('search', searchInput.value);
                if (yearFilter.value) params.append('year', yearFilter.value);
                if (monthFilter.value) params.append('month', monthFilter.value);
                if (completionStatusFilter.value) params.append('completion_status', completionStatusFilter.value);

                const exportUrl = '{{ route("bucok.export") }}?' + params.toString();
                window.open(exportUrl, '_blank');
            });
        });
    </script>
@endpush
