<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>View POS</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .tag {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            color: white;
            font-weight: bold;
        }

        .paid {
            background-color: green;
        }

        .due {
            background-color: red;
        }

        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .custom_select {
            position: relative;
            display: inline-block;
        }

        .select-button {
            background-color: #007BFF;
            color: white;
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 70px;
            text-align: left;
        }

        .arrow {
            margin-left: 3px;
        }

        .select-options {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 150px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
            border-radius: 4px;
            top: 100%;
            left: 0;
        }

        .select-options a {
            color: black;
            padding: 6px 10px;
            text-decoration: none;
            display: block;
            font-size: 12px;
        }

        .select-options a:hover {
            background-color: #f1f1f1;
        }
    </style>
    <!-- view payment detail -------->
    <script>
        function openPopup(url) {
            const popupWidth = 600;
            const popupHeight = 400;
            const left = (screen.width / 2) - (popupWidth / 2);
            const top = (screen.height / 2) - (popupHeight / 2);
            window.open(
                url,
                'Payment Details',
                `width=${popupWidth},height=${popupHeight},top=${top},left=${left},scrollbars=yes,resizable=yes`
            );
        }
    </script>

</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_pos.php">POS</a> > View POS
                                    </h4>
                                </div>
                                <div class="col-lg-6">
                                    <button class="btn btn-primary  ps-5 pe-5" style="float:inline-end;">
                                        <a href="pos.php" class="text-white">
                                            <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px">
                                            </ion-icon> Add
                                        </a>
                                    </button>
                                </div>
                            </div>
                            <!-- search bar -->

                            <!-- searchbar end -->
                            <!-- buttons for export -->
                            <div class="row mt-5">
                                <div class="col-lg-2"></div>
                                <button class="btn btn-info" id="exportExcel">
                                    <ion-icon name="document-outline"></ion-icon>Export to Excel
                                </button>
                                <!-- <button class="btn btn-dark" id="exportPDF">
                                    <ion-icon name="document-outline"></ion-icon>Export to PDF
                                </button> -->
                            </div> <?php
                                    include 'includes/config.php';

                                    // Initialize filters
                                    $date_filter_condition = '1'; // Default: no filtering
                                    $search_condition = '1'; // Default: no filtering

                                    // Handle date filter
                                    if (isset($_GET['date_filter'])) {
                                        $date_filter = $_GET['date_filter'];

                                        switch ($date_filter) {
                                            case 'today':
                                                $date_filter_condition = "s.date_sale = CURDATE()";
                                                break;
                                            case 'yesterday':
                                                $date_filter_condition = "s.date_sale = CURDATE() - INTERVAL 1 DAY";
                                                break;
                                            case 'last_7_days':
                                                $date_filter_condition = "s.date_sale >= CURDATE() - INTERVAL 7 DAY";
                                                break;
                                            case 'last_30_days':
                                                $date_filter_condition = "s.date_sale >= CURDATE() - INTERVAL 30 DAY";
                                                break;
                                            case 'this_month':
                                                $date_filter_condition = "MONTH(s.date_sale) = MONTH(CURDATE()) AND YEAR(s.date_sale) = YEAR(CURDATE())";
                                                break;
                                            case 'last_month':
                                                $date_filter_condition = "MONTH(s.date_sale) = MONTH(CURDATE() - INTERVAL 1 MONTH) AND YEAR(s.date_sale) = YEAR(CURDATE() - INTERVAL 1 MONTH)";
                                                break;
                                            case 'this_month_last_year':
                                                $date_filter_condition = "MONTH(s.date_sale) = MONTH(CURDATE()) AND YEAR(s.date_sale) = YEAR(CURDATE() - INTERVAL 1 YEAR)";
                                                break;
                                            case 'this_year':
                                                $date_filter_condition = "YEAR(s.date_sale) = YEAR(CURDATE())";
                                                break;
                                            case 'last_year':
                                                $date_filter_condition = "YEAR(s.date_sale) = YEAR(CURDATE() - INTERVAL 1 YEAR)";
                                                break;
                                        }
                                    }

                                    // Handle search filter
                                    if (isset($_GET['search']) && !empty($_GET['search'])) {
                                        $search_term = '%' . $_GET['search'] . '%'; // Use wildcards for partial matching
                                        $search_condition = " (c.name LIKE ? OR c.mobile LIKE ? OR s.invoice LIKE ?) ";
                                    }

                                    // Prepare the SQL query with both date and search filter conditions
                                    $query = "SELECT 
    s.invoice AS invoice_no,
    c.id AS customer_id,
    c.name AS customer_name,
    c.mobile AS contact_number,
    GROUP_CONCAT(s.product_name SEPARATOR ', ') AS product_names,
    SUM(s.price) AS total_price,
    SUM(s.sale_qty) AS total_sale_qty,
    SUM(s.total_amount) AS total_amount,
    SUM(s.order_tax) AS total_order_tax,
    SUM(s.discount) AS total_discount,
    s.payment_status,
    MAX(s.date_sale) AS date_sale,
    (
        SELECT 
            SUM(cd.amount) 
        FROM 
            bank_debit_amount cd 
        WHERE 
            cd.invoice = s.invoice
    ) AS total_net_cash
