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

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>

<!--get customer name or id-->
<?php
function get_brand()
{
    require("include/config.php");
    $output = '';
    $sql = "SELECT * FROM contacts WHERE type = 'customer' ORDER BY id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    if (count($rows) > 0) {
        foreach ($rows as $row) {
            $output .= '<option value="' . $row["id"] . '">' . $row["name"] . '</option>';
        }
    }
    return $output;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Add To Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
    <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">

    <style>
        main {
            height: 458px;
            overflow: auto;
            /* background-color: white; */
        }

        th {
            background-color: rgb(210 214 223);
        }

        .mein {
            height: 283px;
            overflow-y: auto;
            border-bottom: 1px solid green;
            margin-left: -12px;
        }

        .mein table {
            width: 100%;
            margin-left: -0px;
        }

        .mein input[type="number"] {
            width: 100px;
        }

        table {
            margin-left: -12px;
        }

        .select2-container--default .select2-selection--single {
            border: none;
            /* Remove border */
            background-color: transparent;
            /* Make background transparent */
            box-shadow: none;
            /* Remove any shadow */
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #000;
            /* Text color */
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            display: none;
            /* Optionally hide the arrow */
        }

        /* Optional: Add focus styles */
        .select2-container--default .select2-selection--single:focus {
            outline: none;
            /* Remove focus outline */
        }



        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background-color: #f8f8f8;
            border-bottom: 1px solid #ccc;
        }

        .location {
            font-size: 18px;
            font-weight: bold;
        }

        .datetime {
            font-size: 14px;
            color: #555;
        }


        .back-button p {
            background-color: #007BFF;
            /* Primary color */
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .back-button p:hover {
            background-color: #0056b3;
            /* Darker shade on hover */
        }

        .back-button p:focus {
            outline: none;
            /* Remove outline on focus */
        }

        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            /* 15% from the top and centered */
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            /* Could be more or less, depending on screen size */
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-control {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }

        .btn {
            background-color: rgb(243, 156, 17);
            color: white;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
        }

        .btn:hover {
            background-color: darkorange;
        }
       /* .col-lg-7.col-md-7 {
                    display: flex;
                    flex-direction: column;
                    height: 100vh;
                    border-right: 1px solid #ddd;
                    overflow: hidden;
                } */
    </style>
  
    <style>
        #dateTime {
            font-size: 18px;
            font-weight: bold;
            color: #0073e6;
            /* Royal Blue */
            background: #f0f8ff;
            /* Light Sky Blue */

            border-radius: 5px;
            display: inline-block;
            box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
        }
    </style>
                  <style>
                    
html, body { height: 100%; margin: 0; font-family: Arial, sans-serif; }
.container-fullscreen { display: flex; flex-direction: column; height: 90vh; background-color: rgba(247, 245, 242, 1); padding: 10px; box-sizing: border-box; }
.mein { flex: 1; overflow-y: auto; margin-bottom: 10px; }
.tbl { flex-shrink: 0; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; }
table th, table td { padding: 6px; border: 1px solid #ccc; text-align: left; word-wrap: break-word; font-size: 12px; }
.tbl input, .tbl select { width: 100%; padding: 5px; border-radius: 5px; box-sizing: border-box; font-size: 12px; }
.buttons-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 5px; margin-top: 10px; }
.buttons-row button { flex: 1 1 100px; max-width: 150px; padding: 6px; font-size: 12px; border: none; border-radius: 5px; color: white; cursor: pointer; }
#holdButton { background-color: #605ca8; }
#submitBtn { background-color: #2dce89; }
#installmentBtn { background-color: #f39c12; }
</style>
    <!-- <div id="dateTime"></div> -->

    <script>
        const updateDateTime = () => {
            const now = new Date();
            const options = {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            };
            document.getElementById('dateTime').textContent = now.toLocaleDateString(undefined, options);
        };

        setInterval(updateDateTime, 1000); 
        updateDateTime();
    </script>      <!-- Include jQuery (required for Select2) -->
                    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                    <!-- Include Select2 CSS and JS -->
                    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
                    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

                    <script>
                        $(document).ready(function() {
                            $('#category-filter').select2({
                                placeholder: 'View All Categories',
                                allowClear: true
                            });
                        });
                    </script>
</head>

