<?php 
include_once("includes/config.php");
session_start();

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

$invoice_no = isset($_GET['invoice']) ? $_GET['invoice'] : '';
$sale_data = null;
$sale_items = [];

$customer_query = "SELECT id, name FROM contacts WHERE type='customer'";
$customer_stmt = $conn->query($customer_query);
$customers = $customer_stmt->fetchAll();

if ($invoice_no) {
    try {
        $conn->beginTransaction();
        
        $query = "SELECT ss.*, 
                  c.name as customer_name, 
                  cd.amount as cash_deposit_amount, 
                  cd.bank_id,
                  b.bank_name as bank_name
                  FROM stock_sale ss
                  LEFT JOIN contacts c ON ss.customer_id = c.id
                  LEFT JOIN cash_deposit cd ON ss.invoice = cd.invoice
                  LEFT JOIN banks b ON cd.bank_id = b.id
                  WHERE ss.invoice = :invoice";
        
        $stmt = $conn->prepare($query);
        $stmt->execute(['invoice' => $invoice_no]);
        $sale_data = $stmt->fetch(PDO::FETCH_ASSOC);

        $item_query = "SELECT ss.*, p.name as product_name 
                       FROM stock_sale ss
                       LEFT JOIN products p ON ss.product_id = p.id
                       WHERE ss.invoice = :invoice";

        $item_stmt = $conn->prepare($item_query);
        $item_stmt->execute(['invoice' => $invoice_no]);
        $sale_items = $item_stmt->fetchAll(PDO::FETCH_ASSOC);

        $conn->commit();
    } catch (PDOException $e) {
        $conn->rollBack();
        $_SESSION['error'] = "Error fetching sale data: " . $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $conn->beginTransaction();

        $update_query = "UPDATE stock_sale 
                         SET customer_id = :customer_id, 
                             date_sale = :date_sale 
                         WHERE invoice = :invoice";
        
        $stmt = $conn->prepare($update_query);
        $stmt->execute([
            'customer_id' => $_POST['customer_id'],
            'date_sale' => $_POST['date_sale'],
            'invoice' => $invoice_no
        ]);

        $check_query = "SELECT COUNT(*) FROM cash_deposit WHERE invoice = :invoice";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->execute(['invoice' => $invoice_no]);
        $invoice_exists = $check_stmt->fetchColumn() > 0;

        if ($invoice_exists) {
            $deposit_query = "UPDATE cash_deposit
                              SET amount = :amount, 
                                  bank_id = :bank_id, 
                                  status = 'customer', 
                                  user_id = :user_id
                              WHERE invoice = :invoice";
        } else {
            $deposit_query = "INSERT INTO cash_deposit 
                              (invoice, amount, bank_id, date_deposit, status, user_id) 
                              VALUES (:invoice, :amount, :bank_id, CURDATE(), 'customer', :user_id)";
        }

        $stmt = $conn->prepare($deposit_query);
        $stmt->execute([
            'invoice' => $invoice_no,
            'amount' => floatval($_POST['receive_amount']),
            'bank_id' => $_POST['bank_id'],
            'user_id' => $_POST['customer_id']
        ]);

        // -----------------------
        // Handle deleted rows
        // -----------------------
$submitted_ids = array_map('intval', $_POST['sale_item_id'] ?? []);
$stmt = $conn->prepare("SELECT sale_id FROM stock_sale WHERE invoice = :invoice");
$stmt->execute(['invoice' => $invoice_no]);
$existing_ids = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

$to_delete = array_diff($existing_ids, $submitted_ids);
if (!empty($to_delete)) {
    try {
        $placeholders = implode(',', array_fill(0, count($to_delete), '?'));
        $delete_stmt = $conn->prepare("DELETE FROM stock_sale WHERE sale_id IN ($placeholders)");
        $delete_stmt->execute(array_values($to_delete));
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            echo json_encode([
                'success' => true,
                'deleted_ids' => array_values($to_delete)
            ]);
        }
    } catch (PDOException $e) {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            echo json_encode([
                'error' => 'Delete failed: ' . $e->getMessage(),
                'to_delete' => array_values($to_delete)
            ]);
            exit;
        } else {
            throw $e;
        }
    }
}

        // -----------------------
        // Insert/Update sale items
        // -----------------------
        foreach ($_POST['product_id'] as $index => $product_id) {
            $sale_item_id = intval($_POST['sale_item_id'][$index]);
            $qty = floatval($_POST['quantity'][$index]);
            $price = floatval($_POST['price'][$index]);
            $unit = $_POST['unit'][$index];
            $category = $_POST['category'][$index];
            $product_code = $_POST['product_code'][$index];
            $product_name = $_POST['product_name'][$index];
            $total_amount = $qty * $price;

            $net_cash = ($sale_item_id > 0 && $index == 0) ? floatval($_POST['receive_amount']) : 0;

            if ($sale_item_id > 0) {
              
                $update_item = "UPDATE stock_sale 
                                SET sale_qty = :qty,
                                    price = :price,
                                    unit = :unit,
                                    category = :category,
                                    product_code = :product_code,
                                    product_name = :product_name,
                                    total_amount = :total_amount,
                                    net_cash = :net_cash
                                WHERE sale_id = :id";
                $stmt = $conn->prepare($update_item);
                $stmt->execute([
                    'qty' => $qty,
                    'price' => $price,
                    'unit' => $unit,
                    'category' => $category,
                    'product_code' => $product_code,
                    'product_name' => $product_name,
                    'total_amount' => $total_amount,
                    'net_cash' => $net_cash,
                    'id' => $sale_item_id
                ]);
            } else {
                
                $insert_item = "INSERT INTO stock_sale 
                                (invoice, product_id, sale_qty, price, unit, category, product_code, product_name, total_amount, net_cash)
                                VALUES 
                                (:invoice, :product_id, :qty, :price, :unit, :category, :product_code, :product_name, :total_amount, :net_cash)";
                $stmt = $conn->prepare($insert_item);
                $stmt->execute([
                    'invoice' => $invoice_no,
                    'product_id' => $product_id,
                    'qty' => $qty,
                    'price' => $price,
                    'unit' => $unit,
                    'category' => $category,
                    'product_code' => $product_code,
                    'product_name' => $product_name,
                    'total_amount' => $total_amount,
                    'net_cash' => $net_cash
                ]);
            }
        }

        $conn->commit();

        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            echo json_encode(['success' => true]);
            exit;
        }

        $_SESSION['success'] = "Sale updated successfully";
        header("Location: customer_bill_reprint.php?invoice_no=$invoice_no");
        exit;

    } catch (PDOException $e) {
        $conn->rollBack();
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            echo json_encode(['error' => $e->getMessage()]);
            exit;
        }
        $_SESSION['error'] = "Error: " . $e->getMessage();
    }
}
?>