FROM 
    return_sale s
JOIN 
    contacts c ON s.customer_id = c.id
WHERE 
    $date_filter_condition AND $search_condition
GROUP BY 
    s.invoice
 ORDER by s.sale_id DESC";

                                    // Prepare the statement
                                    $stmt = $conn->prepare($query);

                                    // Bind parameters for the search filter if applicable
                                    if (isset($_GET['search']) && !empty($_GET['search'])) {
                                        $stmt->execute([$search_term, $search_term, $search_term]);
                                    } else {
                                        $stmt->execute();
                                    }

                                    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    ?>

                            <form action="" method="GET">
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-4 mb-4">
                                        <input type="search" name="search" class="form-control" placeholder="Search..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>" id="">
                                    </div>

                                    <div class="col-lg-4">
                                        <select name="date_filter" class="form-control">
                                            <option value="">Select Filter</option>
                                            <option value="today">Today</option>
                                            <option value="yesterday">Yesterday</option>
                                            <option value="last_7_days">Last 7 Days</option>
                                            <option value="last_30_days">Last 30 Days</option>
                                            <option value="this_month">This Month</option>
                                            <option value="last_month">Last Month</option>
                                            <option value="this_month_last_year">This Month Last Year</option>
                                            <option value="this_year">This Year</option>
                                            <option value="last_year">Last Year</option>
                                        </select>
                                    </div>
                                    <div class="col-lg-2">
                                        <button style="width:100%;" class="btn btn-primary p-2">Search</button>

                                    </div>
                                    <div class="col-lg-2">
                                        <a href="list_pos.php" class="btn btn-secondary  p-2" style="width:100%;">Clear Filter</a>

                                    </div>
                                </div>

                        </div>
                        </form>
                        <!-- buttons for export end -->
                        <div class="iq-card-body" style="overflow:auto;">


                            <table class="table table-hover table-bordered" id="salesTable">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="0"> Invoice No.</th>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="1"> Actions</th>
                                                                                <th><input type="checkbox" class="column-checkbox" checked data-column-index="10"> Date Sale</th>

                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="2"> Customer Name</th>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="3"> Contact Number</th>
                                        <th style="display: none;"><input type="checkbox" class="column-checkbox" data-column-index="4"> Product Names</th>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="5"> Total Price</th>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="6"> Total Return Quantity</th>
                                        <th><input type="checkbox" class="column-checkbox" checked data-column-index="7"> Total Return Amount</th>
                                        <!--<th><input type="checkbox" class="column-checkbox" checked data-column-index="8"> Total Sale Tax</th>-->
                                        <!--<th><input type="checkbox" class="column-checkbox" checked data-column-index="9"> Total Discount</th>-->
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $total_due_amount = 0; // Initialize the total due amount
                                    foreach ($sales as $sale):
                                        $due_amount = ($sale['total_amount'] + $sale['total_order_tax']) - ($sale['total_net_cash'] + $sale['total_discount']);
                                        $payment_status_class = $due_amount > 0 ? 'due' : 'paid';
                                        $payment_status_text = $due_amount > 0 ? 'Due' : 'Paid';

                                        // Accumulate the due amount for each row
                                        $total_due_amount += $due_amount;
                                    ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars(intval($sale['invoice_no'])); ?></td>
                                            <td>
                                                <div class="custom_select">
                                                    <button class="select-button">
                                                        <span class="selected-option">Actions</span>
                                                        <span class="arrow">&#9660;</span>
                                                    </button>
                                                    <div class="select-options">
                                                        <a href="print/return_customer_bill.php?invoice_no=<?php echo htmlentities($sale['invoice_no']); ?>" class="">
                                                            <ion-icon name="print-outline"></ion-icon> &nbsp; Print
                                                        </a>
                                                        <!-- <a href="javascript:void(0);" 
   onclick="openPopup('customer_bill_amount_detail.php?invoice_no=<?php echo htmlentities($sale['invoice_no']); ?>')">
    <ion-icon name="print-outline"></ion-icon> &nbsp; View Payment
