<div class="container-jcph">
    <div class="card">
        <div class="card-header text-center">
            <h4>Order Form</h4>
        </div>
        <div class="card-body-jcph" id="order-form">
            <% if (orders.length > 0) { %>
                <div class="invoice-details">
                    <div class="hidden-print text-center" style="border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 20px;">
                        <h2 style="margin: 0;">JCPH Plastic Printing</h2>
                        <p style="margin: 0;">Alaminos City, Pangasinan</p><br>
                        <h4 style="margin: 0;">DELIVERY RECEIPT</h4>
                    </div>
                    <h6 class="text-right" style="padding-right: 10px;"><b>Order #</b>: JCPH-XXXX-XXXXXX</h6>
                    <h6 class="text-right" style="padding-right: 10px;"><b>Order Date</b>: <%= date %></h6>
                    <h6 class="text-left" style="padding-left: 10px;"><b>Deliver To:</b> <%= orders[0].Owner %> / <%= client %></h6>
                    <h6 class="text-left" style="padding-left: 10px;"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b> <%= orders[0].Address %></h6>
                    <h6 class="text-left" style="padding-left: 10px;"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b> +<%= orders[0].ContactNo %></h6>
                </div>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th class="text-center">Quantity</th>
                                <th class="text-center">Unit</th>
                                <th class="text-center">Description</th>
                                <th class="text-center">Unit Price</th>
                                <th class="text-center">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <% let totalAmount = 0; %>
                            <% orders.forEach((order, index) => { %>
                                <tr>
                                    <td class="text-center">
                                        <input type="number" class="form-control" name="quantities[]" value="<%= order.Quantity %>" onchange="updateTotal(<%= index %>)">
                                    </td>
                                    <td class="text-center"><%= order.Unit %></td>
                                    <td><%= order.Description %></td>
                                    <td class="text-center">
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text">₱</span>
                                            </div>
                                            <input type="number" step="0.01" class="form-control" name="prices[]" value="<%= parseFloat(order.Price).toFixed(2) %>" onchange="updateTotal(<%= index %>)">
                                        </div>
                                    </td>
                                    <td class="text-right">
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text">₱</span>
                                            </div>
                                            <input type="number" step="0.01" class="form-control" name="totals[]" id="total-<%= index %>" value="<%= parseFloat(order.Total).toFixed(2) %>" readonly>
                                        </div>
                                    </td>
                                </tr>
                                <% totalAmount += parseFloat(order.Total); %>
                            <% }) %>
                        </tbody>
                        <tfoot>
                            <tr class="spacer-row">
                                <td colspan="5" style="height: 10px;"></td> <!-- Spacer row -->
                            </tr>
                            <tr>
                                <td colspan="4" class="text-right"><strong>Total Amount:</strong></td>
                                <td class="text-right"><strong id="total-amount">₱<%= totalAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") %></strong></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            <% } else { %>
                <p class="text-center">No orders found for the selected date and client.</p>
            <% } %>
            <!-- Footer for Delivery Receipt -->
            <div class="hidden-print text-center" style="border-top: 2px solid #000; padding-top: 10px; margin-top: 20px;">
                <p style="margin: 0;">I hereby confirm that all goods have been delivered without any issues and defects.</p>
                <table style="width: 100%; margin-top: 10px;">
                    <tr>
                        <td style="width: 50%; text-align: left;"></td>
                        <td style="width: 50%; text-align: right;">Received by: __________________________________</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td style="text-align: right;">Signature over Printed Name&nbsp;&nbsp;&nbsp;</td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="card-footer text-center">
            <form id="confirm-orders-form" action="/payment/update-orders" method="POST" class="d-flex justify-content-center">
                <input type="hidden" name="orderDate" value="<%= date %>">
                <% orders.forEach((order, index) => { %>
                    <input type="hidden" name="orderIDs[]" value="<%= order.OrderID %>">
                    <input type="hidden" name="quantities[]" id="hidden-quantity-<%= index %>" value="<%= order.Quantity %>">
                    <input type="hidden" name="prices[]" id="hidden-price-<%= index %>" value="<%= order.Price %>">
                <% }) %>
                <button type="submit" class="btn btn-primary mr-2" title="CONFIRM"><i class="fas fa-check"></i></button>
                <button type="button" class="btn btn-secondary" onclick="window.location.href='/payment/pending-orders'" title="CANCEL"><i class="fas fa-times"></i></button>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    // Function to update the total amount
    function updateTotal(index) {
        const quantity = parseFloat(document.getElementsByName('quantities[]')[index].value);
        const price = parseFloat(document.getElementsByName('prices[]')[index].value);
        const total = quantity * price;
        document.getElementById(`total-${index}`).value = total.toFixed(2);

        // Update the total amount
        let totalAmount = 0;
        document.querySelectorAll('input[name="totals[]"]').forEach(input => {
            totalAmount += parseFloat(input.value);
        });
        document.getElementById('total-amount').innerText = `₱${totalAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    }

    // Function to update the hidden input fields with the edited values
    function updateHiddenFields() {
        try {
            document.querySelectorAll('input[name="quantities[]"]').forEach((input, index) => {
                const hiddenQuantity = document.getElementById(`hidden-quantity-${index}`);
                if (hiddenQuantity) {
                    hiddenQuantity.value = input.value;
                }
            });
            document.querySelectorAll('input[name="prices[]"]').forEach((input, index) => {
                const hiddenPrice = document.getElementById(`hidden-price-${index}`);
                if (hiddenPrice) {
                    hiddenPrice.value = input.value;
                }
            });
            console.log('Hidden fields updated');
        } catch (error) {
            console.error('Error updating hidden fields:', error);
        }
    }

    // Attach the updateHiddenFields function to the form submit event
    document.getElementById('confirm-orders-form').addEventListener('submit', function(event) {
        updateHiddenFields();
        console.log('Form submitted with updated hidden fields');
    });
</script>