<body>
    <!-- Modal -->
    <!-- Modal -->
    <div class="modal" id="addUnitModal">
        <div class="modal-content">
            <div class="modal-header">
                <h4>Add Customer</h4>
                <span class="close" id="closeModalButton">&times;</span>
            </div>
            <form method="POST" action="submit_contact_customer_pos.php">
                <div class="modal-body">
                    <!-- Your form fields -->
                    <div class="row">
                        <div class="form-group col">
                            <label for="name">Name:*</label>
                            <input type="text" class="form-control" name="name" placeholder="Enter Name" required>
                        </div>
                        <div class="form-group col">
                            <label for="contact_id">Contact ID:</label>
                            <input type="number" class="form-control" name="contact_id" placeholder="Contact ID">
                        </div>
                        <div class="form-group col" style="display: none;">
                            <label for="tax_number">Tax number:</label>
                            <input type="number" class="form-control" name="tax_number" placeholder="Tax number">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col" style="display: none;">
                            <label for="opening_balance">Opening Balance:</label>
                            <input type="number" class="form-control" name="opening_balance" placeholder="0">
                        </div>
                        <div class="form-group col" style="display: none;">
                            <label for="pay_term_type">Pay term:</label>
                            <input type="number" class="form-control" name="pay_term_type" placeholder="Pay term">
                        </div>
                        <div class="form-group col" style="display: none;">
                            <label for="credit_limit">Credit Limit:</label>
                            <input type="number" class="form-control" name="credit_limit" placeholder="Credit Limit">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col">
                            <label for="email">Email:</label>
                            <input type="email" class="form-control" name="email" placeholder="Email">
                        </div>
                        <div class="form-group col">
                            <label for="mobile">Mobile:*</label>
                            <input type="text" class="form-control" name="mobile" placeholder="Mobile Number:*"
                                required>
                        </div>
                        <div class="form-group col">
                            <label for="alternate_number">Alternate contact number:</label>
                            <input type="text" class="form-control" name="alternate_number"
                                placeholder="Alternate contact number">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col">
                            <label for="landline">Landline:</label>
                            <input type="text" class="form-control" name="landline" placeholder="Landline">
                        </div>
                        <div class="form-group col">
                            <label for="city">City:</label>
                            <input type="text" class="form-control" name="city" placeholder="City">
                        </div>
                        <div class="form-group col">
                            <label for="state">State:</label>
                            <input type="text" class="form-control" name="state" placeholder="State">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col">
                            <label for="country">Country:</label>
                            <input type="text" class="form-control" name="country" placeholder="Country">
                        </div>
                        <div class="form-group col">
                            <label for="landmark">Landmark:</label>
                            <input type="text" class="form-control" name="landmark" placeholder="Landmark">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col">
                            <label for="" class="label-control">Custom Field 1:</label>
                            <input type="text" class="form-control" name="custom_field1" placeholder="Custom Field 1">
                        </div>
                        <div class="form-group col">
                            <label for="" class="label-control">Custom Field 2:</label>
                            <input type="text" class="form-control" name="custom_field2" placeholder="Custom Field 2">
                        </div>
                        <div class="form-group col">
                            <label for="" class="label-control">Custom Field 3:</label>
                            <input type="text" class="form-control" name="custom_field3" placeholder="Custom Field 3">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col">
                            <label for="" class="label-control">Custom Field 4:</label>
                            <input type="text" class="form-control" name="custom_field4" placeholder="Custom Field 4">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn" name="submit_popup">Submit</button>
                    <button type="button" class="btn" id="closeModalButtonFooter">Close</button>
                </div>
            </form>
        </div>
    </div>

    <!-- CSS -->
    <style>
        .modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background: #fff;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 60%;
            max-width: 700px;
        }

        .close {
            cursor: pointer;
            font-size: 20px;
        }
    </style>

    <!-- JS -->
    <script>
        // Wait until DOM ready
        document.addEventListener("DOMContentLoaded", function() {
            var modal = document.getElementById("addUnitModal");
            var openBtn = document.getElementById("openModalBtn");
            var closeBtn = document.getElementById("closeModalButton");
            var closeFooterBtn = document.getElementById("closeModalButtonFooter");

            // Open modal
            openBtn.onclick = function() {
                modal.style.display = "block";
            }

            // Close modal (X button)
            closeBtn.onclick = function() {
                modal.style.display = "none";
            }

            // Close modal (footer button)
            closeFooterBtn.onclick = function() {
                modal.style.display = "none";
            }

            // Close modal when clicking outside
            window.onclick = function(event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }
        });
    </script>

    <?php
    // Fetch categories with business_id = 3


    // Fetch brands for filters
    try {
        $brandQuery = 'SELECT DISTINCT name FROM brands ORDER BY name';
        $brandStmt = $conn->query($brandQuery);
        $brands = $brandStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        echo "Error fetching brands: " . htmlspecialchars($e->getMessage());
        $brands = [];
    }

    // Fetch customers for filters
    try {
        $customerQuery = "SELECT id, name FROM contacts WHERE type = 'customer' ORDER BY id";
        $customerStmt = $conn->query($customerQuery);
        $customers = $customerStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        echo "Error fetching customers: " . htmlspecialchars($e->getMessage());
        $customers = [];
    }


    ?>
    <!-- <nav class="navbar" style="background-color:rgb(255, 237, 137)">
        <div class="location">Pen Grid</div>
        <div class="datetime">
            <span id="dateTime"></span>
        </div>
        <div class="back-button">
            <button onclick="location.href='list_pos.php'">&lt; Back</button>
        </div>

    </nav> -->


    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-7 col-md-7">
                <header class="p-3" style="
    background-color: #f4f4f4;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
    border-bottom: 3px solid #0073e6;