<!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;">
<?php if (isset($sale_data) && $sale_data): ?>
<form id="searchForm" method="POST">
    <input type="hidden" name="invoice" value="<?php echo $invoice_no; ?>">

    <!-- Customer Selection -->
    <div class="form-group">
        <label>Customer</label>
        <select name="customer_id" class="form-control">
            <option value="<?php echo $sale_data['customer_id']; ?>">
                <?php echo $sale_data['customer_name']; ?>
            </option>
            <?php foreach ($customers as $customer): ?>
                <option value="<?php echo $customer['id']; ?>">
                    <?php echo $customer['name']; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <!-- Sale Date -->
    <div class="form-group">
        <label>Sale Date</label>
        <input type="date" name="date_sale" class="form-control" value="<?php echo $sale_data['date_sale']; ?>">
    </div>

    <!-- Product Search -->
    <div class="row mb-3">
        <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%; left: 0;"></div>
    </div>

    <!-- Products Table -->
    <table id="product-table" class="table">
        <thead>
            <tr>
                <th>Product</th>
                <th>Quantity</th>
                <th>Unit</th>
                <th>Price</th>
                <th>Subtotal</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($sale_items as $item): ?>
            <tr>
                <td>
                    <?php echo $item['product_name']; ?>
                    <input type="hidden" name="product_id[]" value="<?php echo $item['product_id']; ?>">
                    <input type="hidden" name="product_name[]" value="<?php echo $item['product_name']; ?>">
                    <input type="hidden" name="product_code[]" value="<?php echo $item['product_id']; ?>">
                    <input type="hidden" name="sale_item_id[]" value="<?php echo $item['sale_id']; ?>">
                    <input type="hidden" name="category[]" value="<?php echo $item['category']; ?>">
                </td>
                <td><input type="number" name="quantity[]" class="form-control quantity" value="<?php echo $item['sale_qty']; ?>"></td>
                <td>
                    <select name="unit[]" class="form-control">
                        <option value="<?php echo $item['unit']; ?>"><?php echo $item['unit']; ?></option>
                    </select>
                </td>
                <td><input type="number" name="price[]" class="form-control unit-selling-price" value="<?php echo $item['price']; ?>"></td>
                <td class="subtotal"></td>
                <td><ion-icon name="trash-outline" class="delete-row"></ion-icon></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Totals and Bank -->
    <div class="row">
        <div class="col-md-6">
            <p>Total Items: <span id="total-items">0</span></p>
            <p>Net Total: <span id="net-total-amount">0.00</span></p>
        </div>
        <div class="col-md-6">
            <select class="form-control" name="bank_id" id="bankSelect" required>
                <option value="<?php echo $sale_data['bank_id']; ?>"><?php echo $sale_data['bank_name']; ?></option>
                <?php foreach ($banks as $bank): ?>
                    <option value="<?= htmlspecialchars($bank['id']) ?>"><?= htmlspecialchars($bank['bank_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label>Received Amount</label>
                <input type="number" id="receive_amount" name="receive_amount" class="form-control" value="<?php echo $sale_data['cash_deposit_amount']; ?>">
            </div>
            <p>Payment Due: <span id="payment-due">0.00</span></p>
        </div>
    </div>

    <button type="submit" class="btn btn-primary" id="submit-sale">Update Sale</button>
</form>
<?php endif; ?>
</div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    </div>
    </div>
    </div>
    <script>
 $(document).ready(function() {
    // Search products
    $('#product-search').on('keyup', function() {
        var search = $(this).val().trim();
        if (search.length > 0) {
            $.post('search_products.php', {search: search}, function(response) {
                if (response.includes('Product not found') || response.trim() === '') {
                    $('#product-list').hide();
                } else {
                    $('#product-list').html(response).show();
                }
            });
        } else $('#product-list').hide();
    });

    // Select product
    $(document).on('click', '.product-item', function() {
        var productId = $(this).data('id');
        addProductToTable(productId);
        $('#product-list').hide();
        $('#product-search').val('');
    });

    function addProductToTable(productId) {
        var exists = false;
        $('#product-table tbody tr').each(function() {
            if ($(this).find('input[name="product_id[]"]').val() == productId) {
                exists = true;
                var qty = parseInt($(this).find('.quantity').val()) + 1;
                $(this).find('.quantity').val(qty);
                updateRow($(this));
                updateTotals();
                return false;
            }
        });

        if (!exists) {
            $.post('get_product_edit_pos.php', {id: productId}, function(response) {
                if (response.error) { alert(response.error); return; }

                var unitOptions = '';
                if (response.units && response.units.length > 0) {
                    response.units.forEach(u => {
                        unitOptions += `<option value="${u.actual_name}">${u.actual_name}</option>`;
                    });
                } else unitOptions = '<option value="Piece">Piece</option>';

                var newRow = `
<tr>
    <td>${response.product_name}
        <input type="hidden" name="product_name[]" value="${response.product_name}">
        <input type="hidden" name="product_code[]" value="${response.product_id}">
        <input type="hidden" name="product_id[]" value="${response.product_id}">
        <input type="hidden" name="category[]" value="${response.category_id}">
        <input type="hidden" name="sale_item_id[]" value="0">
    </td>
    <td><input type="number" name="quantity[]" class="form-control quantity" value="1"></td>
    <td><select name="unit[]" class="form-control">${unitOptions}</select></td>
    <td><input type="number" name="price[]" class="form-control unit-selling-price" value="${response.sell_price}"></td>
    <td class="subtotal"></td>
    <td><ion-icon name="trash-outline" class="delete-row"></ion-icon></td>
</tr>`;
                $('#product-table tbody').append(newRow);
                updateRow($('#product-table tbody tr:last'));
                updateTotals();
            }, 'json');
        }
    }

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

    function updateTotals() {
        var totalItems = 0, netTotal = 0;
        $('#product-table tbody tr').each(function() {
            var qty = parseFloat($(this).find('.quantity').val()) || 0;
            var sub = parseFloat($(this).find('.subtotal').text()) || 0;
            totalItems += qty; netTotal += sub;
        });
        $('#total-items').text(totalItems);
        $('#net-total-amount').text(netTotal.toFixed(2) + ' ₨');
        var receive = parseFloat($('#receive_amount').val()) || 0;
        $('#payment-due').text((netTotal - receive).toFixed(2) + ' ₨');
    }

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

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

    // Submit
    $('#submit-sale').on('click', function(e) {
        e.preventDefault();
        if ($('#product-table tbody tr').length === 0) { alert('Add at least one product'); return; }
        var formData = new FormData($('#searchForm')[0]);
        $.ajax({
            url: 'edit_pos.php?invoice=' + $('input[name="invoice"]').val(),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
         success: function(res) {
    try {
        var result = JSON.parse(res);
        if (result.success) {
            if(result.deleted_ids) console.log('Deleted IDs:', result.deleted_ids);
            alert('Sale updated successfully');
              window.location.href = 'print/customer_bill_reprint.php?invoice_no=' + $('input[name="invoice"]').val();
        } else if(result.error) {
            // alert('Error: ' + result.error);
              window.location.href = 'print/customer_bill_reprint.php?invoice_no=' + $('input[name="invoice"]').val();
        }
    } catch(e) {
        console.log('Raw response:', res);
        // alert('Response parse error');
          window.location.href = 'print/customer_bill_reprint.php?invoice_no=' + $('input[name="invoice"]').val();
    }
}
,
            error: function() { alert('AJAX error'); }
        });
    });

    $('#product-table tbody tr').each(function() { updateRow($(this)); });
    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>