</a> -->

                                                        <!-- <a href="javascript:void(0);" class="add-payment-link" 
                data-toggle="modal" 
                data-target="#exampleModal"
                data-invoice-no="<?php echo htmlspecialchars($sale['invoice_no']); ?>"
                data-customer-id="<?php echo htmlspecialchars($sale['customer_id']); ?>"
                data-customer-name="<?php echo htmlspecialchars($sale['customer_name']); ?>"
                data-due-amount="<?php echo htmlspecialchars(number_format($due_amount, 2)); ?>"
                data-sale-date="<?php echo htmlspecialchars($sale['date_sale']); ?>">
                <ion-icon name="cash-outline"></ion-icon> &nbsp; Add Payment
            </a> -->
            <!--<a href="edit_pos.php?invoice=<?php echo htmlentities($sale['invoice_no']); ?>" class="delete-link" >-->
            <!--<ion-icon name="create-outline"></ion-icon> &nbsp; Edit-->
            <!--                                            </a>-->
                                                        <a href="action/delete_pos_return_sale.php?del=<?php echo htmlspecialchars($sale['invoice_no']); ?>" class="delete-link" onclick="return confirm('Are you sure you want to delete this item?');">
                                                            <ion-icon name="trash-outline"></ion-icon> &nbsp; Delete
                                                        </a>
                                                    </div>
                                                </div>
                                            </td>
                                                                                        <td><?php echo htmlspecialchars($sale['date_sale']); ?></td>

                                            <td data-customer-id="<?php echo htmlspecialchars($sale['customer_id']); ?>" data-invoice-no="<?php echo htmlspecialchars($sale['invoice_no']); ?>"><?php echo htmlspecialchars($sale['customer_name']); ?></td>
                                            <td><?php echo htmlspecialchars($sale['contact_number']); ?></td>
                                            <!-- <td>
                <span class="tag <?php echo htmlspecialchars($payment_status_class); ?>">
                    <?php echo htmlspecialchars($payment_status_text); ?>
                </span>
            </td> -->
                                            <td style="display: none;"><?php echo htmlspecialchars($sale['product_names']); ?></td>
                                            <td><?php echo htmlspecialchars($sale['total_price']); ?></td>
                                            <td><?php echo htmlspecialchars($sale['total_sale_qty']); ?></td>
                                            <td><?php echo htmlspecialchars($sale['total_amount']); ?></td>
                                            <!-- <td><?php echo htmlspecialchars($sale['total_net_cash']); ?></td> -->
                                            <!-- <td><?php echo htmlspecialchars(number_format($due_amount, 2)); ?></td> -->
                                            <!--<td><?php echo htmlspecialchars($sale['total_order_tax']); ?></td>-->
                                            <!--<td><?php echo htmlspecialchars($sale['total_discount']); ?></td>-->
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="9" class="text-right"><strong>Total Due Amount:</strong></td>
                                        <td><strong><?php echo htmlspecialchars(number_format($total_due_amount, 2)); ?></strong></td>
                                        <td colspan="4"></td>
                                    </tr>
                                </tfoot>
                            </table>

                            <!--------------------------------Add Payment pop up ------------------------------------------>
                            <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" style="z-index: 99999;">
                                <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">Add Payment</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body">
                                            <form id="paymentForm" method="POST">
                                                <div class="form-row">
                                                    <div class="form-group col-md-6">
                                                        <label for="invoice_no">Invoice No</label>
                                                        <input type="text" class="form-control" id="invoice_no" name="invoice_no" readonly>
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="Sale_date">Sale Date</label>
                                                        <input type="date" class="form-control" id="Sale_date" name="sale_date" required>
                                                    </div>
                                                </div>
                                                <div class="form-row">
                                                    <div class="form-group col-md-6">
                                                        <label for="user_id">Customer Name</label>
                                                        <input type="hidden" class="form-control" id="user_id" name="user_id" readonly>
                                                        <input type="text" class="form-control" id="customer" name="customer" readonly>
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="due_amount">Due Amount</label>
                                                        <input type="text" class="form-control" id="due_amount" name="due_amount" readonly>
                                                    </div>
                                                </div>
                                                <div class="form-row">
                                                    <div class="form-group col-md-6">
                                                        <label for="paymentMethod">Payment Method</label>
                                                        <select class="form-control" id="paymentMethod" name="paymentMethod" onchange="togglePaymentFieldsAndAction()" required>
                                                            <option value="">Select Payment Method</option>
                                                            <option value="bank">Bank</option>
                                                            <option value="cheque">Cheque</option>
                                                        </select>
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="amount">Amount</label>
                                                        <input type="number" class="form-control" id="amount" name="amount" required>
                                                    </div>
                                                </div>

                                                <!-- Bank Fields -->
                                                <div id="bankFields" class="form-row" style="display: none;">
                                                    <div class="form-group col-md-6">
                                                        <label for="Credit_account">Credit Account</label>
                                                        <select class="form-control" id="Credit_account" name="credit_account">
                                                            <option value="">Select Account</option>
                                                            <!-- Dynamically populated options -->
                                                        </select>
                                                    </div>

                                                </div>

                                                <!-- Cheque Fields -->
                                                <div id="chequeFields" class="form-row" style="display: none;">
                                                    <div class="form-group col-md-6">
                                                        <label for="chequeNumber">Cheque Number</label>
                                                        <input type="text" class="form-control" id="chequeNumber" name="cheque_number">
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="bankName">Bank Name</label>
                                                        <input type="text" class="form-control" id="bankName" name="bank_name">
                                                    </div>
                                                </div>
                                                <div id="chequeFields2" class="form-row" style="display: none;">
                                                    <div class="form-group col-md-6">
                                                        <label for="issuedDate">Issued Date</label>
                                                        <input type="date" class="form-control" id="issuedDate" name="issued_date">
                                                    </div>
                                                    <div class="form-group col-md-6">
                                                        <label for="status">Status</label>
                                                        <select class="form-control" id="status" name="status" onchange="toggleHoldUntilField()">
                                                            <option value="cleared">Cleared</option>
                                                            <option value="hold">Hold</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div id="holdUntilField" class="form-row" style="display: none;">
                                                    <div class="form-group col-md-6">
                                                        <label for="holdUntil">Hold Until</label>
                                                        <input type="date" class="form-control" id="holdUntil" name="hold_until">
                                                    </div>
                                                </div>

                                                <div class="form-group">
                                                    <label for="payment_status">Note</label>
                                                    <textarea class="form-control" id="payment_status" name="payment_status" required></textarea>
                                                </div>

                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                    <button type="submit" class="btn btn-primary" id="submitPayment">Submit Payment</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <script>
                                function togglePaymentFieldsAndAction() {
                                    const paymentMethod = document.getElementById('paymentMethod').value;
                                    const status = document.getElementById('status') ? document.getElementById('status').value : null;
                                    const paymentForm = document.getElementById('paymentForm');
                                    const bankFields = document.getElementById('bankFields');
                                    const chequeFields = document.getElementById('chequeFields');
                                    const chequeFields2 = document.getElementById('chequeFields2');

                                    if (paymentMethod === 'bank') {
                                        bankFields.style.display = 'flex';
                                        chequeFields.style.display = 'none';
                                        chequeFields2.style.display = 'none';
                                        paymentForm.action = 'submit_payment.php';
                                    } else if (paymentMethod === 'cheque') {
                                        if (status === 'cleared') {
                                            bankFields.style.display = 'flex';
                                        } else {
                                            bankFields.style.display = 'none';
                                        }

                                        chequeFields.style.display = 'flex';
                                        chequeFields2.style.display = 'flex';
                                        paymentForm.action = 'submit_payment_cheque.php';
                                    } else {
                                        bankFields.style.display = 'none';
                                        chequeFields.style.display = 'none';
                                        chequeFields2.style.display = 'none';
                                        paymentForm.action = '';
                                    }
                                }

                                function toggleHoldUntilField() {
                                    const status = document.getElementById('status').value;
                                    const holdUntilField = document.getElementById('holdUntilField');

                                    if (status === 'hold') {
                                        holdUntilField.style.display = 'flex';
                                    } else {
                                        holdUntilField.style.display = 'none';
                                    }
                                }
                            </script>

                            <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    fetch('get_banks.php')
                                        .then(response => response.json())
                                        .then(data => {
                                            const creditAccountSelect = document.getElementById('Credit_account');
                                            data.forEach(bank => {
                                                const option = document.createElement('option');
                                                option.value = bank.id;
                                                option.textContent = bank.bank_name;
                                                creditAccountSelect.appendChild(option);
                                            });
                                        })
                                        .catch(error => console.error('Error fetching banks:', error));

                                    document.querySelectorAll('.add-payment-link').forEach(link => {
                                        link.addEventListener('click', function() {
                                            const invoiceNo = this.dataset.invoiceNo;
                                            const customerId = this.dataset.customerId;
                                            const customerName = this.dataset.customerName;
                                            const dueAmount = this.dataset.dueAmount;
                                            const saleDate = this.dataset.saleDate;

                                            document.getElementById('invoice_no').value = invoiceNo;
                                            document.getElementById('user_id').value = customerId;
                                            document.getElementById('customer').value = customerName;
                                            document.getElementById('due_amount').value = dueAmount;
                                            document.getElementById('Sale_date').value = saleDate;
                                        });
                                    });
                                });
                            </script>

                            <!----------------------------------End Add payment pop up------------------------------------------------>

                            <!-- Modal Structure -->
                            <div id="infoModal" class="modal">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h2>Details</h2>
                                        <span class="close-btn" onclick="closeModal()">&times;</span>
                                    </div>
                                    <div class="modal-body">
                                        <div class="modal-left">
                                            <p><strong>Invoice No:</strong> <span id="modal-invoice-no"></span></p>
                                        </div>
                                        <div class="modal-center">
                                            <p><strong>Customer Name:</strong> <span id="modal-customer-name"></span></p>
                                            <p><strong>Contact Number:</strong> <span id="modal-contact-number"></span></p>
                                        </div>
                                        <div class="modal-right">
                                            <p><strong>Date:</strong> <span id="modal-date"></span></p>
                                        </div>
                                        <div class="modal-payment-status">
                                            <p><strong>Payment Status:</strong> <span id="modal-payment-status"></span></p>
                                        </div>
                                        <table class="modal-detail-table">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Product</th>
                                                    <th>Quantity</th>
                                                    <th>Unit Price</th>
                                                    <!-- <th>Discount</th>
                        <th>Tax</th> -->
                                                    <th>Price</th>
                                                    <th>Subtotal</th>
                                                </tr>
                                            </thead>
                                            <tbody id="modal-detail-table-body">
                                                <!-- Dynamic rows will be populated here -->
                                            </tbody>
                                            <tfoot>
                                                <tr class="total-row">
                                                    <td colspan="5">Subtotal</td>
                                                    <td id="total-subtotal">0.00</td>
                                                </tr>
                                                <!--<tr class="total-row">-->
                                                <!--    <td colspan="5">Total Discount</td>-->
                                                <!--    <td id="total-discount">0.00</td>-->
                                                <!--</tr>-->
                                                <tr class="total-row">
                                                    <td colspan="5">Total Tax</td>
                                                    <td id="total-tax">0.00</td>
                                                </tr>
                                                <tr class="total-row">
                                                    <td colspan="5">Net Cash</td>
                                                    <td id="total-net-cash">0.00</td>
                                                </tr>
                                                <tr class="total-row">
                                                    <td colspan="5">Remaining Total</td>
                                                    <td id="remaining-balance">0.00</td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>


                            <style>
                                /* Modal styling */
                                .modal {
                                    display: none;
                                    position: fixed;
                                    z-index: 1000;
                                    left: 0;
                                    top: 0;
                                    width: 100%;
                                    height: 100%;
                                    overflow: auto;
                                    background-color: rgba(0, 0, 0, 0.6);
                                    transition: opacity 0.3s ease;
                                }

                                .modal-content {
                                    background-color: #fff;
                                    margin: 5% auto;
                                    padding: 20px;
                                    border-radius: 8px;
                                    width: 80%;
                                    max-width: 1000px;
                                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                                    animation: slideIn 0.3s ease;
                                }

                                @keyframes slideIn {
                                    from {
                                        opacity: 0;
                                        transform: translateY(-50px);
                                    }

                                    to {
                                        opacity: 1;
                                        transform: translateY(0);
                                    }
                                }

                                .modal-header {
                                    display: flex;
                                    justify-content: space-between;
                                    align-items: center;
                                    border-bottom: 1px solid #ddd;
                                    padding-bottom: 10px;
                                    margin-bottom: 15px;
                                }

                                .modal-header h2 {
                                    margin: 0;
                                    color: #333;
                                }

                                .close-btn {
                                    font-size: 24px;
                                    font-weight: bold;
                                    color: #333;
                                    cursor: pointer;
                                    transition: color 0.3s ease;
                                }

                                .close-btn:hover {
                                    color: #f00;
                                }

                                .modal-body {
                                    display: flex;
                                    flex-direction: column;
                                }

                                .modal-left,
                                .modal-center,
                                .modal-right,
                                .modal-payment-status {
                                    padding: 10px;
                                    border-radius: 4px;
                                    background-color: #f9f9f9;
                                    border: 1px solid #ddd;
                                    margin-bottom: 10px;
                                }

                                .modal-left {
                                    background-color: #eaf4f4;
                                }

                                .modal-center {
                                    background-color: #e7f0f7;
                                }

                                .modal-right {
                                    background-color: #f4f7ea;
                                }

                                .modal-payment-status {
                                    background-color: #f4eaf4;
                                }

                                .modal-body p {
                                    margin: 5px 0;
                                }

                                .modal-detail-table {
                                    width: 100%;
                                    border-collapse: collapse;
                                    margin-top: 20px;
                                }

                                .modal-detail-table th,
                                .modal-detail-table td {
                                    border: 1px solid #ddd;
                                    padding: 10px;
                                    text-align: left;
                                }

                                .modal-detail-table th {
                                    background-color: #f4f4f4;
                                    color: #333;
                                }

                                .modal-detail-table tbody tr:nth-child(even) {
                                    background-color: #f9f9f9;
                                }

                                .modal-detail-table tbody tr:hover {
                                    background-color: #f1f1f1;
                                }

                                /* Total rows styling */
                                .total-row {
                                    font-weight: bold;
                                    background-color: #f4f4f4;
                                }

                                .total-row td {
                                    border: none;
                                    padding: 10px;
                                }
                            </style>
                            <script>
                                document.addEventListener('DOMContentLoaded', () => {
                                    // Attach event listeners for dynamically added elements
                                    document.body.addEventListener('click', (event) => {
                                        const selectButton = event.target.closest('.select-button');
                                        const selectOptions = event.target.closest('.select-options');

                                        if (selectButton) {
                                            const dropdown = selectButton.nextElementSibling; // select-options
                                            dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
                                            event.stopPropagation(); // Prevent the click from propagating to window
                                        } else if (!selectOptions || !selectOptions.contains(event.target)) {
                                            // Hide all dropdowns if the click is outside of any dropdown
                                            document.querySelectorAll('.select-options').forEach((dropdown) => {
                                                if (dropdown.style.display === 'block') {
                                                    dropdown.style.display = 'none';
                                                }
                                            });
                                        }
                                    });

                                    // Handle option selection
                                    document.body.addEventListener('click', (event) => {
                                        if (event.target.tagName === 'A' && event.target.closest('.select-options')) {
                                            const selectButton = event.target.closest('.custom_select').querySelector('.select-button');
                                            selectButton.querySelector('.selected-option').textContent = event.target.textContent;
                                            event.target.closest('.select-options').style.display = 'none';
                                        }
                                    });
                                });
                            </script>
                            <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    const tableBody = document.querySelector('tbody');
                                    const modal = document.getElementById('infoModal');
                                    const modalInvoiceNo = document.getElementById('modal-invoice-no');
                                    const modalCustomerName = document.getElementById('modal-customer-name');
                                    const modalContactNumber = document.getElementById('modal-contact-number');
                                    const modalDate = document.getElementById('modal-date');
                                    const modalPaymentStatus = document.getElementById('modal-payment-status');
                                    const modalDetailTableBody = document.getElementById('modal-detail-table-body');
                                    const totalSubtotalEl = document.getElementById('total-subtotal');
                                    const totalDiscountEl = document.getElementById('total-discount');
                                    const totalTaxEl = document.getElementById('total-tax');
                                    const totalNetCashEl = document.getElementById('total-net-cash');
                                    const remainingBalanceEl = document.getElementById('remaining-balance'); // Changed ID for Remaining Balance

                                    tableBody.addEventListener('click', function(event) {
                                        // Find the closest td element that was clicked
                                        const targetCell = event.target.closest('td');

                                        // Proceed only if the clicked element is a <td> and has the attributes data-customer-id and data-invoice-no
                                        if (targetCell && targetCell.hasAttribute('data-customer-id') && targetCell.hasAttribute('data-invoice-no')) {
                                            const targetRow = targetCell.parentElement; // Get the parent <tr>

                                            // Extract the required data from the clicked <td>
                                            const invoiceNo = targetCell.getAttribute('data-invoice-no');
                                            const customerId = targetCell.getAttribute('data-customer-id');
                                            const customerName = targetCell.innerText;
                                            const contactNumber = targetRow.cells[3].innerText;
                                            const date = targetRow.cells[13].innerText; // Assuming "Date Sale" is at index 13
                                            const paymentStatus = targetRow.cells[4].innerText; // Assuming "Payment Status" is at index 4

                                            // Assign the modal values
                                            modalInvoiceNo.innerText = parseInt(invoiceNo);
                                            modalCustomerName.innerText = customerName;
                                            modalContactNumber.innerText = contactNumber;
                                            modalDate.innerText = date;
                                            modalPaymentStatus.innerText = paymentStatus;

                                            // Fetch sale details
                                            fetch(`get_sale_details.php?customer_id=${customerId}&invoice_no=${invoiceNo}`)
                                                .then(response => response.json())
                                                .then(data => {
                                                    if (data.error) {
                                                        console.error('Error:', data.error);
                                                        return;
                                                    }

                                                    modalDetailTableBody.innerHTML = '';
                                                    let totalSubtotal = 0;
                                                    let totalDiscount = 0;
                                                    let totalTax = 0;

                                                    data.details.forEach((item, index) => {
                                                        const quantity = parseFloat(item.quantity) || 0;
                                                        const unitPrice = parseFloat(item.unit_price) || 0;
                                                        const discount = parseFloat(item.discount) || 0;
                                                        const tax = parseFloat(item.tax) || 0;
                                                        const priceIncTax = parseFloat(item.price_inc_tax) || 0;
                                                        const subtotal = parseFloat(item.subtotal) || 0;

                                                        const row = document.createElement('tr');
                                                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td>${item.product_name}</td>
                            <td>${quantity}</td>
                            <td>${unitPrice.toFixed(2)}</td>
                            <td>${priceIncTax.toFixed(2)}</td>
                            <td>${subtotal.toFixed(2)}</td>
                        `;
                                                        modalDetailTableBody.appendChild(row);

                                                        totalSubtotal += subtotal;
                                                        totalDiscount += discount;
                                                        totalTax += tax;
                                                    });

                                                    // Set modal values
                                                    totalSubtotalEl.innerText = totalSubtotal.toFixed(2);
                                                    totalDiscountEl.innerText = totalDiscount.toFixed(2);
                                                    totalTaxEl.innerText = totalTax.toFixed(2);
                                                    totalNetCashEl.innerText = data.totalNetCash.toFixed(2);

                                                    // Calculate Grand Total and Remaining Balance
                                                    const grandTotal = totalSubtotal - totalDiscount + totalTax;
                                                    const remainingBalance = grandTotal - data.totalNetCash;

                                                    // Set Remaining Balance in the modal
                                                    remainingBalanceEl.innerText = remainingBalance.toFixed(2);
                                                })
                                                .catch(error => console.error('Error fetching details:', error));

                                            // Show the modal
                                            modal.style.display = 'block';
                                        }
                                    });

                                    function closeModal() {
                                        modal.style.display = 'none';
                                    }

                                    // Close button event listener
                                    document.querySelector('.close-btn').addEventListener('click', closeModal);

                                    // Close modal when clicking outside of it
                                    window.onclick = function(event) {
                                        if (event.target == modal) {
                                            closeModal();
                                        }
                                    };
                                });
                            </script>



                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                            document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                                .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const checkboxes = document.querySelectorAll(".column-checkbox");
            const table = document.getElementById("salesTable");

            checkboxes.forEach(checkbox => {
                checkbox.addEventListener("change", function() {
                    const columnIndex = this.dataset.columnIndex;
                    const isChecked = this.checked;

                    const rows = table.querySelectorAll("tr");
                    rows.forEach(row => {
                        const cells = row.querySelectorAll("th, td");
                        if (cells[columnIndex]) {
                            cells[columnIndex].style.display = isChecked ? "" : "none";
                        }
                    });
                });
            });

            document.getElementById("exportExcel").addEventListener("click", function(event) {
                event.preventDefault();
                exportTableToExcel();
            });

            function exportTableToExcel() {
                const workbook = XLSX.utils.book_new();
                const visibleColumns = [];
                const headerRow = [];
                const dataRows = [];

                checkboxes.forEach((checkbox, index) => {
                    if (checkbox.checked && checkbox.dataset.columnIndex !== "1") {
                        visibleColumns.push(index);
                        headerRow.push(checkbox.parentElement.textContent.trim());
                    }
                });

                const rows = table.querySelectorAll("tbody tr");
                rows.forEach(row => {
                    const rowData = [];
                    const cells = row.querySelectorAll("td");
                    visibleColumns.forEach(index => {
                        rowData.push(cells[index]?.innerText || "");
                    });
                    dataRows.push(rowData);
                });

                const worksheetData = [headerRow, ...dataRows];
                const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

                const columnWidths = headerRow.map(header => ({
                    wch: Math.max(header.length + 5, 15)
                }));
                worksheet["!cols"] = columnWidths;

                const headerRange = XLSX.utils.decode_range(worksheet["!ref"]);
                for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
                    const cellAddress = XLSX.utils.encode_cell({
                        r: 0,
                        c: col
                    });
                    worksheet[cellAddress].s = {
                        font: {
                            bold: true
                        },
                        alignment: {
                            horizontal: "center",
                            vertical: "center"
                        },
                        fill: {
                            fgColor: {
                                rgb: "FFFF00"
                            }
                        }
                    };
                }

                XLSX.utils.book_append_sheet(workbook, worksheet, "Sales Data");
                XLSX.writeFile(workbook, "sales_data.xlsx");
            }
        });
    </script>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>