@extends('base.layout')
@section('content')
<style>
    .rekap-toolbar {
        position: sticky;
        top: 0;
        z-index: 5;
        background: #fff;
        padding-bottom: 10px;
    }
    .rekap-table-wrap {
        max-height: 65vh;
        overflow: auto;
        border: 1px solid #dee2e6;
    }
    #penerimaansamplereport thead th {
        position: sticky;
        top: 0;
        z-index: 2;
        background: #f8f9fa;
    }
    .status-print-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 600;
        white-space: nowrap;
    }
    .status-print-badge.pending {
        background: #e9ecef;
        color: #495057;
    }
    .status-print-badge.done {
        background: #d4edda;
        color: #155724;
    }
    tr.printed-row {
        background-color: #f8f9fa;
    }
</style>
<div class="wrapper">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-4">
                <div class="mb-2">
                    <h5>Riwayat Cetak</h5>
                    <div class="table-responsive" style="max-height: 220px; overflow:auto; border:1px solid #dee2e6;">
                        <table class="table table-sm table-bordered mb-0" id="printHistoryTable">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Waktu Cetak</th>
                                    <th>Petugas</th>
                                    <th>Jumlah Row</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody id="printHistoryBody">
                                @forelse(($printHistories ?? []) as $idx => $history)
                                    <tr data-history-id="{{ $history['id'] }}">
                                        <td>{{ $idx + 1 }}</td>
                                        <td>{{ $history['printed_at_label'] }}</td>
                                        <td>{{ $history['printed_by_name'] }}</td>
                                        <td>{{ $history['total_rows'] }}</td>
                                        <td>
                                            <button type="button" class="btn btn-xs btn-info btn-reprint-history" data-history-id="{{ $history['id'] }}">
                                                Cetak Ulang
                                            </button>
                                        </td>
                                    </tr>
                                @empty
                                    <tr id="emptyHistoryRow">
                                        <td colspan="5" class="text-center">Belum ada riwayat cetak.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-sm-8">
                <div class="card-box ribbon-box">
                    <div class="ribbon ribbon-danger">Rekapitulasi Penerimaan Sample {{$tanggal}}</div>
                    <p></p>
                    <div class="table-responsive">
                        <div class="rekap-toolbar">
                            <button type="button" class="btn btn-primary" id="btnexport"><i class="fa fa-file-excel-o"></i> Export</button>
                            <select id="printOrientation" class="btn btn-default">
                                <option value="landscape">Landscape</option>
                                <option value="portrait">Portrait</option>
                            </select>
                            <select id="sortStatus" class="btn btn-default">
                                <option value="default">Sort Status (Default)</option>
                                <option value="asc">Sort Status A-Z</option>
                                <option value="desc">Sort Status Z-A</option>
                            </select>
                            <select id="filterStatus" class="btn btn-default">
                                <option value="">Filter Status: Semua</option>
                            </select>
                            <select id="filterCetak" class="btn btn-default">
                                <option value="">Filter Cetak: Semua</option>
                                <option value="done">Sudah Dicetak</option>
                                <option value="pending">Belum Dicetak</option>
                            </select>
                            <button type="button" class="btn btn-success" id="btnprintselected"><i class="fa fa-print"></i> Cetak Terpilih</button>
                        </div>
                        <div class="rekap-table-wrap">
                            <table class="table table-bordered table-striped" id="penerimaansamplereport">
                                <thead>
                                    <tr>
                                        <th style="width: 40px; text-align:center;">
                                            <input type="checkbox" id="checkAllRows">
                                        </th>
                                        <th>Keterangan Cetak</th>
                                        <th>Status</th>
                                        <th>Tanggal Terima</th>
                                        <th>Petugas</th>
                                        <th>No.RM</th>
                                        <th>Nama</th>
                                        <th>No.Sample</th>
                                        <th>Asal Pasien</th>
                                        <th>Daftar</th>
                                        <th>Order</th>
                                        <th>Kode</th>
                                        <th>Spesimen</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($detail as $r)
                                        @php
                                            $isPrinted = !empty($r['ppdsjunior2']) && $r['ppdsjunior2'] != '0';
                                            $statusValue = trim((string)($r['status'] ?? ''));
                                            if ($statusValue === '') {
                                                $statusValue = '-';
                                            }
                                            $petugas = '';
                                            if ($r['nmppdsmiddle2'] != '') {
                                                $petugas = $r['nmppdsmiddle2'];
                                            }
                                            if ($r['nmppdsjunior2'] != '') {
                                                $petugas = trim($petugas.' '.$r['nmppdsjunior2']);
                                            }
                                        @endphp
                                        <tr data-id="{{ $r['id'] }}" data-status="{{ strtolower($statusValue) }}" data-printed="{{ $isPrinted ? 'done' : 'pending' }}" data-order="{{ $loop->index }}" class="{{ $isPrinted ? 'printed-row' : '' }}">
                                            <td style="text-align:center;">
                                                <input type="checkbox" class="row-check" {{ $isPrinted ? 'disabled' : '' }}>
                                            </td>
                                            <td class="print-status-cell">
                                                @if($isPrinted)
                                                    <span class="status-print-badge done">Sudah Dicetak</span>
                                                @else
                                                    <span class="status-print-badge pending">Belum Dicetak</span>
                                                @endif
                                            </td>
                                            <td>{{ $statusValue }}</td>
                                            <td>{{ $r['tgldraft'] }}</td>
                                            <td class="petugas-cell">{{ $petugas }}</td>
                                            <td>{{ $r['noregister'] }}</td>
                                            <td>{{ $r['nmpasien'] }}</td>
                                            <td>{{ $r['nofoto'] }}</td>
                                            <td>{{ $r['asalpasien'] }}</td>
                                            <td>{{ $r['daftar'] }}</td>
                                            <td>{{ $r['reques'] }}</td>
                                            <td>{{ $r['kd_spesimen'] }}</td>
                                            <td>{{ $r['nm_spesimen'] }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
@endsection
@push('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
        var table = document.getElementById('penerimaansamplereport');
        var tableBody = table ? table.querySelector('tbody') : null;
        var checkAllRows = document.getElementById('checkAllRows');
        var printOrientation = document.getElementById('printOrientation');
        var sortStatus = document.getElementById('sortStatus');
        var filterStatus = document.getElementById('filterStatus');
        var filterCetak = document.getElementById('filterCetak');
        var printHistoryBody = document.getElementById('printHistoryBody');
        var token = document.getElementById('token').value;
        var markPrintedUrl = @json(route('markRekapPenerimaanSamplePrinted'));
        var selectedTanggal = @json($tanggal);
        var printHistories = @json($printHistories ?? []);
        var printHistoryMap = {};
        var printHistoryMetaMap = {};
        var appName = @json(config('global.namaapps'));
        var appDomain = @json(config('global.domainapps'));
        var appSubDomain = @json(config('global.subdomainapps'));
        var appSubSubDomain = @json(config('global.subsubdomainapps'));
        var appAddress = @json(config('global.addressapps'));
        var petugasCetak = @json(Session('nama'));
        printHistories.forEach(function(item) {
            printHistoryMap[String(item.id)] = item.rows_payload || [];
            printHistoryMetaMap[String(item.id)] = {
                printed_by_name: item.printed_by_name || '',
                printed_at_label: item.printed_at_label || ''
            };
        });

        function renderHistoryNumbers() {
            if (!printHistoryBody) {
                return;
            }
            var rows = printHistoryBody.querySelectorAll('tr[data-history-id]');
            rows.forEach(function(row, idx) {
                var firstCell = row.querySelector('td');
                if (firstCell) {
                    firstCell.innerText = idx + 1;
                }
            });
        }

        function addHistoryRow(history) {
            if (!printHistoryBody || !history) {
                return;
            }
            var emptyRow = document.getElementById('emptyHistoryRow');
            if (emptyRow) {
                emptyRow.remove();
            }

            printHistoryMap[String(history.id)] = history.rows_payload || [];
            printHistoryMetaMap[String(history.id)] = {
                printed_by_name: history.printed_by_name || '',
                printed_at_label: history.printed_at_label || ''
            };
            var tr = document.createElement('tr');
            tr.setAttribute('data-history-id', history.id);
            tr.innerHTML = ''
                + '<td>1</td>'
                + '<td>' + (history.printed_at_label || '-') + '</td>'
                + '<td>' + (history.printed_by_name || '-') + '</td>'
                + '<td>' + (history.total_rows || 0) + '</td>'
                + '<td><button type="button" class="btn btn-xs btn-info btn-reprint-history" data-history-id="' + history.id + '">Cetak Ulang</button></td>';
            if (printHistoryBody.firstChild) {
                printHistoryBody.insertBefore(tr, printHistoryBody.firstChild);
            } else {
                printHistoryBody.appendChild(tr);
            }
            renderHistoryNumbers();
        }

        function openPrintWindowFromRows(printedRows, printMeta) {
            if (!printedRows || printedRows.length === 0) {
                alert('Data riwayat cetak tidak ditemukan.');
                return;
            }

            var now = new Date();
            var orientation = printOrientation ? printOrientation.value : 'landscape';
            var tanggalCetakDefault = now.toLocaleString('id-ID', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            var tanggalCetak = (printMeta && printMeta.printed_at_label) ? printMeta.printed_at_label : tanggalCetakDefault;
            var petugasCetakLabel = (printMeta && printMeta.printed_by_name) ? printMeta.printed_by_name : (petugasCetak || '-');

            var printWindow = window.open('', '_blank');
            if (!printWindow) {
                alert('Pop-up diblokir browser. Izinkan pop-up untuk mencetak.');
                return;
            }

            var rowsHtml = '';
            printedRows.forEach(function(rowData) {
                rowsHtml += '<tr>'
                    + '<td>' + (rowData.noregister || '') + '</td>'
                    + '<td>' + (rowData.nmpasien || '') + '</td>'
                    + '<td>' + (rowData.nofoto || '') + '</td>'
                    + '<td>' + (rowData.asalpasien || '') + '</td>'
                    + '<td>' + (rowData.daftar || '') + '</td>'
                    + '<td>' + (rowData.reques || '') + '</td>'
                    + '<td>' + (rowData.kd_spesimen || '') + '</td>'
                    + '<td>' + (rowData.nm_spesimen || '') + '</td>'
                    + '<td>' + (rowData.status || '') + '</td>'
                    + '<td>' + (rowData.tgldraft || '') + '</td>'
                    + '<td>' + (rowData.petugas || '') + '</td>'
                    + '</tr>';
            });

            var html = ''
                + '<!DOCTYPE html>'
                + '<html><head><title>Cetak Rekap Penerimaan Sample</title>'
                + '<style>'
                + '@page { size: A4 ' + orientation + '; margin: 10mm; }'
                + 'body { font-family: Arial, sans-serif; margin: 0; color: #111; }'
                + '.header { text-align: center; margin-bottom: 8px; }'
                + '.header h2 { margin: 0; font-size: 16px; }'
                + '.header .line { margin: 2px 0; font-size: 12px; }'
                + '.meta { display: flex; justify-content: space-between; margin: 8px 0 10px; font-size: 11px; }'
                + '.title { text-align: center; font-weight: 700; margin-bottom: 8px; font-size: 12px; }'
                + 'table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 10px; }'
                + 'th, td { border: 1px solid #000; padding: 3px; word-break: break-word; vertical-align: top; }'
                + 'th { background: #f1f1f1; }'
                + '</style></head><body>'
                + '<div class="header">'
                + '<h2>' + (appName || '') + '</h2>'
                + '<div class="line">' + (appDomain || '') + '</div>'
                + '<div class="line">' + (appSubDomain || '') + ', ' + (appSubSubDomain || '') + '</div>'
                + '<div class="line">' + (appAddress || '') + '</div>'
                + '</div>'
                + '<div class="title">Rekapitulasi Penerimaan Sample {{$tanggal}}</div>'
                + '<div class="meta">'
                + '<div>Tanggal Cetak: ' + tanggalCetak + '</div>'
                + '<div>Petugas: ' + petugasCetakLabel + '</div>'
                + '</div>'
                + '<table>'
                + '<thead><tr>'
                + '<th>No.RM</th>'
                + '<th>Nama</th>'
                + '<th>No.Sample</th>'
                + '<th>Asal Pasien</th>'
                + '<th>Daftar</th>'
                + '<th>Order</th>'
                + '<th>Kode</th>'
                + '<th>Spesimen</th>'
                + '<th>Status</th>'
                + '<th>Tanggal Terima</th>'
                + '<th>Petugas</th>'
                + '</tr></thead>'
                + '<tbody>' + rowsHtml + '</tbody>'
                + '</table>'
                + '<script>window.onload = function(){ window.print(); window.close(); };<\/script>'
                + '</body></html>';

            printWindow.document.open();
            printWindow.document.write(html);
            printWindow.document.close();
        }

        function getEnabledVisibleChecks() {
            return table ? table.querySelectorAll('tbody tr:not([style*="display: none"]) .row-check:not(:disabled)') : [];
        }

        function updateCheckAllState() {
            if (!checkAllRows) {
                return;
            }
            var rowChecks = getEnabledVisibleChecks();
            var checkedCount = 0;
            rowChecks.forEach(function(cb) {
                if (cb.checked) {
                    checkedCount++;
                }
            });
            checkAllRows.checked = rowChecks.length > 0 && rowChecks.length === checkedCount;
        }

        function initStatusFilterOptions() {
            if (!table || !filterStatus) {
                return;
            }
            while (filterStatus.options.length > 1) {
                filterStatus.remove(1);
            }

            // Status yang valid untuk rekap penerimaan sample
            var allowed = ['-', 'Pemeriksaan awal', 'Pemeriksaan Sampel', 'Penerimaan Sampel'];
            allowed.forEach(function(status) {
                var opt = document.createElement('option');
                opt.value = status.toLowerCase();
                opt.textContent = 'Status: ' + status;
                filterStatus.appendChild(opt);
            });
        }

        function applyStatusSortFilter() {
            if (!tableBody) {
                return;
            }

            var rows = Array.from(tableBody.querySelectorAll('tr'));
            var sortMode = sortStatus ? sortStatus.value : 'default';
            var selectedStatus = filterStatus ? filterStatus.value : '';
            var selectedCetak = filterCetak ? filterCetak.value : '';

            rows.sort(function(a, b) {
                if (sortMode === 'asc') {
                    return (a.dataset.status || '').localeCompare(b.dataset.status || '');
                }
                if (sortMode === 'desc') {
                    return (b.dataset.status || '').localeCompare(a.dataset.status || '');
                }
                return parseInt(a.dataset.order || '0', 10) - parseInt(b.dataset.order || '0', 10);
            });

            rows.forEach(function(row) {
                tableBody.appendChild(row);
                var rowStatus = row.dataset.status || '';
                var rowPrinted = row.dataset.printed || '';
                var showByStatus = (selectedStatus === '' || rowStatus === selectedStatus);
                var showByCetak = (selectedCetak === '' || rowPrinted === selectedCetak);
                var show = showByStatus && showByCetak;
                row.style.display = show ? '' : 'none';
                if (!show) {
                    var cb = row.querySelector('.row-check');
                    if (cb) {
                        cb.checked = false;
                    }
                }
            });

            if (checkAllRows) {
                checkAllRows.checked = false;
            }
            updateCheckAllState();
        }

        if (checkAllRows && table) {
            checkAllRows.addEventListener('change', function() {
                getEnabledVisibleChecks().forEach(function(cb) {
                    cb.checked = checkAllRows.checked;
                });
            });

            table.addEventListener('change', function(e) {
                if (e.target && e.target.classList.contains('row-check')) {
                    updateCheckAllState();
                }
            });
        }

        if (sortStatus) {
            sortStatus.addEventListener('change', applyStatusSortFilter);
        }

        if (filterStatus) {
            filterStatus.addEventListener('change', applyStatusSortFilter);
        }
        if (filterCetak) {
            filterCetak.addEventListener('change', applyStatusSortFilter);
        }

        initStatusFilterOptions();
        applyStatusSortFilter();

        document.getElementById('btnexport').addEventListener('click', function() {
            if (table) {
                var wb = XLSX.utils.table_to_book(table, { sheet: "Report" });
                XLSX.writeFile(wb, "Rekap_Penerimaan_Sample_{{$tanggal}}.xlsx");
            }
        });

        document.getElementById('btnprintselected').addEventListener('click', function() {
            if (!table) {
                return;
            }

            var selectedRows = table.querySelectorAll('tbody tr');
            var printedRows = [];
            var selectedIds = [];
            var selectedRowElements = [];

            selectedRows.forEach(function(row) {
                if (row.style.display === 'none') {
                    return;
                }
                var rowCheck = row.querySelector('.row-check');
                if (rowCheck && rowCheck.checked) {
                    var cells = row.querySelectorAll('td');
                    var rowId = parseInt(row.getAttribute('data-id'), 10);
                    if (!isNaN(rowId)) {
                        selectedIds.push(rowId);
                        selectedRowElements.push(row);
                    }
                    printedRows.push([
                        cells[2] ? cells[2].innerText : '',
                        cells[3] ? cells[3].innerText : '',
                        cells[4] ? cells[4].innerText : '',
                        cells[5] ? cells[5].innerText : '',
                        cells[6] ? cells[6].innerText : '',
                        cells[7] ? cells[7].innerText : '',
                        cells[8] ? cells[8].innerText : '',
                        cells[9] ? cells[9].innerText : '',
                        cells[10] ? cells[10].innerText : '',
                        cells[11] ? cells[11].innerText : '',
                        cells[12] ? cells[12].innerText : ''
                    ]);
                }
            });

            if (printedRows.length === 0 || selectedIds.length === 0) {
                alert('Pilih minimal satu baris untuk dicetak.');
                return;
            }

            $.post(markPrintedUrl, { ids: selectedIds, tanggal: selectedTanggal, _token: token }, function(resp) {
                if (!resp || resp.status !== 'success') {
                    alert((resp && resp.message) ? resp.message : 'Gagal memperbarui status cetak.');
                    return;
                }

                var affectedIds = Array.isArray(resp.affected_ids) ? resp.affected_ids : [];
                var affectedMap = {};
                affectedIds.forEach(function(id) {
                    affectedMap[String(id)] = true;
                });

                selectedRowElements.forEach(function(row) {
                    var id = row.getAttribute('data-id');
                    if (affectedMap[id]) {
                        row.classList.add('printed-row');
                        var rowCheck = row.querySelector('.row-check');
                        if (rowCheck) {
                            rowCheck.checked = false;
                            rowCheck.disabled = true;
                        }
                        var statusCell = row.querySelector('.print-status-cell');
                        if (statusCell) {
                            statusCell.innerHTML = '<span class="status-print-badge done">Sudah Dicetak</span>';
                        }
                        var petugasCell = row.querySelector('.petugas-cell');
                        if (petugasCell && (!petugasCell.innerText || petugasCell.innerText.trim() === '')) {
                            petugasCell.innerText = resp.printed_by || petugasCetak || '-';
                        }
                    }
                });

                if (checkAllRows) {
                    checkAllRows.checked = false;
                }
                updateCheckAllState();
                if (resp.history) {
                    addHistoryRow(resp.history);
                    openPrintWindowFromRows(resp.history.rows_payload || [], {
                        printed_by_name: resp.history.printed_by_name || '',
                        printed_at_label: resp.history.printed_at_label || ''
                    });
                } else {
                    openPrintWindowFromRows(printedRows.map(function(cols) {
                        return {
                            noregister: cols[0] || '',
                            nmpasien: cols[1] || '',
                            nofoto: cols[2] || '',
                            asalpasien: cols[3] || '',
                            daftar: cols[4] || '',
                            reques: cols[5] || '',
                            kd_spesimen: cols[6] || '',
                            nm_spesimen: cols[7] || '',
                            status: cols[8] || '',
                            tgldraft: cols[9] || '',
                            petugas: cols[10] || ''
                        };
                    }), {
                        printed_by_name: petugasCetak || '',
                        printed_at_label: ''
                    });
                }
            }).fail(function(xhr) {
                var err = 'Gagal memperbarui status cetak.';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    err = xhr.responseJSON.message;
                }
                alert(err);
            });
        });

        if (printHistoryBody) {
            printHistoryBody.addEventListener('click', function(e) {
                var btn = e.target.closest('.btn-reprint-history');
                if (!btn) {
                    return;
                }
                var historyId = btn.getAttribute('data-history-id');
                var payload = printHistoryMap[String(historyId)] || [];
                var meta = printHistoryMetaMap[String(historyId)] || {};
                openPrintWindowFromRows(payload, meta);
            });
        }
    });
</script>
@endpush