">
                    <div class="row align-items-center">
                        <!-- Search Bar -->
                        <div class="col-lg-6 col-md-6 col-sm-6 col-6 d-flex align-items-center">
                            <ion-icon name="search-outline" style="
                font-size: 20px;
                margin-right: 10px;
                color: #333;
            "></ion-icon>
                            <input type="text" id="product-search" class="form-control"
                                style="border: 1px solid #ccc; border-radius: 30px; padding: 5px 15px; width: 100%;"
                                placeholder="Search/Scan Bar">
                        </div>

                        <!-- Category Dropdown -->
                        <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                            <?php
                            // Fetch categories with business_id = 3
                            try {
                                $categoryQuery = 'SELECT id, name FROM categories WHERE business_id = 3 ORDER BY name';
                                $categoryStmt = $conn->query($categoryQuery);
                                $categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);
                            } catch (PDOException $e) {
                                echo "Error fetching categories: " . htmlspecialchars($e->getMessage());
                                $categories = [];
                            }

                            $options = '<option value="">View All</option>'; 
                            foreach ($categories as $category) {
                                $options .= '<option value="' . htmlspecialchars($category['id']) . '">';
                                $options .= htmlspecialchars($category['name']);
                                $options .= '</option>';
                            }
                            ?>
                            <select name="category" class="form-control select2" id="category-filter"
                                style="width: 100%; border-radius: 30px; padding: 5px;">
                                <?php echo $options; ?>
                            </select>
                        </div>


                    </div>

              
                </header>


                <main>

                    <div class="row" style="margin: 0px; padding: 0px" id="productCardsContainer">
                        <?php
                        $limit = 30;
                        $offset = 0;

                        $sql = "SELECT 
            pl.product_id,
            pl.color_id,
            pl.size_id,
            pl.quantity,
            pl.sell_price,
            p.name AS product_name,
            p.image AS product_image,
            c.id AS category_id,
            c.name AS category_name,
            b.name AS brand_name,
            p.sku,
            clr.product_color,
            sz.product_size
        FROM 
            purchase_lines AS pl
        JOIN 
            products AS p ON pl.product_id = p.id
        LEFT JOIN 
            categories AS c ON p.category_id = c.id
        LEFT JOIN 
            brands AS b ON p.brand_id = b.id
        LEFT JOIN 
            colors AS clr ON pl.color_id = clr.id
        LEFT JOIN 
            sizes AS sz ON pl.size_id = sz.id
        GROUP BY 
            pl.product_id, pl.color_id, pl.size_id
        ORDER BY 
            pl.product_id DESC
        LIMIT :limit OFFSET :offset";


                        $stmt = $conn->prepare($sql);
                        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
                        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
                        $stmt->execute();
                        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

                        foreach ($products as $rows) {
                            $productImage = !empty($rows["product_image"]) ? htmlspecialchars($rows["product_image"]) : 'dumy_image.png';
                        ?>

                        <?php } ?>

                    </div>


                </main>

            </div>
<style>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* Works across iOS/Android/PC */
.col-lg-7.col-md-7 {
  display: flex;
  flex-direction: column;
  height: 100dvh;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}

.col-lg-7.col-md-7 header {
  flex-shrink: 0;
  background-color: #f4f4f4;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  border-bottom: 3px solid #0073e6;
  z-index: 5;
}

