<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml"
      xmlns:ctp="http://www.w3.org/1999/xhtml">
<head th:replace="_fragments :: head('PO Report')"></head>
<body>
<div class="container-fluid">
    <header class="row page-header" th:replace="_fragments :: page-header"></header>
    <main class="row page-main">
        <aside class="col-sm-2" th:replace="/reporting/po-report-sidebar :: sidebar"></aside>
        <div class="col-lg-10 col-sm-10" style="overflow-x: auto;">
            <h3>All PO's</h3>
            <div class="table-responsive"> <!-- Bootstrap responsive table wrapper -->
                <table th:if="${ #lists != null && #lists.size(allPOs) != 0 }"
                       class="table table-striped font-sm"  data-order="[[ 0, &quot;desc&quot; ]]" style="min-width: 1500px;">
                <thead>
                <tr>
                    <th>PO Number</th>
                    <th>PO Article</th>
                    <th>PO Quantity</th>
                    <th>Req+ Excess</th>
                    <th>Cut.</th>
                    <th>Cut Bal.</th>
                    <th>Cut Recv.</th>
                    <th>Cut oki</th>
                    <th>Cut Rej.</th>
                    <th>Stit. In</th>
                    <th>Stit. Out</th>
                    <th>Stit. Wips</th>
                    <th>finish In</th>
                    <th>finish Rej.</th>
                    <th>finish QA APP.</th>
                    <th>Rej. Store Rcvd</th>
                    <th>Rej. Store Waiting</th>
                    <th>Packed In</th>
                    <th>Packed Out</th>
                    <th>Packed Stock</th>
                    <th>Shipped Scan</th>
                    <th>Shipped Net</th>
                    <th></th>
                    <th></th>
                    <th>PO Status</th>
                    <th>Generate PDF</th>
                </tr>
                </thead>
                <tbody>
                <!-- Dummy data for testing purposes -->
                <tr th:each="poDetail : ${allPOs}">
                    <td><a class="text-reset" th:href="@{'/po-status/po-report-view/' + ${poDetail.poId}}"
                           th:text="${poDetail.poNumber}"></a></td>
                    <td th:text="${poDetail.articleTitle}"></td>
                    <td th:text="${poDetail.poQuantity}"></td>
                    <td th:text="${poDetail.poRequiredQuantity}"></td>
                    <td th:text="${poDetail.actualCutting}"></td>
                    <td th:text="${poDetail.balanceToCutting}"></td>
                    <td th:text="${poDetail.cuttingReceived}"></td>
                    <td th:text="${poDetail.cuttingOki}"></td>
                    <td th:text="${poDetail.cuttingReject}"></td>
                    <td th:text="${poDetail.stitchingIn}"></td>
                    <td th:text="${poDetail.stitchingOut}"></td>
                    <td th:text="${poDetail.stitchingWips}"></td>
                    <td th:text="${poDetail.finishIn}"></td>
                    <td th:text="${poDetail.finishRej}"></td>
                    <td th:text="${poDetail.finishQaApproved}"></td>
                    <td th:text="${poDetail.storeReceived}"></td>
                    <td th:text="${poDetail.storeWaiting}"></td>
                    <td th:text="${poDetail.packagingIn}"></td>
                    <td th:text="${poDetail.packagingOut}"></td>
                    <td th:text="${poDetail.packagingStock}"></td>
                    <td th:text="${poDetail.shippedScan}"></td>
                    <td th:text="${poDetail.shippedNet}"></td>

                    <td data-show-dropdown-transactions
                        th:data-po-id="${poDetail.poId}"
                        title="Store-Items">
                        <span data-dropdown-icon-transactions class="bi bi-caret-right-fill"></span>
                    </td>
                    <td data-show-dropdown-summary
                        th:data-po-id="${poDetail.poId}" title="Summary">
                        <span data-dropdown-icon-summary class="bi bi-caret-right"></span>
                    </td>
                    <td>
                        <span class="badge font-sm badge-danger" th:if="*{poDetail.poStatus}" th:text="'CLOSE'"></span>
                        <span class="badge font-sm badge-ACTIVE" th:if="*{!poDetail.poStatus}" th:text="'OPEN'"></span>
                    </td>
                    <td>
                        <form th:action="@{/po-status/generate-po-pdf}" method="get" target="_blank"
                              th:id="'form-' + ${poDetail.poId}">
                            <!-- Hidden inputs for all fields -->
                            <input type="hidden" name="poId" th:value="${poDetail.poId}"/>
                            <input type="hidden" name="poNumber" th:value="${poDetail.poNumber}"/>
                            <input type="hidden" name="articleTitle" th:value="${poDetail.articleTitle}"/>
                            <input type="hidden" name="poQuantity" th:value="${poDetail.poQuantity}"/>
                            <input type="hidden" name="poRequiredQuantity" th:value="${poDetail.poRequiredQuantity}"/>
                            <input type="hidden" name="actualCutting" th:value="${poDetail.actualCutting}"/>
                            <input type="hidden" name="balanceToCutting" th:value="${poDetail.balanceToCutting}"/>
                            <input type="hidden" name="cuttingReceived" th:value="${poDetail.cuttingReceived}"/>
                            <input type="hidden" name="cuttingOki" th:value="${poDetail.cuttingOki}"/>
                            <input type="hidden" name="cuttingReject" th:value="${poDetail.cuttingReject}"/>
                            <input type="hidden" name="stitchingIn" th:value="${poDetail.stitchingIn}"/>
                            <input type="hidden" name="stitchingOut" th:value="${poDetail.stitchingOut}"/>
                            <input type="hidden" name="stitchingWips" th:value="${poDetail.stitchingWips}"/>
                            <input type="hidden" name="finishIn" th:value="${poDetail.finishIn}"/>
                            <input type="hidden" name="finishRej" th:value="${poDetail.finishRej}"/>
                            <input type="hidden" name="finishQaApproved" th:value="${poDetail.finishQaApproved}"/>
                            <input type="hidden" name="storeReceived" th:value="${poDetail.storeReceived}"/>
                            <input type="hidden" name="storeWaiting" th:value="${poDetail.storeWaiting}"/>
                            <input type="hidden" name="packagingIn" th:value="${poDetail.packagingIn}"/>
                            <input type="hidden" name="packagingOut" th:value="${poDetail.packagingOut}"/>
                            <input type="hidden" name="packagingStock" th:value="${poDetail.packagingStock}"/>
                            <input type="hidden" name="shippedScan" th:value="${poDetail.shippedScan}"/>
                            <input type="hidden" name="shippedNet" th:value="${poDetail.shippedNet}"/>
                            <input type="hidden" name="poStatus" th:value="${poDetail.poStatus}"/>
                            <a href="javascript:void(0);"
                               th:onclick="'showPdfOptions(' + ${poDetail.poId} + ')'"
                               class="btn btn-sm btn-secondary"
                               title="Generate PDF">
                                <i class="bi bi-filetype-pdf"></i>
                            </a>
                        </form>
                    </td>
                </tr>
                </tbody>
            </table>
            <h4 th:if="${#lists.size(allPOs) ==  0 }">No PO found.</h4>
        </div>
        </div>
        <div class="modal fade" id="pdfOptionsModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Select PDF Options</h5>
                    </div>
                    <div class="modal-body">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="includeItemsDetail" name="includeItemsDetail" value="true" checked>
                            <label class="form-check-label" for="includeItemsDetail">
                                Include Items Details
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="includeStoreDetails" name="includeStoreDetails" value="true" checked>
                            <label class="form-check-label" for="includeStoreDetails">
                                Include Store Details
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="submitPdfForm()">Generate PDF</button>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
<div th:replace="_fragments :: page-footer-scripts"></div>
<script>

    const params = new URLSearchParams(window.location.search);

    // Extract individual parameters
    const size = params.get("size");
    const color = params.get("color");


    // PDF Generation Functions
    let currentPoIdForPdf = null;

    function showPdfOptions(poId) {
        currentPoIdForPdf = poId;
        $('#pdfOptionsModal').modal('show');
    }

    function submitPdfForm() {
        if (!currentPoIdForPdf) return;

        const form = document.getElementById('form-' + currentPoIdForPdf);

        // Remove existing options if they exist
        const existingJobCard = form.querySelector('input[name="includeJobCard"]');
        const existingStoreDetails = form.querySelector('input[name="includeStoreDetails"]');
        const existingItemsDetail = form.querySelector('input[name="includeItemsDetail"]');

        if (existingJobCard) form.removeChild(existingJobCard);
        if (existingStoreDetails) form.removeChild(existingStoreDetails);
        if (existingItemsDetail) form.removeChild(existingItemsDetail);

        // Add store detail params
        const includeStoreDetails = document.createElement('input');
        includeStoreDetails.type = 'hidden';
        includeStoreDetails.name = 'includeStoreDetails';
        includeStoreDetails.value = document.getElementById('includeStoreDetails').checked;
        form.appendChild(includeStoreDetails);

        // Add item color params
        const itemColors = document.createElement('input');
        itemColors.type = 'hidden';
        itemColors.name = 'color';
        itemColors.value = color
        form.appendChild(itemColors);

        // Add item size params
        const itemSize = document.createElement('input');
        itemSize.type = 'hidden';
        itemSize.name = 'size';
        itemSize.value = size;
        form.appendChild(itemSize);

        // Add add items details checkbox params
        const includeItemsDetails = document.createElement('input');
        includeItemsDetails.type = 'hidden';
        includeItemsDetails.name = 'includeItemsDetail';
        includeItemsDetails.value = document.getElementById('includeItemsDetail').checked;
        form.appendChild(includeItemsDetails);

        form.submit();
        $('#pdfOptionsModal').modal('hide');
    }

    // DataTable and Dropdown Initialization
    $(document).ready(function() {
        const $body = $('body');

        // Initialize DataTables for each individual table
        $('table[data-account-table]').each(function () {
            $(this).DataTable({
                paging: false,
                pageLength: 10,
                searching: false,
                lengthChange: false,
                processing: false,
                dom: `
                   <'row'<'col-sm-3'B><'col-sm-4'f>>
                   <'row'<'col-sm-6't>>
                   <'row'<'col-sm-3'i><'col-sm-4'p>>`,
                buttons: [{
                    extend: 'excel',
                    text: '',
                    className: 'bi bi-file-earmark-spreadsheet btn-sm d-none'
                }]
            });
        });

        // Dropdown transactions toggle
        $body.on('click', '[data-show-dropdown-transactions]', function (e) {
            e.preventDefault();

            const $this = $(this);
            const $tr = $this.closest('tr');
            const $table = $this.closest('table');
            const dataTable = $table.DataTable();
            const $row = dataTable.row($tr);
            const $spanDropdown = $this.find('[data-dropdown-icon-transactions]');
            const poId = $this.data('po-id');
            $spanDropdown.toggleClass('bi-caret-right-fill bi-caret-down-fill');

            if ($row.child.isShown()) {
                $row.child.hide();
            } else {
                $row.child(`<span class="spinner-border text-center spinner-border-md" role="status"></span>`).show();
                $.ajax({
                    url: `/ctp/purchase-order/store-items/${poId}`,
                    success: function(data) {
                        if (data.includes('page-login') ||
                            data.includes('login__form') ||
                            data.includes('Sign in')) {
                            // Redirect to login page
                            window.location.href = '/ctp/login?logout';
                        } else {
                            $row.child(data).show();
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            window.location.href = '/ctp/login?logout';
                        } else {
                            $row.child('<span class="text-danger">Error loading data</span>').show();
                        }
                    }
                });
            }
        });


        $body.on( 'click', '[data-show-dropdown-summary]', function( e ) {
            e.preventDefault();
            const $this = $(this);
            const $tr = $this.closest('tr');
            const $table = $this.closest('table');
            const dataTable = $table.DataTable();
            const $row = dataTable.row($tr);
            const $spanDropdown = $tr.find( '[data-dropdown-icon-summary]' );
            const poId = $this.data('po-id');
            $spanDropdown.toggleClass( 'bi-caret-right bi-caret-down' );
            if( $row.child.isShown() ){
                $row.child.hide();
            }
            else {
                $row.child(`<span class="spinner-border text-center spinner-border-md" role="status"></span>`).show();
                $.ajax({
                    url: `/ctp/po-status/po-items?poId=${poId}&size=${size}&color=${color}`,
                    success: function( data ){
                        if (data.includes('page-login') ||
                            data.includes('login__form') ||
                            data.includes('Sign in')) {
                            // Redirect to login page
                            window.location.href = '/ctp/login?logout';
                        } else {
                            $row.child(data).show();
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            window.location.href = '/ctp/login?logout';
                        } else {
                            $row.child('<span class="text-danger">Error loading data</span>').show();
                        }
                    }
                });
            }
        });
    });
</script>

</body>
</html>