<?php
include("db/cn.php");
if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name'])
 && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];

    // Fetch sale history data
    $saleHistoryResult = mysqli_query($connection, "SELECT product_id, order_id, date_time, product_quantity, product_name, product_price, product_total, tax_amount, total_amount, paid_by FROM log_user_sales where outlet_name = '$outlet_name' && login_user = '$userName' && user_role = '$userRole' && outlet_address = '$outlet_address' ");

    // Fetch sale hold data
    $saleHoldResult = mysqli_query($connection, "SELECT product_id, order_id, date_time, product_quantity, product_name, product_price, product_total, tax_amount, total_amount FROM pay_hold where outlet_name = '$outlet_name' && login_user = '$userName' && user_role = '$userRole' && outlet_address = '$outlet_address'");

    // Fetch sale refund data
    $saleRefundResult = mysqli_query($connection, "SELECT * FROM order_detail where outlet_name = '$outlet_name' && sale_by = '$userName' && user_role = '$userRole' && outlet_address = '$outlet_address'");

    // Group sale history data by order ID
    $saleHistoryData = array();
    while ($row = mysqli_fetch_assoc($saleHistoryResult)) {
        $saleHistoryData[] = $row;
    }
    $orderGroups = groupDataByOrderId($saleHistoryData);

    // Group sale hold data by order ID
    $saleHoldData = array();
    while ($row = mysqli_fetch_assoc($saleHoldResult)) {
        $saleHoldData[] = $row;
    }
    $saleHoldGroups = groupDataByOrderId($saleHoldData);

    // Group sale refund data by order ID
    $saleRefundData = array();
    while ($row = mysqli_fetch_assoc($saleRefundResult)) {
        $saleRefundData[] = $row;
    }
    $refundGroups = groupDataByOrderId($saleRefundData);
}
// Close database connection
mysqli_close($connection);