.col-lg-7.col-md-7 main {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 8px;
  background-color: #fafafa;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

.col-lg-7.col-md-7 main::-webkit-scrollbar {
  width: 6px;
}
.col-lg-7.col-md-7 main::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}
</style>




            <div class="col-lg-5 col-md-5 col-sm-5 col-5" style="padding: 0px">
                <!--<form action="" method="POST" <?php echo $_SERVER['PHP_SELF']; ?>>-->
                <form id="saleForm" method="POST">


           <div class="row p-2" style="background-color: rgb(255, 255, 255);"> 
    <div class="col-lg-5 col-md-6 col-sm-12 mb-2 d-flex align-items-center">
        <ion-icon name="person-circle-outline" style="font-size: 25px; margin-right: 10px;"></ion-icon>
        <select id="brand" name="customer_id[]" class="form-control flex-grow-1" style="font-size: 16px; padding: 8px;" required>
            <option value="">Select Customer</option>
            <?php foreach ($customers as $customer): ?>
                <option value="<?php echo htmlspecialchars($customer['id']); ?>"
                    <?php echo (strcasecmp($customer['name'], "walking customer") === 0) ? "selected" : ""; ?>>
                    <?php echo htmlspecialchars($customer['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <input type="hidden" name="user_id[]" value="<?php echo $_SESSION['id']; ?>">
        <button type="button" id="openModalBtn" class="btn btn-success ms-2" style="padding: 5px 10px;">
            <ion-icon name="add-circle-outline"></ion-icon>
        </button>
    </div>

    <div class="col-lg-3 col-md-6 col-sm-12 mb-2 d-flex align-items-center">
        <ion-icon name="calendar-outline" style="font-size: 25px; margin-right: 10px;"></ion-icon>
        <input type="date" class="form-control" name="date_sale[]" id="date" style="font-size: 14px; padding: 5px;" required>
    </div>

 <div class="col-lg-4 col-md-12 col-sm-12 mb-2 d-flex align-items-center">
  <button 
    type="button" 
    class="btn btn-dark d-flex align-items-center gap-2"
    onclick="location.href='list_pos.php'">
    <ion-icon name="arrow-back-outline"></ion-icon>
    Back to List
  </button>
</div>

    <script>
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('date').value = today;
    </script>
</div>



<div class="container-fullscreen">
    <div class="mein">
        <table class="table" id="tb">
            <thead style="background-color: rgb(210,214,223);">
                <tr>
                    <th style="width:18%;">Product</th>
                    <th style="width:15%;">Quantity</th>
                    <th style="width:10%;">Unit</th>
                    <th style="width:15%;">Price</th>
                    <th style="display:none;">Sale Tax</th>
                    <th style="width:14%;">Subtotal</th>
                    <th style="width:6%;">AC</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <div class="tbl">
        <table class="table">
            <thead style="background-color: rgb(210,214,223);">
                <tr>
                    <th>Total Items</th>
                    <th><input id="total-qty" type="text" placeholder="0.00" readonly style="border:none; background:transparent;"></th>
                    <th>Subtotal</th>
                    <th><input id="main_subtotal" placeholder="0.00" style="border:none; background:transparent; border-radius:10px;"></th>
                    <td style="display:none;">Total Tax</td>
                    <td style="display:none;"><input id="total-tax" readonly style="width: 90px; background-color: rgb(66,66,66); border:none; border-radius:10px; color:white;" class="net_sale"></td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="display:none;">Total (With Tax):</td>
                    <td style="display:none;"><input class="main_total form-control" readonly style="border:none; background:transparent; border-radius:10px;"></td>
                    <td>DISCOUNT</td>
                    <td><input id="discount" name="discount[]" placeholder="0.00" style="width: 100px; height:2.4em; border:2px solid #000; border-radius:10px; color:black;" class="net_sale"></td>
                     <td>
                           <?php
                                            // Fetch data from the 'banks' table
                                            $stmt = $conn->prepare("SELECT id, bank_name FROM banks");
                                            $stmt->execute();
                                            $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                            ?>
                        <select class="form-control" name="bank_id" id="bankSelect" required>
                            <?php foreach ($banks as $bank): ?>
                                <option value="<?= htmlspecialchars($bank['id']) ?>"><?= htmlspecialchars($bank['bank_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td style="display:none;">Order Tax(%)</td>
                    <td><input id="order_tax" value="0" name="order_tax[]" style="width: 100px; height:2.4em; display:none; border:none; border-radius:10px; color:black;" class="net_sale"></td>
                </tr>
         
                <tr style="background-color: rgb(210,214,223)">
                    <th>Cash</th>
                    <th><input type="text" id="net_cash" name="net_cash[]"  placeholder="Net Cash" style="border:2px solid #000; border-radius:10px; width: 100px; height:2.4em;" class="net_sale"></th>
                    <th>Change / Bill</th>
                    <th><input type="text" id="remaining_amount" placeholder="0.00" style="border:none; background:transparent; width:57px;" class="remaining_amount"></th>
                </tr>
            </tbody>
        </table>
        <div class="buttons-row">
            <button id="holdButton"><strong>Credit Sale</strong></button>
            <button type="submit" id="submitBtn"><strong>Cash</strong></button>
            <button type="button" id="installmentBtn" style="display:none;"><strong>Installment</strong></button>
        </div>
    </div>
</div>
            </div>
        </div>
    </div>
    </form>












    <!-- Installment & Guarantor Modal -->
    <div id="installmentModal"
        style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%);
            background:#fff; padding:25px; border-radius:12px; box-shadow:0 4px 20px rgba(0,0,0,0.2); 
            z-index:999; width:95%; max-width:1200px; height:90vh; overflow-y:auto; font-family:Arial, sans-serif;">
        <h3 style="margin-bottom:15px; text-align:center; color:#444;">💳 Installment Plan & Guarantors</h3>
        <p>Total Amount: <strong><span id="installment_total"></span></strong></p>

        <!-- Installment Inputs -->
        <div style="display:flex; gap:15px; margin-bottom:15px;">
            <div style="flex:1;">
                <label>Advance Payment</label>
                <input type="number" id="advance_payment" value="0" min="0" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc;">
            </div>
            <div style="flex:1;">
                <label>No. of Installments</label>
                <input type="number" id="num_installments" value="1" min="1" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc;">
            </div>
            <div style="flex:1;">
                <label>Duration (Months)</label>
                <input type="number" id="installment_duration" value="1" min="1" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc;">
            </div>
        </div>

        <div id="installment_schedule" style="margin:15px 0; border:1px solid #ddd; border-radius:6px; padding:10px;"></div>

        <!-- Guarantors Section -->
        <div style="display:flex; gap:20px; flex-wrap:wrap;">
            <!-- Guarantor 1 -->
            <fieldset style="flex:1; min-width:450px; padding:15px; border:1px solid #ddd; border-radius:6px;">
                <legend>Guarantor 1</legend>
                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Name*</label>
                        <input type="text" name="guarantor1_name" required style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>Father's Name*</label>
                        <input type="text" name="guarantor1_father" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Email</label>
                        <input type="email" name="guarantor1_email" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>Phone 1*</label>
                        <input type="text" name="guarantor1_phone1" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Phone 2</label>
                        <input type="text" name="guarantor1_phone2" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>CNIC*</label>
                        <input type="text" name="guarantor1_cnic" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>CNIC Front</label>
                        <input type="file" name="guarantor1_cnic_front" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>CNIC Back</label>
                        <input type="file" name="guarantor1_cnic_back" style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Address*</label>
                        <textarea name="guarantor1_address" required style="width:100%;"></textarea>
                    </div>
                    <div style="flex:1;">
                        <label>Note</label>
                        <textarea name="guarantor1_note" style="width:100%;"></textarea>
                    </div>
                </div>
                <label><input type="checkbox" name="guarantor1_granted" value="1"> Granted</label>
            </fieldset>

            <!-- Guarantor 2 -->
            <fieldset style="flex:1; min-width:450px; padding:15px; border:1px solid #ddd; border-radius:6px;">
                <legend>Guarantor 2</legend>
                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Name*</label>
                        <input type="text" name="guarantor2_name" required style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>Father's Name*</label>
                        <input type="text" name="guarantor2_father" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Email</label>
                        <input type="email" name="guarantor2_email" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>Phone 1*</label>
                        <input type="text" name="guarantor2_phone1" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Phone 2</label>
                        <input type="text" name="guarantor2_phone2" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>CNIC*</label>
                        <input type="text" name="guarantor2_cnic" required style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>CNIC Front</label>
                        <input type="file" name="guarantor2_cnic_front" style="width:100%;">
                    </div>
                    <div style="flex:1;">
                        <label>CNIC Back</label>
                        <input type="file" name="guarantor2_cnic_back" style="width:100%;">
                    </div>
                </div>

                <div style="display:flex; gap:15px; margin-bottom:10px;">
                    <div style="flex:1;">
                        <label>Address*</label>
                        <textarea name="guarantor2_address" required style="width:100%;"></textarea>
                    </div>
                    <div style="flex:1;">
                        <label>Note</label>
                        <textarea name="guarantor2_note" style="width:100%;"></textarea>
                    </div>
                </div>
                <label><input type="checkbox" name="guarantor2_granted" value="1"> Granted</label>
            </fieldset>
        </div>

        <div style="text-align:right; margin-top:15px;">
            <button type="button" id="saveInstallment" style="background:#2ecc71; color:#fff; border:none; padding:10px 20px; border-radius:6px; cursor:pointer;">Save</button>
            <button type="button" id="closeInstallment" style="background:#e74c3c; color:#fff; border:none; padding:10px 20px; border-radius:6px; cursor:pointer; margin-left:5px;">Close</button>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const installmentBtn = document.getElementById('installmentBtn');
            const cashBtn = document.getElementById('submitBtn');
            const creditBtn = document.getElementById('holdButton');
            const saleForm = document.getElementById('saleForm');
            const installmentModal = document.getElementById('installmentModal');
            const installmentTotal = document.getElementById('installment_total');
            const advancePayment = document.getElementById('advance_payment');
            const numInstallments = document.getElementById('num_installments');
            const installmentDuration = document.getElementById('installment_duration');
            const installmentSchedule = document.getElementById('installment_schedule');
            const saveInstallment = document.getElementById('saveInstallment');
            const closeInstallment = document.getElementById('closeInstallment');

            let totalAmount = 0;
            let installmentsData = [];

            installmentBtn.addEventListener('click', function() {
                totalAmount = parseFloat(document.getElementById('main_subtotal').value) || 0;
                if (totalAmount <= 0) {
                    alert("Please add products first.");
                    return;
                }
                installmentTotal.innerText = totalAmount.toFixed(2);
                advancePayment.value = 0;
                numInstallments.value = 1;
                installmentDuration.value = 1;
                renderSchedule();
                installmentModal.style.display = 'block';
            });

            closeInstallment.addEventListener('click', () => {
                installmentModal.style.display = 'none';
            });

            function renderSchedule() {
                const advance = parseFloat(advancePayment.value) || 0;
                const count = parseInt(numInstallments.value) || 1;
                const remaining = totalAmount - advance;
                const perInstallment = (remaining / count).toFixed(2);
                const today = new Date();
                installmentsData = [];
                let html = `<table style="width:100%; border-collapse:collapse; font-size:14px; text-align:center;">
            <thead><tr style="background:#f4f4f4;">
                <th style="border:1px solid #ddd;padding:8px;">#</th>
                <th style="border:1px solid #ddd;padding:8px;">Due Date</th>
                <th style="border:1px solid #ddd;padding:8px;">Amount</th>
            </tr></thead><tbody>`;
                for (let i = 1; i <= count; i++) {
                    let due = new Date(today);
                    due.setDate(1);
                    due.setMonth(today.getMonth() + i);
                    const dueStr = due.toISOString().split('T')[0];
                    html += `<tr><td>${i}</td><td>${dueStr}</td><td>${perInstallment}</td></tr>`;
                    installmentsData.push({
                        installment_no: i,
                        amount: perInstallment,
                        due_date: dueStr
                    });
                }
                html += '</tbody></table>';
                installmentSchedule.innerHTML = html;
            }
            advancePayment.addEventListener('input', renderSchedule);
            numInstallments.addEventListener('input', () => {
                installmentDuration.value = numInstallments.value;
                renderSchedule();
            });
            installmentDuration.addEventListener('input', renderSchedule);

            function appendGuarantors(form) {
                ['guarantor1', 'guarantor2'].forEach(g => {
                    const granted = document.querySelector(`input[name="${g}_granted"]`)?.checked ? 1 : 0;
                    let input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = `${g}_granted`;
                    input.value = granted;
                    form.appendChild(input);

                    ['name', 'father', 'email', 'phone1', 'phone2', 'address', 'cnic', 'note'].forEach(f => {
                        const el = document.querySelector(`[name="${g}_${f}"]`);
                        if (el) {
                            let i = document.createElement('input');
                            i.type = 'hidden';
                            i.name = `${g}_${f}`;
                            i.value = el.value;
                            form.appendChild(i);
                        }
                    });

                    ['cnic_front', 'cnic_back'].forEach(f => {
                        const file = document.querySelector(`[name="${g}_${f}"]`);
                        if (file && file.files.length > 0) form.appendChild(file.cloneNode(true));
                    });
                });
            }

            function submitSale(button, isCredit = false, withInstallments = false) {
                button.disabled = true;
                button.innerHTML = "<strong>Please wait...</strong>";
                if (isCredit) {
                    const netCash = document.getElementById('net_cash');
                    if (netCash) netCash.value = "";
                }
                if (withInstallments) {
                    document.querySelectorAll('.installment_input').forEach(el => el.remove());
                    const advInput = document.createElement('input');
                    advInput.type = 'hidden';
                    advInput.name = 'advance_payment';
                    advInput.value = parseFloat(advancePayment.value) || 0;
                    advInput.classList.add('installment_input');
                    saleForm.appendChild(advInput);

                    installmentsData.forEach(inst => {
                        let amtInput = document.createElement('input');
                        amtInput.type = 'hidden';
                        amtInput.name = 'installment_amount[]';
                        amtInput.value = inst.amount;
                        amtInput.classList.add('installment_input');
                        saleForm.appendChild(amtInput);
                        let dateInput = document.createElement('input');
                        dateInput.type = 'hidden';
                        dateInput.name = 'installment_due_date[]';
                        dateInput.value = inst.due_date;
                        dateInput.classList.add('installment_input');
                        saleForm.appendChild(dateInput);
                    });

                    appendGuarantors(saleForm);
                }

                const formData = new FormData(saleForm);
                fetch('insert_sale.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(res => res.text())
                    .then(data => {
                        if (data.trim() == 'success') window.location.href = "print/customer_bill.php";
                        else {
                            alert(data);
                            button.disabled = false;
                            button.innerHTML = isCredit ? 'Credit Sale' : (withInstallments ? 'Installment' : 'Cash');
                        }
                    })
                    .catch(err => {
                        alert("Request failed: " + err);
                        button.disabled = false;
                        button.innerHTML = isCredit ? 'Credit Sale' : (withInstallments ? 'Installment' : 'Cash');
                    });
            }

            if (creditBtn && saleForm) creditBtn.addEventListener('click', e => {
                e.preventDefault();
                submitSale(creditBtn, true);
            });
            if (saleForm && cashBtn) saleForm.addEventListener('submit', e => {
                e.preventDefault();
                submitSale(cashBtn, false);
            });
            saveInstallment.addEventListener('click', () => {
                installmentModal.style.display = 'none';
                submitSale(saveInstallment, false, true);
            });

        });
    </script>
    <script>
        window.addEventListener('pageshow', function(event) {
            if (event.persisted) {
                window.location.reload();
            }
        });
    </script>


    <!-- <script>
    document.getElementById('submitBtn').addEventListener('click', function() {
      var total = parseFloat(document.getElementById('main_total').value);
      var discount = parseFloat(document.getElementById('discount').value) || 0;
      var orderTax = parseFloat(document.getElementById('order_tax').value) || 0;
      var netCash = (total + orderTax) - discount;

      document.getElementById('net_cash').value = netCash.toFixed(2); /
    });

    document.getElementById('holdButton').addEventListener('click', function() {
      document.getElementById('net_cash').value = "0"; 
    });
  </script> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

    <audio id="beep-add" src="beep/scanner-beeps.wav" preload="auto"></audio>
    <audio id="beep-remove" src="beep/beep-remove.mp3" preload="auto"></audio>
    <audio id="beep-error" src="beep/beep-error.mp3" preload="auto"></audio>
<script>
$(document).ready(function () {
    let loading = false;
    let offset = 0;
    const limit = 30;

    const scrollContainer = document.querySelector('.col-lg-7.col-md-7 main');

    // Load first set
    loadProducts();

    function loadProducts(callback) {
        if (loading) return;
        loading = true;

        $.ajax({
            url: 'load_products.php',
            type: 'GET',
            data: {
                offset: offset,
                limit: limit,
                category: $('#category-filter').val(),
                brand: $('#brand-filter').val(),
                search: $('#product-search').val()
            },
            dataType: 'html',
            success: function (response) {
                if ($.trim(response) === '') {
                    $('#productCardsContainer').append('<div class="text-center text-muted mt-2">No more products.</div>');
                    return;
                }
                $('#productCardsContainer').append(response);
                offset += limit;
                loading = false;
                if (callback) callback();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log('AJAX Error:', textStatus, errorThrown);
                loading = false;
            }
        });
    }

    // ✅ Scroll listener for that container
    scrollContainer.addEventListener('scroll', function () {
        const nearBottom = scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight - 50;
        if (nearBottom && !loading) {
            loadProducts();
        }
    });





    function attachTooltip() {
        $('.product-card').hover(function() {
            const productName = $(this).data('product-name');
            $.ajax({
                url: 'getProductrecord_stock.php',
                type: 'GET',
                data: { product_name: productName },
                dataType: 'json',
                success: function(productData) {
                    if (productData && !productData.error) {
                        $(this).attr('title', productData.tooltip);
                    } else {
                        $(this).attr('title', 'Stock data not available');
                    }
                }.bind(this),
                error: function() { $(this).attr('title', 'Error fetching stock data'); }.bind(this)
            });
        });
    }

    function debounce(func, wait) {
        let timeout;
        return function() {
            clearTimeout(timeout);
            timeout = setTimeout(func, wait);
        };
    }

    function addProductToCart(productId) {
        $('#beep-add')[0].play();

        $.ajax({
            url: 'getProductrecord.php',
            type: 'GET',
            data: { product_id: productId },
            dataType: 'json',
            success: function(productData) {
                if (!productData || productData.error) {
                    $('#beep-error')[0].play();
                    toastr.error('Product not found or error occurred.');
                    return;
                }

                let uniqueKey = productData.product_id + '_' + productData.size_id + '_' + productData.color_id;
                let availableStock = parseInt(productData.current_stock_qty, 10);
                if (availableStock <= 0) {
                    $('#beep-error')[0].play();
                    toastr.error('Stock is unavailable!');
                    return;
                }

                let existingRow = $('#tb').find(`.uniqueKey[value="${uniqueKey}"]`).closest('tr');
                if (existingRow.length > 0) {
                    let qtyField = existingRow.find('.sale_qty');
                    let currentQty = parseInt(qtyField.val(), 10) || 0;
                    if (currentQty + 1 > availableStock) {
                        $('#beep-error')[0].play();
                        toastr.warning('Quantity exceeds stock!');
                        return;
                    }
                    qtyField.val(currentQty + 1);
                    calculateRowTotal(existingRow);
                } else {
                    let newRow = `
<tr style="background-color:#daede5;">
    <td><input type="text" class="form-control productName" name="product_name[]" style="width:11em;" value="${productData.product_name}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control producsize" name="size[]" value="${productData.size}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control availableStock" value="${productData.current_stock_qty}" readonly></td>
    <td>
        <div style="display:flex; align-items:center; gap:2px; max-width:120px; border:1px solid #ccc; border-radius:6px; overflow:hidden;">
            <button type="button" class="btn-decrement" style="flex:1; border:none; background:#f0f0f0; cursor:pointer; font-weight:bold; font-size:16px;">-</button>
            <input type="text" name="sale_qty[]" class="form-control sale_qty" value="1" required style="flex:2; text-align:center; border:none; outline:none; font-size:14px; padding:4px 0;">
            <button type="button" class="btn-increment" style="flex:1; border:none; background:#f0f0f0; cursor:pointer; font-weight:bold; font-size:16px;">+</button>
        </div>
    </td>
    <td><input type="text" class="form-control productUnit mt-1" name="unit[]" value="${productData.actual_name}" readonly style="border:none; background:transparent; text-align:center; font-size:13px; color:#555;"></td>
    <td><input type="text" class="form-control saleprice" name="price[]" value="${productData.sale_price}" required data-unit-price="${productData.sale_price}"></td>
    <td style="display:none;"><input type="text" class="form-control saleTax" name="sale_tax[]" value="0" readonly></td>
    <td><input type="text" name="subtotal_amount[]" class="form-control subtotal_amount" placeholder="Subtotal" readonly></td>
    <td style="display:none;"><input type="text" name="total_amount[]" class="form-control total_amount" placeholder="Total" readonly></td>
    <td style="display:none;"><input type="text" class="form-control productCategory" name="category[]" value="${productData.category_id}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control uniqueKey" value="${uniqueKey}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control productId" name="product_id[]" value="${productData.product_id}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control colorId" name="color_id[]" value="${productData.color_id}" readonly></td>
    <td style="display:none;"><input type="text" class="form-control sizeId" name="size_id[]" value="${productData.size_id}" readonly></td>
    <td><a href='javascript:void(0);' class='remove'><ion-icon name="trash-outline"></ion-icon></a></td>
</tr>`;
                    $('#tb').append(newRow);
                    calculateRowTotal($('#tb').find(`.uniqueKey[value="${uniqueKey}"]`).closest('tr'));
                }
                calculateTotals();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("AJAX Error:", textStatus, errorThrown);
            }
        });
    }

$('#product-search').on('input', debounce(function() {
    let searchVal = $('#product-search').val().trim().toLowerCase();
    if (!searchVal) return;

    $('#productCardsContainer').empty();
    offset = 0;

    loadProducts(function() {
        let exactMatchCard = null;

        $('.product-card').each(function() {
            let productName = String($(this).data('product-name') || '').toLowerCase();
            let productBarcode = String($(this).data('product-barcode') || '').toLowerCase();
            if (productName === searchVal || productBarcode === searchVal) {
                exactMatchCard = $(this);
                return false; 
            }
        });

        if (exactMatchCard) {
            let productId = exactMatchCard.data('product-code');
            addProductToCart(productId);

            $('#product-search').val('').focus();
        }
    });
}, 200)); 

$('#product-search').on('keypress', function(e) {
    if (e.key === "Enter") {
        e.preventDefault();
        $(this).trigger('input');
    }
});

// Filters
$('#category-filter, #brand-filter').on('change', function() {
    $('#productCardsContainer').empty();
    offset = 0;
    loadProducts();
});

    $(document).on('click', '.add-to-cart', function() {
        let productId = $(this).data('product-code');
        addProductToCart(productId);
    });

    $(document).on('click', '.btn-increment', function() {
        let row = $(this).closest('tr');
        let qtyInput = row.find('.sale_qty');
        let stock = parseInt(row.find('.availableStock').val(), 10);
        let qty = parseInt(qtyInput.val()) || 0;
        if (qty < stock) qtyInput.val(qty + 1);
        else toastr.warning('Maximum stock reached!');
        calculateRowTotal(row);
        calculateTotals();
    });

    $(document).on('click', '.btn-decrement', function() {
        let row = $(this).closest('tr');
        let qtyInput = row.find('.sale_qty');
        let qty = parseInt(qtyInput.val()) || 0;
        if (qty > 1) qtyInput.val(qty - 1);
        calculateRowTotal(row);
        calculateTotals();
    });

    $(document).on('input', '.sale_qty', function() {
        let row = $(this).closest('tr');
        let qty = parseInt($(this).val()) || 1;
        let stock = parseInt(row.find('.availableStock').val(), 10);
        if (qty > stock) { $(this).val(stock); toastr.warning('Quantity adjusted to available stock!'); }
        else if (qty < 1) $(this).val(1);
        calculateRowTotal(row);
        calculateTotals();
    });

    // Remove item
    $(document).on('click', '.remove', function() {
        $(this).closest('tr').remove();
        calculateTotals();
        $('#beep-remove')[0].play();
        toastr.info('Item removed!');
    });

    $('.cancel-button').on('click', function() {
        $('#tb').empty();
        calculateTotals();
        $('#beep-remove')[0].play();
        toastr.info('All items removed!');
    });

    // Totals calculation
    let userChangedNetCash = false;

    function calculateRowTotal(row) {
        let saleQty = parseFloat(row.find('.sale_qty').val()) || 0;
        let price = parseFloat(row.find('.saleprice').val()) || 0;
        let taxRate = parseFloat(row.find('.saleTax').val()) || 0;
        let subtotal = saleQty * price;
        let taxAmount = (subtotal * taxRate) / 100;
        row.find('.subtotal_amount').val(subtotal.toFixed(2));
        row.find('.total_amount').val((subtotal + taxAmount).toFixed(2));
    }

    function calculateTotals() {
        let mainSubtotal = 0, totalTaxAmount = 0, mainTotal = 0, totalQty = 0;
        $('#tb tr').each(function() {
            let row = $(this);
            let saleQty = parseFloat(row.find('.sale_qty').val()) || 0;
            let price = parseFloat(row.find('.saleprice').val()) || 0;
            let taxRate = parseFloat(row.find('.saleTax').val()) || 0;
            let subtotal = saleQty * price;
            let taxAmount = (subtotal * taxRate) / 100;
            row.find('.subtotal_amount').val(subtotal.toFixed(2));
            row.find('.total_amount').val((subtotal + taxAmount).toFixed(2));
            mainSubtotal += subtotal;
            totalTaxAmount += taxAmount;
            mainTotal += (subtotal + taxAmount);
            totalQty += saleQty;
        });

        $('#main_subtotal').val(mainSubtotal.toFixed(2));
        $('#total-tax').val(totalTaxAmount.toFixed(2));
        $('.main_total').val(mainTotal.toFixed(2));
        $('#total-qty').val(totalQty);

        let discount = parseFloat($('#discount').val()) || 0;
        let totalAfterDiscount = mainTotal - discount;
        if (!userChangedNetCash) $('#net_cash').val(totalAfterDiscount.toFixed(2));

        let paidAmount = parseFloat($('#net_cash').val()) || 0;
        $('.remaining_amount').val((totalAfterDiscount - paidAmount).toFixed(2));
    }

    $('#net_cash').on('input', function() { userChangedNetCash = true; calculateTotals(); });
    $('#discount').on('input', function() { userChangedNetCash = false; calculateTotals(); });
    $(document).on('input', '.sale_qty, .saleprice', function() { calculateRowTotal($(this).closest('tr')); calculateTotals(); });

    // Initial load
    loadProducts();
    attachTooltip();
    calculateTotals();
});
</script>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous">
    </script>
</body>

</html>