<div class="row">
    <div class="col-xs-12">
        <div class="box box-danger mb0">
            <div class="row">
                <div class="col-xs-12">
                    <div class="pull-right">
                        <?php if (!empty($raportyGlobalne)): ?>
                            <?php if (count($raportyGlobalne) == 1): ?>
                                <!-- Single report button -->
                                <button class="btn btn-primary print-report" style="margin: 10px 10px 0 0" data-report-id="<?php echo $raportyGlobalne[0]['id']; ?>">
                                    Drukuj raport &nbsp <i class="fa fa-print"></i>
                                </button>
                            <?php else: ?>
                                <!-- Multiple reports dropdown -->
                                <div class="btn-group" style="margin: 10px 10px 0 0">
                                    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                        Drukuj raport &nbsp <i class="fa fa-print"></i> <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu" style="right: 10px; left: unset !important;">
                                        <?php foreach ($raportyGlobalne as $raport): ?>
                                            <li><a href="#" class="print-report" data-report-id="<?php echo $raport['id']; ?>"><?php echo $raport['nazwa']; ?></a></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="box-body table-responsive table-fixed-height">
                <table id="OdziezRoboczaTable" class="table hover-rows custom-table FullTable" data-start-sort="1"
                       data-start-sort-direction="desc" data-start-height="70vh" data-start-filter="1">
                    <thead>
                    <tr class="text-uppercase">
                        <th style="text-align: left;">Nazwa odzieży</th>
                        <th style="text-align: center;">Ilość</th>
                        <?php if ($bCzyKolumnaWartosc): ?>
                            <th style="text-align: right;">Wartość</th>
                        <?php endif; ?>
                        <th style="text-align: center;">Data wydania</th>
                        <th style="text-align: center;">Data ważności</th>
                        <?php if ($bCzyKolumnaDataZwrotu): ?>
                            <th style="text-align: center;">Data zwrotu</th>
                        <?php endif; ?>
                        <?php if ($bCzyKolumnaDataLikwidacji): ?>
                            <th style="text-align: center;">Data likwidacji</th>
                        <?php endif; ?>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($listaOdziezy as $odziez): ?>
                        <tr data-gid="<?php echo $odziez['bGid']; ?>">
                            <td style="text-align: left;"><?php echo $odziez['bNazwa']; ?></td>
                            <td style="text-align: center;"><?php echo $odziez['bIlosc']; ?></td>
                            <?php if ($bCzyKolumnaWartosc): ?>
                                <td style="text-align: right;"><?php echo $odziez['bWartosc']; ?></td>
                            <?php endif; ?>
                            <td style="text-align: center;">
                                <?php
                                    if (!empty($odziez['bDataWydania'])) {
                                        $date = preg_replace('/T/', " ", $odziez['bDataWydania']);
                                        echo (new \DateTime($date))->format('Y-m-d');
                                    } else {
                                        echo '-';
                                    }
                                ?>
                            </td>
                            <td style="text-align: center;">
                                <?php
                                    if (!empty($odziez['bDataWaznosci'])) {
                                        $date = preg_replace('/T/', " ", $odziez['bDataWaznosci']);
                                        echo (new \DateTime($date))->format('Y-m-d');
                                    } else {
                                        echo '-';
                                    }
                                ?>
                            </td>
                            <?php if ($bCzyKolumnaDataZwrotu): ?>
                                <td style="text-align: center;">
                                    <?php
                                        if (!empty($odziez['bDataZwrotu'])) {
                                            $date = preg_replace('/T/', " ", $odziez['bDataZwrotu']);
                                            echo (new \DateTime($date))->format('Y-m-d');
                                        } else {
                                            echo '-';
                                        }
                                    ?>
                                </td>
                            <?php endif; ?>
                            <?php if ($bCzyKolumnaDataLikwidacji): ?>
                                <td style="text-align: center;">
                                    <?php
                                        if (!empty($odziez['bDataLikwidacji'])) {
                                            $date = preg_replace('/T/', " ", $odziez['bDataLikwidacji']);
                                            echo (new \DateTime($date))->format('Y-m-d');
                                        } else {
                                            echo '-';
                                        }
                                    ?>
                                </td>
                            <?php endif; ?>
                            <td>
                                <?php if (!empty($raporty)): ?>
                                    <?php if (count($raporty) == 1): ?>
                                        <!-- Single report button -->
                                        <button class="btn btn-primary print-report" style="margin: 10px 10px 0 0" data-report-id="<?php echo $raporty[0]['id']; ?>">
                                            <i class="fa fa-print"></i> &nbsp
                                        </button>
                                    <?php else: ?>
                                        <!-- Multiple reports dropdown -->
                                        <div class="btn-group" style="margin: 10px 10px 0 0">
                                            <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <i class="fa fa-print"></i> &nbsp <span class="caret"></span>
                                            </button>
                                            <ul class="dropdown-menu" style="right: 10px; left: unset !important;">
                                                <?php foreach ($raporty as $raport): ?>
                                                    <li><a href="#" class="print-report" data-report-id="<?php echo $raport['id']; ?>"><?php echo $raport['nazwa']; ?></a></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row more-info-container">
    <div class="col-xs-12">
        <div class="box">
            <div class="box-header">
                <h2 class="box-title">Informacje dodatkowe</h2>
            </div>
            <div class="box-body" id="more-info-container">
                <?php if (!empty($raporty)): ?>
                    <h4>Raporty</h4>
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Identyfikator</th>
                                <th>Nazwa</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($raporty as $raport): ?>
                                <tr>
                                    <td><?php echo $raport['id']; ?></td>
                                    <td><?php echo $raport['nazwa']; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <p>Brak dostępnych raportów.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.page-name:first-of-type').html('Odzież Robocza');

        // initiateDataTable();

        // Add click event handler for print report buttons and links
        $('.print-report').on('click', function(e) {
            e.preventDefault();
            const reportId = $(this).data('report-id');

            // Check if this is a row button by looking for closest tr element
            const isRowButton = $(this).closest('tr').length > 0;
            const rowGid = isRowButton ? $(this).closest('tr').data('gid') : null;

            // If row button, print immediately without showing modal
            if (isRowButton) {
                if (reportId) {
                    printReport(reportId, rowGid, null, null);
                }
                return; // do not show modal
            }

            // Build modal if not exists
            if ($('#reportDateModal').length === 0) {
                const modalHtml = `
                <div class="modal fade" id="reportDateModal" tabindex="-1" role="dialog">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">Okres raportu</h4>
                      </div>
                      <div class="modal-body">
                        <div class="form-group">
                          <label for="reportDateFrom">Data od</label>
                          <input type="date" class="form-control" id="reportDateFrom" placeholder="yyyy.MM.dd" inputmode="numeric" pattern="\d{4}\.\d{2}\.\d{2}">
                        </div>
                        <div class="form-group">
                          <label for="reportDateTo">Data do</label>
                          <input type="date" class="form-control" id="reportDateTo" placeholder="yyyy.MM.dd" inputmode="numeric" pattern="\d{4}\.\d{2}\.\d{2}">
                        </div>
                        <div class="text-danger" id="reportDateError" style="display:none"></div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Anuluj</button>
                        <button type="button" class="btn btn-primary" id="confirmReportDates">Drukuj</button>
                      </div>
                    </div>
                  </div>
                </div>`;
                $('body').append(modalHtml);
            }

            // Prefill dates with current month range
            const now = new Date();
            const pad = n => String(n).padStart(2, '0');
            const formatLocalDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
            const firstLocal = new Date(now.getFullYear(), now.getMonth(), 1);
            const lastLocal = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            const firstDay = formatLocalDate(firstLocal);
            const lastDay = formatLocalDate(lastLocal);
            $('#reportDateFrom').val(firstDay);
            $('#reportDateTo').val(lastDay);
            $('#reportDateError').hide().text('');

            $('#reportDateModal').modal('show');

            $('#confirmReportDates').off('click').on('click', () => {
                const dateFrom = $('#reportDateFrom').val();
                const dateTo = $('#reportDateTo').val();
                if (!dateFrom || !dateTo) {
                    $('#reportDateError').text('Wybierz obie daty.').show();
                    return;
                }
                if (dateFrom > dateTo) {
                    $('#reportDateError').text('Data od nie może być późniejsza niż data do.').show();
                    return;
                }

                if (reportId) {
                    if (isRowButton) {
                        printReport(reportId, rowGid, dateFrom, dateTo);
                    } else {
                        printReport(reportId, null, dateFrom, dateTo);
                    }
                }

                $('#reportDateModal').modal('hide');
            });
        });
    })

    function printReport(reportId, gidDokumentu = null, dataOd = null, dataDo = null) {
        // Determine which type of report to generate based on whether gidDokumentu is provided
        const zMetody = gidDokumentu ? "ListaOdziezy.Wiersz" : "ListaOdziezy";

        // Prepare the data to send
        const data = {
            ZMetody: zMetody,
            Identyfikator: reportId,
            GidDokumentu: gidDokumentu,
            DataOd: dataOd,
            DataDo: dataDo,
            numer: '<?php echo $nrewid; ?>',
        };

        console.log('Printing report with ID: ' + reportId + ', ZMetody: ' + zMetody + ', GidDokumentu: ' + gidDokumentu);

        // Send AJAX POST request
        $.ajax({
            url: '<?php echo $this->Url->build(['action' => 'odziezRoboczaDrukujRaport']); ?>',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            xhrFields: {
                responseType: 'blob'
            },
            success: function(response) {
                // Handle the response as a PDF blob
                if (response) {
                    // Create a blob URL from the PDF blob
                    const blob = new Blob([response], { type: 'application/pdf' });
                    const blobUrl = URL.createObjectURL(blob);

                    // Open the PDF in a new window
                    const win = window.open(blobUrl, '_blank');
                }
            },
            error: function(error) {
                console.error('Error printing report:', error);
            }
        });
    }
</script>

<?php echo $this->element('alert_close'); ?>