// Function to group data by order ID
function groupDataByOrderId($data) {
    $groups = array();
    foreach ($data as $item) {
        $orderId = $item['order_id'];
        if (!isset($groups[$orderId])) {
            $groups[$orderId] = array();
        }
        $groups[$orderId][] = $item;
    }
    return $groups;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Detail</title>
    <!-- Latest compiled and minified CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/custom_css.css" />
</head>
<body>
    
    <!-- Main content -->
    <div class="main-content">
        <br />
        <div class="container" style="text-transform:capitalize;">
            <div class="row">
                <div class="col-sm-8">
                    <!-- Tab navigation -->
                    <ul class="nav nav-tabs" id="myTabs">
                        <li class="nav-item">
                            <a class="nav-link active" id="saleHistory-tab" data-toggle="tab" href="#saleHistory" role="tab" aria-controls="saleHistory" aria-selected="true">Sale History</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="saleHold-tab" data-toggle="tab" href="#saleHold" role="tab" aria-controls="saleHold" aria-selected="false">Sale Hold</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="refund-tab" data-toggle="tab" href="#refund" role="tab" aria-controls="refund" aria-selected="false">Refund</a>
                        </li>
                    </ul>

                    <!-- Tab content -->
                    <div class="tab-content" id="myTabContent">
                        <!-- Sale History tab content -->
                        <div class="tab-pane fade show active" id="saleHistory" role="tabpanel" aria-labelledby="saleHistory-tab">
                            <table class="table text-center" style="width: 100%; ">
                                <!-- Table header -->
                                <thead style="border-radius:8px;">
                                    <!-- Table header rows -->
                                    <tr style="background:#8A1218; color:#fff;">
                                        <th>Order ID</th>
                                        <th>Product Name</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Action</th>
                                        <!-- Add more table columns here as needed -->
                                    </tr>
                                </thead>
                                <!-- Table body -->
                                <tbody>
                                    <!-- Sale history data rows -->
                                    <?php foreach ($orderGroups as $orderId => $group): ?>
                                        <tr class="sale-history-row" data-order-id="<?php echo $orderId; ?>">
                                            <td style="color:#8A1218; font-weight:700;"><?php echo $orderId; ?></td>
                                            <td><?php echo $group[0]['product_name']; ?></td>
                                            <td><span   style="width:50px;height:20px; padding:7px; border-radius:20px; 
                                            color:#fff; background:#8A1218;">
											<?php echo $group[0]['product_quantity']; ?></span></td>
                                            <td><?php echo "Rs ".$group[0]['product_price']."/-"; ?></td>
                                            <td><button type="button" class="btn btn-dark btn-sm">Refund</button></td>
                                            
                                            <!-- Add more table columns here as needed -->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Sale Hold tab content -->
                        <div class="tab-pane fade" id="saleHold" role="tabpanel" aria-labelledby="saleHold-tab">
                            <table class="table text-center" style="width: 100%;">
                                <!-- Table header -->
                                <thead>
                                    <!-- Table header rows -->
                                    <tr style="background:#8A1218; color:#fff;">
                                        <th>Order ID</th>
                                        <th>Product Name</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <!-- Add more table columns here as needed -->
                                    </tr>
                                </thead>
                                <!-- Table body -->
                                <tbody>
                                    <!-- Sale hold data rows -->
                                    <?php foreach ($saleHoldGroups as $orderId => $group): ?>
                                        <tr class="sale-hold-row" data-order-id="<?php echo $orderId; ?>">
                                            <td><?php echo $orderId; ?></td>
                                            <td><?php echo $group[0]['product_name']; ?></td>
                                            <td><?php echo $group[0]['product_quantity']; ?></td>
                                            <td><?php echo $group[0]['product_price']; ?></td>
                                            <!-- Add more table columns here as needed -->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Refund tab content -->
                        <div class="tab-pane fade" id="refund" role="tabpanel" aria-labelledby="refund-tab">
                            <table class="table text-center" style="width: 100%;">
                                <!-- Table header -->
                                <thead>
                                    <!-- Table header rows -->
                                    <tr style="background:#8A1218; color:#fff;">
                                        <th>Order ID</th>
                                        <th>Product Name</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <!-- Add more table columns here as needed -->
                                    </tr>
                                </thead>
                                <!-- Table body -->
                                <tbody>
                                    <!-- Sale refund data rows -->
                                    <?php foreach ($refundGroups as $orderId => $group): ?>
                                        <tr class="refund-row" data-order-id="<?php echo $orderId; ?>">
                                            <td><?php echo $orderId; ?></td>
                                            <td><?php echo $group[0]['product_name']; ?></td>
                                            <td><?php echo $group[0]['product_quantity']; ?></td>
                                            <td><?php echo $group[0]['product_price']; ?></td>
                                            <!-- Add more table columns here as needed -->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Single view column -->
                <div class="col-sm-4">
                    <div id="singleView" style="display: ;">
                        <!-- Single view content will be displayed here -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Sale History Modal -->
    <div class="modal fade" id="saleHistoryModal" tabindex="-1" aria-labelledby="saleHistoryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saleHistoryModalLabel">Sale History Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="saleHistoryModalBody">
                    <!-- Sale history data will be inserted here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Sale Hold Modal -->
    <div class="modal fade" id="saleHoldModal" tabindex="-1" aria-labelledby="saleHoldModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saleHoldModalLabel">Sale Hold Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="saleHoldModalBody">
                    <!-- Sale hold data will be inserted here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Refund Modal -->
    <div class="modal fade" id="refundModal" tabindex="-1" aria-labelledby="refundModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="refundModalLabel">Refund Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="refundModalBody">
                    <!-- Refund data will be inserted here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Your JavaScript and Bootstrap scripts -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
    $(document).ready(function() {
        // Function to populate Single View
        function populateSingleView(orderId, products, sales) {
            // Calculate subtotal
            var subtotal = 0;
            products.forEach(function(productss) {
                subtotal += parseFloat(productss.product_price);
            });

            // Construct HTML for product details
            var detailsHTML = '<div class="single-view-content">';
            detailsHTML += '<h5>Order ID# <span class="order-id" style="border:1px solid #353535;padding:8px; border-radius:7px;">' + orderId + '</span></h5><br>';
            detailsHTML += '<p class="order-date"><i class="fa fa-calendar-check" style="color:#8A1218;font-size:20px;"></i>&nbsp;' + sales[0].date_time + '</p>';
            detailsHTML += '<table class="table table-stripped text-center">';
            detailsHTML += '<thead><tr><th>Product Name</th><th>Price</th><th>Quantity</th></tr></thead>';
            detailsHTML += '<tbody>';
            products.forEach(function(product) {
                detailsHTML += '<tr style="height:70px;margin-top:20px;text-transform:capitalize;" >';
                detailsHTML += '<td>' + product.product_name + '</td>';
                detailsHTML += '<td>' + product.product_price + '</td>';
                detailsHTML += '<td><span class="bg-dark2" style="width:50px;height:20px;border-radius:20px;font-size:16px;padding:4px;">' + product.product_quantity + '</span></td>';
                detailsHTML += '</tr>';
            });
            detailsHTML += '</tbody></table>';
            detailsHTML += '<div class="order-summary text-center" style="font-weight:500;">';
      detailsHTML += '<div class=" row subtotal"><div class="col-sm-6">Subtotal:</div><div class="col-sm-6" > Rs ' + subtotal.toFixed(2) + '/-</div></div><br>';
   detailsHTML += '<div class=" row tax-amount"><div class="col-sm-6">Tax ~ (10%):</div><div class="col-sm-6">Rs ' + sales[0].tax_amount + '/-</div></div><br>';
            detailsHTML += '<div class=" row total-amount"><div class="col-sm-6">Grand-Total:</div><div class="col-sm-6"> Rs ' + sales[0].total_amount + '/-</div></div>';
            detailsHTML += '</div><br>';
            detailsHTML += '<div class="order-actions">';
            detailsHTML += '<a href="order_view.php?order_id=' + orderId + '" style="border-radius:20px;" class="btn btn-dark print-invoice form-control">Print Invoice</a><br>';
           
            detailsHTML += '</div>';
            detailsHTML += '</div>';

            // Set HTML content to singleView div and show it
            $('#singleView').html(detailsHTML).show();
        }

        // Function to handle click event on table rows
        $(document).on('click', '.sale-history-row, .sale-hold-row, .refund-row', function() {
            var orderId = $(this).data('order-id');
            var products, sales;

            // Determine the tab and get data accordingly
            if ($(this).hasClass('sale-history-row')) {
                products = <?php echo json_encode($orderGroups); ?>[orderId];
                sales = <?php echo json_encode($orderGroups); ?>[orderId];
            } else if ($(this).hasClass('sale-hold-row')) {
                products = <?php echo json_encode($saleHoldGroups); ?>[orderId];
                sales = <?php echo json_encode($saleHoldGroups); ?>[orderId];
            } else if ($(this).hasClass('refund-row')) {
                products = <?php echo json_encode($refundGroups); ?>[orderId];
                sales = <?php echo json_encode($refundGroups); ?>[orderId];
            }

            // Populate single view
            populateSingleView(orderId, products, sales);
        });

        // Function to handle printing when the "Print Invoice" button is clicked
        $(document).on('click', '.print-invoice', function() {
            // Get the content of #singleView div
            var content = $('#singleView').html();
            // Open a new window for printing
            var printWindow = window.open('', '_blank');
            // Write the content to the new window
            printWindow.document.write('<html><head><title>Print Invoice</title><style>@media print {.order-actions {display: none;}}</style></head><body>' + content + '</body></html>');
            // Print the new window
            printWindow.print();
        });

        // Function to handle printing when the "Refund Invoice" button is clicked
        $(document).on('click', '.refund-invoice', function() {
            // Implement refund invoice functionality if necessary
        });
    });
</script>
</body>
</html>
