<?php
include("../db/cn.php");
include("common/tx.php");
ob_start();

// Handle deletion request
if (isset($_GET['delete_order_id'])) {
    $deleteOrderId = $_GET['delete_order_id'];
    $deleteQuery = "DELETE FROM log_user_sales WHERE order_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);
    // Optional: redirect after delete to avoid resubmission
   echo "<script type='text/javascript'>window.location.href = 'order_detail_v.php';</script>";
    exit();
}

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 * FROM log_user_sales where status = ''");

    // Fetch sale hold data
    $saleHoldResult = mysqli_query($connection, "SELECT * FROM pay_hold where outlet_name = '$outlet_name' && login_user = '$userName' && user_role = '$userRole' && outlet_address = '$outlet_address' ORDER BY date_time DESC");

    // Fetch sale refund data
    $saleRefundResult = mysqli_query($connection, "SELECT * FROM log_user_sales where status = 'refund' ");

    // 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;
}
ob_end_flush();
?>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $tx; ?></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 href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/custom_css.css" />

   
</head>

<style>
body {
    font-family: 'Quicksand', sans-serif;
    
}
 #table-container-single {
    max-height: 660px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}

@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
}
    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #3C2F23);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }

    .sidebar.hide {
        transform: translateX(-100px);
        /* Move sidebar out of the viewport when it is hidden */
    }

    .sidebar .nav-item {
        padding: 10px 0;
        text-align: center;
        position: relative;
        font-size: 12px;
    }

    .sidebar .nav-link {
        color: #fff;
        position: relative;
        /* Ensure icon and text are positioned relative to the nav link */
        z-index: 2;
        /* Ensure the text and icon are above the hover background */
    }

    .sidebar .nav-link i {
        margin-bottom: 5px;
        /* Adjust the margin of the icon */
    }

    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
        background-color: #fff;
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        /* Ensure the hover background is below the text and icon */
    }

    .sidebar .nav-item:hover .nav-link {
        color: #503F2E;
    }

    /* Custom styles for divider */
    .sidebar .nav-item:after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #fff;
        transition: height 0.3s ease-in-out;
        /* Transition effect for smooth animation */
    }

    /* Custom styles for header */
    .header {
        background: linear-gradient(90deg, #3C2F23, #060606);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }

    .header .navbar-toggler {
        color: #fff;
    }

    .header .navbar-toggler-icon {
        color: #fff;
        /* Set the color of the toggle button to white */
    }

    .header .navbar-toggler.white {
        color: #fff !important;
        /* Ensure the toggle button is white */
    }

    .header .navbar-brand {
        color: #fff;
        /* Set navbar brand text color to white */
    }

    .header .nav-item .nav-link {
        color: #fff;
        /* Set nav link text color to white */
    }

.main-content {
    margin-top: 50px; /* Height of fixed header */
    margin-left: 120px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;
        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

    .btn-dark {
        background: #0A4657;
        color: #fff;
        border: 1px solid #0A4657;
    }

    .btn-dark:hover {
        background: #fff;
        color: #0A4657;
        border: 1px solid #0A4657;
    }

    .bg-dark2 {
        background: #0A4657;
        color: #fff;
    }

    .modal-content {
        animation: modal-animation 0.5s;
    }

    @keyframes modal-animation {
        from {
            opacity: 0;
            transform: scale(0.8);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }	
      .bg {
            background: linear-gradient(270deg, #060606, #0A4657);
        }
</style>
<body>

    <!-- Main content -->
<div class="container-fluid">
    <div class="row bg">
        <div class="col-sm-3">
            
                <img src="../img/logo231.png" style="margin-top:5px;" width="70" height="70" alt="Logo">
            </a>
        </div>
        <div class="col-sm-6">
            <h3 class="mb-4 text-center" style="color:#fff; font-weight:700; text-transform:uppercase; line-height:60px;font-size:33px;">
               <?php echo $tx; ?>

            </h3>
        </div>
        <div class="col-sm-3">
            <a href="addproduct.php">
            <button type="button" style="margin-top:20px;float:right;" class="btn btn-light">Back</button>
            </a>
        </div>
    </div>
</div> 
        <br />
        <div class="container-fluid" style="text-transform:capitalize;">
            <div class="row">
                <div class="col-sm-6">
                    <!-- Tab navigation -->
                    <ul class="nav nav-tabs" id="myTabs">
                        <li class="nav-item">
                            <a class="nav-link active text-dark" 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 text-dark" 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 text-dark" 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">
                           <div style="max-height: 900px; overflow-y: auto;">
                           <br>
                           <!-- Filter controls -->
                            <div class="form-group row">
                                <label for="saleOrderID" class="col-sm-2 col-form-label">Search by :</label>
                                <div class="col-sm-8">
                                    <input type="text" class="form-control" id="saleOrderID" placeholder="">
                                </div>
                            </div>
                            <br>
                            
                            <table class="table table-sm text-center" style="width: 100%; font-size:14px; ">
                                <!-- Table header -->
                                <thead style="border-radius:8px;">
                                    <!-- Table header rows -->
                                    <tr style="background:#212529; color:#fff; font-weight:700;">
                                         <th>Date</th>
                                         <th>name</th>
                                        <th>Order </th>
                                        <th>Amount(Rs)</th>
                                        <th>Status</th>
                                        <th>Print</th>
                                        <th>Edit</th>
                                        <th>Delete</th>
                                        <th>Add Item</th>
                                        <th>Refund</th> 
                                       
                                        <!-- Add more table columns here as needed -->
                                    </tr>
                                </thead>
                                <!-- Table body -->
                                <tbody id="saleHistoryTableBody">
                                <?php foreach (array_reverse($orderGroups) as $orderId => $group): ?>
                                    <?php  
                                        $subtotal = 0;
                                        foreach ($group as $orderRow) {
                                            $gross = $orderRow['product_quantity'] * $orderRow['product_price'];
                                            $discountAmount = ($gross * $orderRow['discount']) / 100;
                                            $productTotal = $gross - $discountAmount;   // Final total after discount
                                            $subtotal += $productTotal;
                                        }
                                    ?>
                                    <tr class="sale-history-row" data-order-id="<?php echo $orderId; ?>">
                                        <td style="font-weight:700;"> <?php echo $group[0]['date_time']; ?> </td>
                                        <td style="font-weight:700;"> <?php echo $group[0]['customer_name']; ?> </td>
                                        <td style="color:#8A1218; font-weight:700; font-size:11px;"> <?php echo $orderId; ?> </td>
                                
                                        <!-- Show final subtotal (after discount) -->
                                        <td style="font-weight:700;"> <?php echo number_format($subtotal, 2); ?> </td>
                                
                                        <td style="font-weight:700;"> <?php echo $group[0]['paid_by']; ?> </td>
                                        <td>
                                            <a href="print_invoice_o.php?order_id=<?php echo $orderId; ?>" target="_blank" style="border-radius:20px;" class="btn btn-dark btn-sm print-invoice form-control">
                                                <i class="fas fa-print"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <a href="edit_order_2.php?order_id=<?php echo $orderId; ?>" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                        </td>
                                        <td>
                                            <a href="order_detail_v.php?delete_order_id=<?php echo $orderId; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this order?');">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <a href="add_item.php?order_id=<?php echo $orderId; ?>" class="btn btn-sm btn-primary"><i class="fas fa-plus"></i></a>
                                        </td>
                                        <td>
                                            <a href="refund_order.php?order_id=<?php echo urlencode($orderId); ?>"
                                               class="btn btn-warning btn-sm"
                                               onclick="return confirm('Are you sure you want to refund this order?');">
                                               Refund
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                            </div>
                        </div>

                        <!-- Sale Hold tab content -->
                        <div class="tab-pane fade" id="saleHold" role="tabpanel" aria-labelledby="saleHold-tab">
                        <div style="max-height: 900px; overflow-y: auto;"><br>
                         <div class="form-group row">
                            <label for="holdOrderID" class="col-sm-2 col-form-label">Search by:</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" id="holdOrderID" placeholder="">
                            </div>
                        </div><br>
                          <table class="table table-sm text-center" style="width: 100%; font-size:14px; ">
                                <!-- Table header -->
                                <thead style="border-radius:8px;">
                                    <!-- Table header rows -->
                                    <tr style="background:#212529; color:#fff;">
                                         <th>Date</th>
                                         <th>name</th>
                                         <th>Cell</th>
                                        <th>Order </th>
                                        <th>Amount(Rs)</th>
                                        <th>Action</th>
                                        
                                        <!--<th>Print</th>-->
                                        <!-- Add more table columns here as needed 
                                    </tr>
                                </thead>
                                <!-- Table body--> 
                                <tbody id="saleHoldTableBody" >
                                    <!-- Sale history data rows -->
                                    <?php foreach (array_reverse($saleHoldGroups) as $orderId => $group): ?>
                                        <tr class="sale-hold-row" data-order-id="<?php echo $orderId; ?>" >
                                        <td><?php echo $group[0]['date_time']; ?></td>
                                        <td><?php echo $group[0]['customer_name']; ?></td>
                                        <td><?php echo $group[0]['customer_phone']; ?></td>
                                            <td style="color:#8A1218; font-weight:700; font-size:11px;"><?php echo $orderId; ?></td>
                                          <td>Rs <?php echo $group[0]['discount_amount']; ?></td>
                                           
										
                                           <td><a href="hold_p.php?order_id=<?php echo $orderId; ?>"><button type="button" class="btn btn-dark btn-rounded btn-sm"><i class="fas fa-box fa-1x"></i></button></td></a>
                                           
                                            <!--<td> <a href="print_invoice.php?order_id=<?php echo $orderId; ?>" target="_blank" style="border-radius:20px;" class="btn btn-dark  btn-sm print-invoice form-control"><i class="fas fa-print"></i></a></td>-->
                                            
                                            <!-- Add more table columns here as needed -->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            </div>
                        </div>

                        <!-- Refund tab content -->
                        <div class="tab-pane fade" id="refund" role="tabpanel" aria-labelledby="refund-tab">
                        <div style="max-height: 900px; overflow-y: auto;">
                        <br>
                                              <!-- Filter controls -->
                                               <div class="form-group row ">
                                <label for="refundOrderID" class="col-sm-2 col-form-label">Search By:</label>
                                <div class="col-sm-8">
                                    <input type="text" class="form-control" id="refundOrderID" placeholder="">
                                </div>
                            </div><br>
                                <table class="table text-center table-sm" style="width: 100%;font-size:14px;">
                                <!-- Table header -->
                                <thead>
                                    <!-- Table header rows -->
                                    <tr style="background:#212529; color:#fff;">
                                        <th>Date</th>
                                        <th>Name</th>
                                        <th>Order </th>
                                        <th>Amount(Rs)</th>
                                        <th>Status</th>
                                        <th>Print</th>
                                        
                                        <!-- Add more table columns here as needed -->
                                    </tr>
                                </thead>
                                <!-- Table body -->
                                <tbody id="refundTableBody" >
                                    <!-- Sale refund data rows -->
                                    <?php foreach (array_reverse($refundGroups) as $orderId => $group): ?>
                                        <tr class="refund-row" data-order-id="<?php echo $orderId; ?>">
                                             <td><?php echo $group[0]['date_time']; ?></td>
                                             <td><?php echo $group[0]['customer_name']; ?></td>
                                             <td style="color:#8A1218; font-weight:700; font-size:12px;"><?php  echo $group[0]['r_order_id']; ?></td>
                                             <td style="font-weight:700;"> <?php echo $group[0]['discount_amount']; ?> </td>
                                             <td style="font-weight:700;"><?php echo $group[0]['paid_by']; ?></td>
                                             <td> <a href="print_invoice_r.php?order_id=<?php echo $group[0]['r_order_id']; ?>" target="_blank" style="border-radius:20px;" class="btn btn-dark  btn-sm print-invoice form-control"><i class="fas fa-print"></i></a></td>
                                             
                                            
                                            <!--<td><?php echo $group[0]['product_name']; ?></td>
                                            <td><?php echo $group[0]['product_quantity']; ?></td>-->
                                            
                                            <!-- Add more table columns here as needed -->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Single view column -->
                <div class="col-sm-6">
                <br>
                    <div id="singleView" style="display: ;">
                        <!-- Single view content will be displayed here -->
                    </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.addEventListener("DOMContentLoaded", function () {
    // Reference to the table body
    const tableBody = document.getElementById("saleHistoryTableBody");
    
    // Convert HTMLCollection of rows to an array
    let rowsArray = Array.from(tableBody.rows);
    
    // Sort rows based on the Date column (first <td> element)
    rowsArray.sort((rowA, rowB) => {
        // Get the date text from the first cell of each row
        const dateA = new Date(rowA.cells[0].innerText);
        const dateB = new Date(rowB.cells[0].innerText);

        // Descending order
        return dateB - dateA;
    });

    // Clear the table body and append rows in sorted order
    tableBody.innerHTML = "";
    rowsArray.forEach(row => tableBody.appendChild(row));
});
    
$(document).ready(function() {
    // Function to filter table by any text
    function filterTable(tableBody, searchText) {
        $(tableBody + ' tr').each(function() {
            var row = $(this).text().toLowerCase();
            if (row.indexOf(searchText.toLowerCase()) === -1) {
                $(this).hide();
            } else {
                $(this).show();
            }
        });
    }

    // Event listener for sale history search
    $('#saleOrderID').keyup(function() {
        var searchText = $(this).val();
        filterTable('#saleHistoryTableBody', searchText);
    });

    // Event listener for sale hold search
    $('#holdOrderID').keyup(function() {
        var searchText = $(this).val();
        filterTable('#saleHoldTableBody', searchText);
    });

    // Event listener for refund search
    $('#refundOrderID').keyup(function() {
        var searchText = $(this).val();
        filterTable('#refundTableBody', searchText);
    });
});
	
	
 $(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 font-weight-bold" style="font-weight:700;">';
detailsHTML += '<h5 style="font-size:15px;"> <span class="order-id" style="border:1px solid #353535;padding:8px; border-radius:7px; font-size:16px;background:#0A4657;color:#fff;font-weight:700;">' + orderId + '</span></h5><br>';
detailsHTML += '<p class="order-date"><i class="fa fa-calendar-check" style="color:#0A4657;font-size:20px;"></i>&nbsp;&nbsp;' + sales[0].date_time + '</p>';
detailsHTML += '<p class="order-date"><i class="fa fa-user" style="color:#0A4657;font-size:20px;"></i>&nbsp;&nbsp;' + sales[0].customer_name + '</p>';
detailsHTML += '<p class="order-date"><i class="fa fa-phone-alt" style="color:#0A4657;font-size:20px;"></i>&nbsp;&nbsp;' + sales[0].customer_phone + '</p>';
detailsHTML += '<p class="order-date"><i class="fa fa-money-bill" style="color:#0A4657;font-size:20px;"></i>&nbsp;' + sales[0].paid_by + '</p>';
detailsHTML += '<div id="table-container-single"><table class="table table-stripped text-center table-sm">';
detailsHTML += '<thead><tr><th>Product</th><th>Category</th><th>Quantity</th><th>Price(Rs)</th><th>Sale Cost(Rs)</th><th>Subtotal(Rs)</th><th>Disc(RS)</th><th>Total(Rs)</th></tr></thead>';
detailsHTML += '<tbody>';

var subtotal = 0;

products.forEach(function(product) {
    var qty   = parseFloat(product.product_quantity) || 0;
    var price = parseFloat(product.product_price) || 0;
    var saleCost = parseFloat(product.sale_cost) || 0;

    var perUnitSaleCost = (qty > 0) ? (saleCost / qty) : 0;
    var updatedSaleCost = perUnitSaleCost * qty;

    var gross = qty * price;
    var discountAmount = (gross * product.discount) / 100;

    var productSubtotal = gross - discountAmount;
    subtotal += productSubtotal;

    detailsHTML += '<tr style="height:35px;margin-top:20px;text-transform:capitalize;">';
    detailsHTML += '<td style="font-size:14px; font-weight:700;">' + product.product_name + '</td>';
    detailsHTML += '<td style="font-size:14px; font-weight:700;">' + product.category + '</td>';
    detailsHTML += '<td><span class="bg-dark2" style="width:50px;height:20px;border-radius:20px;font-size:12px;padding:4px;">' + qty + '</span></td>';
    detailsHTML += '<td style="font-weight:700;">' + price.toFixed(2) + '</td>';
    detailsHTML += '<td style="font-weight:700;">' + updatedSaleCost.toFixed(2) + '</td>';
    detailsHTML += '<td style="font-weight:700;">' + gross.toFixed(2) + '</td>';                
    detailsHTML += '<td style="font-weight:700;">' + product.disc_amount + '</td>';               
    detailsHTML += '<td style="font-weight:700;">' + productSubtotal.toFixed(2) + '</td>'; 
    detailsHTML += '</tr>';
});

detailsHTML += '</tbody></table></div>';

detailsHTML += '<div class="order-summary text-center font-weight-bold" style="font-weight:700;">';

// Convert numeric values from sales[0]
var discount = parseFloat(sales[0].discounted) || 0;  
var preAmount = parseFloat(sales[0].pre_amount) || 0;

// 1️⃣ Subtotal already calculated above
var subTotal = subtotal;

// 2️⃣ Total = Subtotal - Discount
var total = subTotal - discount;

// 3️⃣ Grand Total = Total + Pre Amount
var grandTotal = total + preAmount;

// ---- Render Output ----
detailsHTML += '<div class="row total-amount"><div class="col-sm-6">SubTotal:</div><div class="col-sm-6">Rs ' + subTotal.toFixed(0) + '</div></div>';

detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Discount:</div><div class="col-sm-6">Rs ' + discount.toFixed(0) + '</div></div>';

detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Total:</div><div class="col-sm-6">Rs ' + total.toFixed(0) + '</div></div>';

detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Pre Amount:</div><div class="col-sm-6">Rs ' + preAmount.toFixed(0) + '</div></div>';

detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Grand Total:</div><div class="col-sm-6">Rs ' + grandTotal.toFixed(0) + '</div></div>';

// detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Amount Recieved:</div><div class="col-sm-6"> Rs ' + sales[0].cash_amount + '</div></div>';
// detailsHTML += '<div class="row total-amount"><div class="col-sm-6">Amount Remainig:</div><div class="col-sm-6"> Rs ' + sales[0].change_amount + '</div></div>';

detailsHTML += '</div>';

detailsHTML += '<div class="order-actions">';
detailsHTML += '<a href="" style="border-radius:20px;" class=""></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);
        });
$(document).on('click', '.print-invoice', function() {
    // Get the content of #singleView div
    var content = $('#singleView').clone(); // Clone the content to keep the original intact

    // Remove any buttons or interactive elements
    content.find('.order-actions').remove();
    content.find('.refund-invoice').remove();

    // Get the invoice items content
    var itemsContent = content.find('.invoice-items').html();

    // Create data object
    var data = [];
    content.find('.invoice-items tbody tr').each(function() {
        var item = {
            product_name: $(this).find('td:eq(0)').text(),
            product_price: $(this).find('td:eq(1)').text(),
            product_quantity: $(this).find('td:eq(2)').text()
        };
        data.push(item);
    });

    // Debugging: check the collected data
    console.log(data);

    // Open a new window for printing


    // Debugging: check the printWindow object
    

    // Debugging: check if the content is written to the new window
    console.log(printWindow.document.body.innerHTML);
});
                // Function to handle printing when the "Refund Invoice" button is clicked
        $(document).on('click', '.refund-invoice', function() {
            // Implement refund invoice functionality if necessary
        });
    });
	
	
	      document.addEventListener('DOMContentLoaded', function() {
            // Sample sales data
            const sales = [
                {
                    discount_amount: 100, // Change this value to test different scenarios
                }
            ];

            let detailsHTML = '';
            
            // Function to check if the current tab is the refund tab
            function isRefundTab() {
                // Placeholder logic for checking if it's the refund tab
                // You can replace this with your actual logic, e.g., checking an element's ID or class
                return document.body.classList.contains('refund-tab');
            }

            // Check if sales array has elements and discount_amount is valid
            if (sales.length > 0 && sales[0].discount_amount && !isRefundTab()) {
                detailsHTML += '<div class="row tax-amount"><div class="col-sm-6">Discount:</div><div class="col-sm-6">Rs ' + sales[0].discount_amount + '</div></div>';
            }

            // Insert the generated HTML into the page
            document.getElementById('order-details').innerHTML = detailsHTML;
        });
	
    </script>
    </body>
</html>
