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

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

<?php
$sql = "SELECT * FROM contacts WHERE type = 'supplier'";
try {
    $query = $conn->prepare($sql);
    $query->execute();
    $space = $query->fetchAll();
} catch (Exception $ex) {
    echo ($ex->getMessage());
}
?>
<?php
$customerQuery = 'SELECT id, name FROM contacts WHERE  business_id = 3 ORDER BY id';
$customerStmt = $conn->query($customerQuery);
$customers = $customerStmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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>Add Sale</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">
    <!-- Chosen CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Chosen JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
    <!-- Custom Styles -->
    <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>

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

        .chosen-container {
            height: 40px;
            /* Adjust the height of the selected box */
        }

        .chosen-container .chosen-single {
            height: 40px;
            /* Adjust the height of the selected box */
            line-height: 38px;
            /* Align text vertically */
            border-radius: 0px;
        }

        .chosen-container .chosen-drop {
            max-height: 200px;
            /* Adjust the max height of the dropdown */
            overflow-y: auto;
            /* Add scroll if content exceeds max-height */
        }

        .chosen-container .chosen-results {
            padding: 0;
            /* Remove default padding */
        }

        .file-input-wrapper {
            display: flex;
            align-items: center;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            border-radius: 0px;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-input-wrapper .form-control {
            margin-right: 0;
            /* Remove margin to align properly */
        }

        .file-input-wrapper .btn-browse {
            margin-left: -1px;
            /* Adjust to align with the input field */
            border-radius: 0;
            height: 2.4em;
            width: 11em;
        }

        input[type="text"],
        input[type="number"],
        input[type="date"] {
            border-radius: 0px;
            height: 2.3em;
        }

        input[type="search"] {
            border-radius: 0px;
            height: 3em;
        }

        table .th {
            font-size: 12px;
            font-weight: bold;

        }

        table .td {
            width: 8em;
            height: 1.7em;
            border: 1px solid #c5c6c7;
        }

        tbody {
            background-color: #fff;
        }

        .input-group-text {
            background: #f8f9fa;
            /* Optional: to match the input background */
            border-right: 1px solid #ced4da;
            /* Optional: to match the input border */
        }

        .table-container {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        #product-table {
            min-width: 1000px;
            /* Set this based on your column widths */
        }

        #product-table th,
        #product-table td {
            white-space: nowrap;
            /* Prevents text wrapping */
            text-align: center;
            /* Centers the text */
        }

        #product-table th:nth-child(1),
        #product-table td:nth-child(1) {
            width: 5%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(2),
        #product-table td:nth-child(2) {
            width: 30%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(3),
        #product-table td:nth-child(3) {
            width: 17%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(4),
        #product-table td:nth-child(4) {
            width: 8%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(5),
        #product-table td:nth-child(5) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(6),
        #product-table td:nth-child(6) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(7),
        #product-table td:nth-child(7) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(8),
        #product-table td:nth-child(8) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(9),
        #product-table td:nth-child(9) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(10),
        #product-table td:nth-child(10) {
            width: 20%;
            /* Adjust width as needed */
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
        }

        th,
        td {
            text-align: center;
            vertical-align: middle;
            padding: 4px;
            /* Reduced padding to save space */
            font-size: 12px;
            /* Slightly smaller font size */
            text-transform: capitalize;
        }

        th {
            white-space: nowrap;
            /* Prevent header text from wrapping */
        }

        .table th {
            border-color: #dee2e6;
        }

        .table-bordered th,
        .table-bordered td {
            border: 1px solid #dee2e6;
        }

        .table input {
            width: 100%;
            padding: 3px;
            /* Reduced padding in input fields */
            box-sizing: border-box;
            font-size: 0.875rem;
        }

        @media (max-width: 768px) {

            .table th,
            .table td {
                font-size: 0.75rem;
                padding: 3px;
            }
        }
    </style>
    <script>
        $(document).ready(function() {
            $('#supplier').chosen({
                width: '100%', // Adjust width as needed
                placeholder_text_single: 'Select Supplier',
                no_results_text: 'No results matched'
            });
        });
    </script>
    <!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function() {
            $('#file-input').on('change', function() {
                var fileName = $(this).val().split('\\').pop();
                $(this).siblings('input[type="text"]').val(fileName);
            });
        });
    </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 --><!-- The Modal -->
         
    <div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog" aria-labelledby="addUnitModalLabel" aria-hidden="true">
        <div class="modal-dialog">
        <div class="modal-content">
          <!-- Modal Header -->
          <div class="modal-header">
            <h4 class="modal-title">Add Customer</h4>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>

          <!-- Modal body -->
          <form method="POST" action="submit_contact_customer.php">
            <div class="modal-body">
                <div class="row">
                    <div class="col-lg-6 mt-2" style="display: none;">
                        <div class="form-group">
                            <label for="" class="label-control">Contact type:*</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="type" value="customer" placeholder="Please Select" readonly>
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Name:*</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="name" placeholder="Enter Name" id="">
                        </div>
                    </div>
                   
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Contact ID:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="contact_id" placeholder="Contact ID" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Tax number:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="tax_number" placeholder="Tax number" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Opening Balance:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="opening_balance" placeholder="0" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Pay term:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="pay_term_type" placeholder="Pay term" id="">
                        </div>
                    </div>
                    <!-- <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Customer Group:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="" placeholder="None" id="">
                        </div>
                    </div> -->
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Credit Limit:</label>
                            <input style="border-radius: 0px;" type="number" class="form-control" name="credit_limit" placeholder="Credit Limit" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Email:</label>
                            <input style="border-radius: 0px;" type="email" class="form-control" name="email" placeholder="Email" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Mobile:*</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="mobile" placeholder="Mobile Number:*" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Alternate contact number:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="alternate_number" placeholder="Alternate contact number" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Landline:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="landline" placeholder="Landline" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">City:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="city" placeholder="City" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">State:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="state" placeholder="State" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Country:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="country" placeholder="Country" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Landmark:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="landmark" placeholder="Landmark" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Custom Field 1:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="custom_field1" placeholder="Custom Field 1" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Custom Field 2:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="custom_field2" placeholder="Custom Field 2" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Custom Field 3:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="custom_field3" placeholder="Custom Field 3" id="">
                        </div>
                    </div>
                    <div class="col-lg-6 mt-2">
                        <div class="form-group">
                            <label for="" class="label-control">Custom Field 4:</label>
                            <input style="border-radius: 0px;" type="text" class="form-control" name="custom_field4" placeholder="Custom Field 4" id="">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button class="btn btn-primary" name="submit_popup">Submit</button>
              <button
                type="button"
                class="btn btn-danger"
                data-bs-dismiss="modal"
              >
                Close
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!----pop customer add 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="add_sale.php">Sale</a> > Add Sale

                                    </h4>
                                </div>
                            </div>
                            <div class="iq-card-body" style="overflow:auto;">
                                <form id="searchForm" method="POST" enctype="multipart/form-data">
                                    <div class="row">
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                            <label for="" class="label-control">Customer:*</label>

                                            <div class="input-group">
                                                <select id="customer" name="customer_id" class="form-control">
                                                    <option selected disabled>Select Customer</option>
                                                    <?php foreach ($customers as $customer): ?>
                                                        <option value="<?php echo htmlspecialchars($customer['id']); ?>">
                                                            <?php echo htmlspecialchars($customer['name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <div class="input-group-append">
                                                <button class="btn btn-outline-secondary" type="button" data-toggle="modal" data-target="#addUnitModal">
    <i class="fa fa-plus"></i>
</button>
                                                </div>
        </div>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <label for="" class="label-control">Pay term: </label>

                                            <div class="input-group input-group-sm">
                                                <input type="number" class="form-control" id="pay-term" name="pay_term" placeholder="Pay term">
                                                <select class="form-control" name="pay_term_status" id="pay-term-status">
                                                    <option value="">Please Select</option>
                                                    <option value="Months">Months</option>
                                                    <option value="Days">Days</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label for="" class="label-control">Sale Date:</label>
                                                <input type="date" class="form-control" name="date_sale"
                                                    placeholder="Business Name" id="date-sale">
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label for="" class="label-control">SaleMan:</label>
                                                <input type="text" class="form-control" name="saleman"
                                                    placeholder="SaleMan" id="saleman">
                                            </div>
                                        </div>
                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label for="" class="label-control">Status:*</label>
                                                <select class="form-control" id="sale-status" name="sale_status">
                                                    <option>Final</option>
                                                    <option>Draft</option>
                                                    <option>Quotation</option>
                                                </select>
                                            </div>
                                        </div>


                                    </div>
                            </div>
                        </div>
                        <div class="col-sm-12 iq-card">
                            <div class="">
                                <div class="iq-card-body">
                                    <form action="" id="searchForm">
                                        <div class="container mt-5">
                                            <div class="row">
                                                <div class="col-lg-5 mx-auto position-relative">
                                                    <div class="input-group">
                                                        <div class="input-group-prepend">
                                                            <span class="input-group-text" style="border: 1px solid gray;">
                                                                <ion-icon name="search-outline"></ion-icon>
                                                            </span>
                                                        </div>
                                                        <input type="search" id="product-search" class="form-control" placeholder="Enter Product name / SKU">
                                                    </div>
                                                    <div id="product-list" class="dropdown-menu w-100" style="max-height: 200px; overflow-y: auto; display: none; position: absolute; top: 100%; margin-top: 3.5em; left: 0;">
                                                        <!-- Dropdown items will be injected here -->
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                </div>
                                <div class="container mt-5">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-bordered mt-3" id="product-table">
                                            <thead>
                                                <tr>
                                                    <th style="width: 3%;">#</th>
                                                    <th style="width: 11%;">Product Name</th>
                                                    <th style="width: 20%;">Quantity</th>
                                                    <th style="width: 20%;">Price</th>
                                                    <th style="width: 12%;">Subtotal</th>
                                                    <th style="width: 3%;"><ion-icon name="trash-outline"></ion-icon>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>

                            </div>
                            <hr>
                            <div style="display:inline; float:inline-end; margin-bottom:10px;">
                                <h6><span>Total Items:</span> <span id="total-items">0</span></h6>
                                <h6><span>Net Total Amount:</span> <span id="net-total-amount">0.00 ₨</span></h6>
                            </div>

                        </div>
                    </div>
                    <div class="col-sm-12 iq-card">
                        <div class="">
                            <div class="iq-card-body">

                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-5">
                                        <label for="" class="control-label">Discount Type:</label>
                                        <select name="discount_type" class="form-control" id="discount-type">
                                            <option value="None">None</option>
                                            <option value="Fixed">Fixed</option>
                                            <option value="Percentage">Percentage</option>
                                        </select>
                                    </div>
                                    <div class="col-lg-5">
                                        <label for="" class="control-label">Discount Amount:</label>
                                        <input type="text" name="discount" class="form-control" placeholder="0.00" id="discount-amount">
                                    </div>
                                    <div class="col-lg-2">
                                        <h6 class="mt-5"><strong>Discount:</strong> (-)<span id="applied-discount">0.00 Rs</span></h6>
                                    </div>
                                </div>
                                <hr>
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-5">
                                        <label for="" class="control-label">Purchase Tax:</label>
                                        <select name="" class="form-control" id="">
                                            <option value="">None</option>
                                        </select>
                                    </div>
                                    <div class="col-lg-4">
                                    </div>
                                    <div class="col-lg-3">
                                        <h6 class="mt-5" style="display:inline;float:inline-end;"><strong>Purchase
                                                Tax:</strong>(-)0.00 Rs</h6>
                                    </div>
                                </div>
                                <hr>
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-4">
                                        <label for="" class="control-label">Shipping Details:</label>
                                        <input type="text" name="shipping_detail" class="form-control"
                                            placeholder="Enter Shipping Details" id="shipping-detail">
                                    </div>

                                    <div class="col-lg-4">
                                        <label for="" class="control-label">Shipping Address:</label>
                                        <input type="text" name="shipping_address" class="form-control"
                                            placeholder="Enter Shipping Address" id="shipping-address">
                                    </div>

                                    <div class="col-lg-4">
                                        <label for="" class="control-label">Additional Shipping charges:</label>
                                        <input type="text" name="shipping_charges" class="form-control" placeholder="0.00" id="shipping-charges">
                                    </div>

                                    <div class="col-lg-4 mt-5">
                                        <label for="" class="control-label">Shipping Status:</label>
                                        <select name="shipping_status" class="form-control" id="shipping-status">
                                            <option value="">None</option>
                                        </select>
                                    </div>

                                    <div class="col-lg-4 mt-5">
                                        <label for="" class="control-label">Delivered To:</label>
                                        <input type="text" name="delivered_to" class="form-control"
                                            placeholder="Enter Delivered To" id="delivered-to">
                                    </div>


                                </div>
                                <hr>
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-5">
                                    </div>
                                    <div class="col-lg-4">
                                    </div>
                                    <div class="col-lg-3">
                                        <h6><strong>Total Payable:</strong> <span id="sale-total">0.00 Rs</span></h6>
                                    </div>
                                </div>

                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                    <div class="col-lg-12">
                                        Sell note
                                        <textarea name="" class="form-control" id=""></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <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">Add Payment
                                    </h4>
                                </div>
                            </div>
                            <div class="iq-card-body" style="overflow:auto;">
                                <div class="row">
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="" class="label-control">Amount:*</label>
                                            <input type="number" class="form-control" name="receive_amount" placeholder="0.00" id="receive_amount">

                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="form-group">
                                            <label for="" class="label-control">Payment Method:</label>
                                            <select name="payment_method" class="form-control" id="payment_method">
                                                <option>Please Select</option>
                                                <option>Cash</option>
                                                <option>Card</option>
                                                <option>Cheque</option>
                                                <option>Bank Transfer</option>
                                                <option>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-lg-12">
                                        <textarea name="note" class="form-control" id=""></textarea>
                                    </div>
                                    <hr>
                                    <div>
                                        <p><strong>Payment due:</strong> <span id="payment-due">0.00</span></p>
                                        <button class="btn btn-primary" id="submit-sale">Save</button>
                                    </div>
                                </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </form>
    </div>
    </div>
    </div>
    <script>
$(document).ready(function () {
    let rowCounter = 1;

    // Handle direct product entry
    $('#product-search').on('keypress', function(e) {
        if (e.which == 13) { // Enter key
            e.preventDefault();
            var productName = $(this).val().trim();
            
            if (productName) {
                addNewRow(productName);
                $(this).val('');
            }
        }
    });

    function addNewRow(productName) {
        var newRow = `
            <tr>
                <td>${rowCounter}</td>
                <td class="product-name">${productName}</td>
                <td>
                    <input type="number" 
                           class="form-control quantity" 
                           name="quantity[]" 
                           value="1" 
                           min="1">
                </td>
                <td>
                    <input type="number" 
                           class="form-control unit-selling-price" 
                           name="price[]" 
                           value="0" 
                           min="0"
                           step="0.01">
                </td>
                <td class="subtotal">0.00</td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm delete-row">
                        <ion-icon name="trash-outline"></ion-icon>
                    </button>
                </td>
            </tr>
        `;
        
        $('#product-table tbody').append(newRow);
        rowCounter++;
        
        // Focus price input in new row
        var $newRow = $('#product-table tbody tr:last');
        $newRow.find('.unit-selling-price').focus();
        
        updateTotals();
    }

    // Handle quantity/price changes
    $('#product-table').on('input', '.quantity, .unit-selling-price', function() {
        updateRow($(this).closest('tr'));
        updateTotals();
    });

    // Handle row deletion
    $('#product-table').on('click', '.delete-row', function() {
        $(this).closest('tr').remove();
        updateRowNumbers();
        updateTotals();
    });

    function updateRowNumbers() {
        rowCounter = 1;
        $('#product-table tbody tr').each(function() {
            $(this).find('td:first').text(rowCounter++);
        });
    }

    function updateRow($row) {
        var quantity = parseFloat($row.find('.quantity').val()) || 0;
        var price = parseFloat($row.find('.unit-selling-price').val()) || 0;
        var subtotal = quantity * price;
        $row.find('.subtotal').text(subtotal.toFixed(2));
    }

    function updateTotals() {
        var totalItems = 0;
        var netTotalAmount = 0;

        $('#product-table tbody tr').each(function() {
            var quantity = parseFloat($(this).find('.quantity').val()) || 0;
            var subtotal = parseFloat($(this).find('.subtotal').text()) || 0;
            totalItems += quantity;
            netTotalAmount += subtotal;
        });

        // Calculate discount
        var discountType = $('#discount-type').val();
        var discountAmount = parseFloat($('#discount-amount').val()) || 0;
        var appliedDiscount = 0;

        if (discountType === 'Fixed') {
            appliedDiscount = discountAmount;
        } else if (discountType === 'Percentage') {
            appliedDiscount = (discountAmount / 100) * netTotalAmount;
        }

        // Calculate final totals
        var shippingCharges = parseFloat($('#shipping-charges').val()) || 0;
        var finalTotal = netTotalAmount - appliedDiscount + shippingCharges;
        var paymentAmount = parseFloat($('#receive_amount').val()) || 0;
        var paymentDue = finalTotal - paymentAmount;

        // Update display
        $('#total-items').text(totalItems);
        $('#net-total-amount').text((netTotalAmount - appliedDiscount).toFixed(2) + ' ₨');
        $('#applied-discount').text(appliedDiscount.toFixed(2) + ' ₨');
        $('#sale-total').text(finalTotal.toFixed(2) + ' ₨');
        $('#payment-due').text(paymentDue.toFixed(2) + ' ₨');
    }

    // Handle form submission
  // Handle form submission with validation
$('#submit-sale').on('click', function() {
    // Validate required fields
    if (!$('#customer').val()) {
        alert('Please select a customer');
        return;
    }

    if (!$('#date-sale').val()) {
        alert('Please select a sale date');
        return;
    }

    // Check if table has products
    if ($('#product-table tbody tr').length === 0) {
        alert('Please add at least one product');
        return;
    }

    var data = {
        customer_id: $('#customer').val(),
        pay_term: $('#pay-term').val() || '',
        pay_term_status: $('#pay-term-status').val() || '',
        saleman: $('#saleman').val(),
        date_sale: $('#date-sale').val(),
        sale_status: $('#sale-status').val() || '',
        discount_type: $('#discount-type').val() || '',
        discount: $('#discount-amount').val() || 0,
        shipping_detail: $('#shipping-detail').val() || '',
        shipping_address: $('#shipping-address').val() || '',
        shipping_charges: $('#shipping-charges').val() || 0,
        shipping_status: $('#shipping-status').val() || '',
        delivered_to: $('#delivered-to').val() || '',
        receive_amount: $('#receive_amount').val() || 0,
        payment_method: $('#payment_method').val() || '',
        products: []
    };

    // Collect products data
    $('#product-table tbody tr').each(function() {
        var quantity = $(this).find('.quantity').val();
        var price = $(this).find('.unit-selling-price').val();
        
        if (!quantity || !price) {
            alert('Please fill quantity and price for all products');
            return false;
        }

        data.products.push({
            product_id: '', // Empty string for product_id
            product_name: $(this).find('.product-name').text(),
            unit: '', // Empty string for unit
            quantity: quantity,
            price: price,
            subtotal: $(this).find('.subtotal').text()
        });
    });

    // Submit data
    $.ajax({
        type: 'POST',
        url: 'submit_sale.php',
        data: data,
        success: function(response) {
            if (response.trim() === 'success') {
                window.location.href = 'print/customer_bill_sale_manually.php';
            } else {
                alert('Error: ' + response);
            }
        }
    });
});
    // Update totals when discount/shipping/payment changes
    $('#discount-type, #discount-amount, #shipping-charges, #receive_amount')
        .on('change keyup', updateTotals);
});
</script>



    <!-- 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 -->
    <!-- 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>