<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("includes/db_config.php");

date_default_timezone_set('Asia/Kolkata'); 

if (isset($_POST['psubmit'])) {
    extract($_POST);
    $datetime = date('Y-m-d H:i:s');
    $tmp_file = $_FILES['item_img']['tmp_name'];
    $ext = pathinfo($_FILES["item_img"]["name"], PATHINFO_EXTENSION);
    $rand = md5(uniqid() . rand());
    $itm_img = $rand . "." . $ext;
    move_uploaded_file($tmp_file, "images/" . $itm_img);

    // Insert purchase entry
    $sql = "INSERT INTO tbl_ah_items (type, customer_id, bill_no, bill_date, total_amt, received_amount, balance, payment_by, desp, reference_no, image) 
            VALUES ('Purchase', '$customer_id', '$bill_no', '$bill_date', '$total_amt', '$received_amount', '$balance', '$payment_by', '$desp', '$reference_no', '$itm_img')";

    if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);

        // Update customer balance
        $sql_fetch = "SELECT opening_balance FROM ah_party WHERE id = '$customer_id'";
        $result = mysqli_query($conn, $sql_fetch);

        if ($result && mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $current_balance = floatval($row['opening_balance']);
            $new_balance = $current_balance + $balance;

            $sqlpartyupdate = "UPDATE ah_party SET opening_balance = '$new_balance' WHERE id = '$customer_id'";
            mysqli_query($conn, $sqlpartyupdate);
        }

        // Process each purchased item
        if (!empty($_POST["item_name"])) {
            for ($i = 0; $i < count($_POST["item_name"]); $i++) {
                $item_name = mysqli_real_escape_string($conn, $_POST['item_name'][$i]);
                $qty = (int) $_POST['qty'][$i]; // Ensure quantity is integer
                $unit = mysqli_real_escape_string($conn, $_POST['unit'][$i]);
                $unit_amt = (float) $_POST['unit_amt'][$i]; // Ensure price is float
                $discount = (float) $_POST['discount'][$i];
                $tax_rate = (float) $_POST['tax_rate'][$i];
                $ttl_amt = (float) $_POST['ttl_amt'][$i];

                // Insert into purchase item details
                $sql_prd = "INSERT INTO ah_purchase_item_details (sale_id, item_name, quantity, unit, price_unit, discount, tax_rate, amount) 
                            VALUES ('$last_id', '$item_name', '$qty', '$unit', '$unit_amt', '$discount', '$tax_rate', '$ttl_amt')";
                mysqli_query($conn, $sql_prd) or die(mysqli_error($conn));

                // Update item purchase price and stock
                $sqlupdate = "UPDATE ah_item_details SET purchase_price = '$unit_amt', tax_rate = '$tax_rate', created_date = NOW()
                              WHERE id = '$item_name'";
                mysqli_query($conn, $sqlupdate) or die(mysqli_error($conn));

                // Check if item exists in tracking
                $check_item = "SELECT id, opening_stock FROM ah_item_tracking_details WHERE item_id = '$item_name'";
                $result = mysqli_query($conn, $check_item);

                if ($result && mysqli_num_rows($result) > 0) {
                    $row = mysqli_fetch_assoc($result);
                    $existing_item_id = $row['id'];
                    $existing_qty = (int) $row['opening_stock'];
                    $updated_qty = $existing_qty + $qty; // Add purchased quantity to stock

                    $update_item = "UPDATE ah_item_tracking_details SET at_price_unit = '$unit_amt',min_stock_quatity = '$updated_qty', opening_stock = '$updated_qty' , item_date = NOW()
                                    WHERE id = '$existing_item_id'";
                    mysqli_query($conn, $update_item) or die(mysqli_error($conn));
                    $addStock = " INSERT INTO stock_transactions (item_id, transaction_type, stock,  item_tracking_id, transaction_date) VALUES ('$item_name', 'purchase', $qty, '$existing_item_id', CURDATE())";
                    mysqli_query($conn, $addStock) or die(mysqli_error($conn));

                } else {
                    // Insert new stock record
                    $insert_tracking = "INSERT INTO ah_item_tracking_details (item_id, opening_stock,min_stock_quatity, at_price_unit, item_date) 
                                        VALUES ('$item_name', '$qty','$qty', '$unit_amt', NOW())";
                    mysqli_query($conn, $insert_tracking) or die(mysqli_error($conn));
                    $lasttracking_id = mysqli_insert_id($conn);
                    $addStock = " INSERT INTO stock_transactions (item_id, transaction_type, stock,  item_tracking_id, transaction_date) VALUES ('$item_name', 'purchase', $qty,'$lasttracking_id', CURDATE())";
                    mysqli_query($conn, $addStock) or die(mysqli_error($conn));
                }

                
            }
        }
        echo "<script>location.replace('all-purchase-list.php');</script>";
    } else {
        echo "Error inserting data: " . mysqli_error($conn);
    }
}

// Fetch paid & unpaid totals
$sql = "SELECT 
            SUM(CASE WHEN payment_by = 'Cash' THEN total_amt ELSE 0 END) AS paid, 
            SUM(CASE WHEN payment_by = 'Cheque' THEN total_amt ELSE 0 END) AS unpaid 
        FROM ah_purchase_details";
$summary_result = mysqli_query($conn, $sql);
$summary_row = mysqli_fetch_assoc($summary_result);

$paid = isset($summary_row['paid']) ? (float) $summary_row['paid'] : 0;
$unpaid = isset($summary_row['unpaid']) ? (float) $summary_row['unpaid'] : 0;
$totalbal = $paid + $unpaid;
?>

<!DOCTYPE html>
<html lang="en" dir="ltr" data-theme="light">
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <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>
    <?php include("includes/css.php");?>
    <style>.table tbody tr td:nth-child(even){background-color: var(--bs-table-bg);}
        .modal-body .form-label {
            font-weight: 600;
        }

        .viewptdt .form-label {
            font-weight: 600;
        }

        .viewptdt label {
            margin-top: 10px;
        }

        .form-check-input {
            background-color: var(--bs-bg-level-1);
            border: 1px solid #6163f8;
        }

        .form-switch .form-check-input {
            margin-left: -2em;
            margin-right: 5px;
        }

        .tbladdt .form-control {
            background-color: #fff !important;
            padding: 8px 0.2rem !important;
            min-width: 45px !important;
        }   .select2-container--default .select2-selection--single .select2-selection__rendered {
   width: 158px!important;line-height: 17px;
        }  
        .select2-container--default .select2-selection--single .select2-selection__clear {
  margin-top: 10px;
  margin-right: -20px;
}
        .select2-container .select2-selection--single { 
  height: 38px; 
        }.select2-container--default .select2-selection--single .select2-selection__placeholder {
  color: #999;
  line-height: 28px;
  font-size: 12px;
  color: var(--bs-text-level-3);
        } .select2-container {
  margin-top: -30px;
}
        .customer_records .select2-container{
  margin-top: 0px!important;
}
       
       .customer_records .select2-container:nth-child(1) {
  margin-top: 0px!important;
}
        .remove td:nth-child(1){width:30px;}.btn-remove-customer{margin-top: -32px;position: absolute;padding:5px!important;;color:#fff;background-color:red!important;;border-radius: 2px!important;}
    </style>
</head>
<body class="preload-active aside-active aside-mobile-minimized aside-desktop-maximized">
    <div class="holder">
        <?php include("includes/sidebar.php");?>
        <div class="wrapper">
            <?php include("includes/header.php");?>
            <div class="content">
                <div class="container-fluid g-5">
                  <form action="" method="post" enctype="multipart/form-data"> 
                    <div class="row">
                        <div class="col-12">
                            <div class="portlet">
                                <div class="row portlet-header portlet-header-bordered">
                                         <h3 class="portlet-title">Add Purchase Details</h3>
                                    </div> 
                                </div>
                                <div class="portlet-body"> 
                                    <div class="row">
                                         <?php $sqlfts=mysqli_fetch_array(mysqli_query($conn,"select * from tbl_ah_items where type = 'Purchase' order by id DESC"));
                                    if(!empty($sqlfts['bill_no'])){
                                    $in_no= (int)$sqlfts['bill_no'];
                                    $bill_no= ++$in_no; }else{
                                    $bill_no='1';
                                    } ?>
                                         <div class="col-md-4 mb-2">
                                                   <label class="form-label">Party Name </label> <select class="form-control" name="customer_id" id="customer_id" required>
                                                        <option value="">Select Customer Name</option>
                                                        <?php $sqlct=mysqli_query($conn,"select * from ah_party WHERE type = 'Purchase' ");
                                                        while($resct= mysqli_fetch_array($sqlct)){ ?>
                                                        <option value="<?= $resct['id'];?>"><?= $resct['party_name'];?></option>
                                                        <?php } ?>
                                             </select><br/><center id="hideBalance" style="display: none;"><b>Balance: <span id="getbalance">0.00</span></b></center> 
                                                </div> 
                                        <div class="col-md-2 mb-2" id="hidePhone" style="display: none;">
                                                <label class="form-label">Phone Number</label>
                                                <input type="tel" name="party_phone_no" value="" placeholder="Enter Phone Number" id="party_phone_no" class="form-control">
                                             </div>
                                        <div class="col-md-2 mb-2"></div>
                                        <div class="col-md-2 mb-2">
                                                <label class="form-label">Bill Number</label>
                                                <input type="text" name="bill_no" value="<?= $bill_no;?>" placeholder="Enter Bill Number" class="form-control">
                                            </div> 
                                     <div class="col-md-2 mb-2">
                                                 <label class="form-label">Bill Date</label>
                                                <input type="text" name="bill_date" value="<?= date("d-m-Y");?>" placeholder="" class="form-control">
                                         
                                   <br/> 
                                                <label class="form-label">State Of Supply</label>
                                                <select type="text" name="gst_state" id="gst_state" placeholder="" class="form-control">
                                                    <option value="">Select</option>
                                                    <option value="Telangana">Telangana</option>
                                                    <option value="Hyderabad">Hyderabad</option>
                                                </select><br/>
                                            </div>
                                            </div>
                                 <div class="row table-responsive">
                                    <table  class="table table-bordered table-striped tbladdt">
                                        <thead>
                                            <tr>
                                                <th style="text-align:center;" rowspan="2">#</th>
                                                <th style="text-align:center;" rowspan="2">Item Name</th>
                                                 <th style="text-align:center;" rowspan="2">Qty.</th>
                                                <th style="text-align:center;" rowspan="2">Unit</th>
                                                <th style="text-align:center;">Price/Unit</th>
                                                 <th style="text-align:center;" colspan="2">Discount</th> 
                                                <th style="text-align:center;" colspan="2">Tax</th>
                                                <th style="text-align:center;" rowspan="2">Amount</th> 
                                                </tr>
                                                <tr>
                                                <th><select class="form-control">
                                                    <option>WithTax</option>
                                                    <option>WithoutTax</option>
                                                </select>
                                                </th> 
                                                <th>%</th>
                                                <th>Amount</th>
                                                <th>Amount</th>
                                                 <th>%</th> 
                                             </tr> 
                                        </thead>
                                        <tbody>
                                            <tr class="customer_records">
                                                <td>1.</td> 
                                                <td> <select class="form-control it_id select2 item-dropdown" name="item_name[]" id="item_name">
                                                    <option value="">Select Item Name</option>
                                                     <?php $sqldt=mysqli_query($conn,"SELECT * from ah_item_details");
                                                    while($resdt=mysqli_fetch_array($sqldt)){ ?>
                                                    <option value="<?= $resdt['id'];?>"><?= $resdt['item_name'];?></option>
                                                    <?php } ?>
                                                </select>
                                               </td>
                                                <td> <input type="text" name="qty[]" id="qty" class="form-control qty" value="1" class="form-control" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                <td> <select class="form-control" name="unit[]" id="utid">
                                                         <option value="">Select</option> 
                                                  <?php $sqlpr=mysqli_query($conn,"SELECT * from primery_unit");
                                                    while($respr=mysqli_fetch_array($sqlpr)){ ?>
                                                <option value="<?= $respr['id'];?>"><?= $respr['unit'];?></option><?php } ?>
                                                    </select> </td>
                                                <td><input type="text" name="unit_amt[]" id="unit_amt" class="form-control unit_amt" class="form-control unit_amt" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                
                                                <td><input type="text" name="discount[]" id="discount" class="form-control discount" class="form-control" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                <td><input type="text" name="amount[]" id="amount" class="form-control amount" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                <td> <select class="form-control tax_gsts" name="tax_rate[]" id="tax_gst">
                                                        <option value="">Select</option>
                                                        <?php $sql2="SELECT * from tax_rate";
                                                    $exe2=mysqli_query($conn,$sql2);
                                                    while($res2=mysqli_fetch_array($exe2)){ ?>
                                                    <option value="<?= $res2['id'];?>" data-wd="<?= $res2['tax_gst']; ?>"><?= $res2['tax_gst'];?></option>
                                                    <?php } ?>
                                                    </select> </td>
                                                    <td><input type="text" id="ds_amt" name="ds_amt[]" class="form-control ds_amt" class="form-control" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                    <td><input type="text" id="ttl_amt" name="ttl_amt[]" class="form-control ttl_amt" class="form-control" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                                    <input type="hidden" name="httl_amt[]" id="httl_amt" class="form-control httl_amt"class="form-control" style="border:1px solid #e7e2e2;border-bottom:1px solid #e7e2e2"></td>
                                              
                                            </tr>
                                            <tr>
                                               <th colspan="11" style="border: 0px;">
                                               <div class="customer_records_dynamic" style="width:100%"></div>
                                               </th>
                                            </tr>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="2"><span class="btn btn-warning extra-fields-customer">Add Row</span></td>
                                                <td colspan="5"><strong>Total:</strong> </td> 
                                                <td class="text-center"> <input type="text" value="" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly></td>
                                                 <td colspan="3" class="text-center"><input type="text" name="total_amt" id="total_amt" class="form-control total_amt" style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                        </div>
                    <div class="row">
                        <div class="mb-1 col-md-4"><h6 style="margin-top:5px;"><strong>Payment By:</strong></h6>
                             <select class="form-control" name="payment_by" id="payment_by">
                                <option value="Cash">Cash</option>
                                <option value="Cheque">Cheque</option>
                                <option value="Credit">Credit</option>
                            </select> 
                            <br/>

                            <!-- Reference No. Field (Initially Hidden) -->
                            <div id="reference_field" style="display: none;">
                                <label>Reference No.</label>
                                <input type="text" class="form-control" id="reference_no" name="reference_no">
                                <br/>
                            </div>
                        </div>
                        <div class="mb-1 col-md-4"></div> 
                         <div class="mb-1 col-md-4 ttl-cls">
                            <strong>Total : </strong>
                            <input type="text" name="total_amt" id="stotal_amts" class="form-control stotal_amts" 
                                   style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly>
                            
                            <strong>Paid : </strong>
                            <input type="number" name="received_amount" id="received_amount" class="form-control received_amount" 
                                   style="border:0px solid #ccc;border-bottom:1px solid #ccc" min="0">
                            <span id="error-message" style="color: red; font-size: 14px; display: none;">
                                Paid amount cannot be more than Total amount!
                            </span>
                            <strong>Balance : </strong>
                            <input type="text" name="balance" id="balance" class="form-control stotal_amts" 
                                   style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly>
                        </div>
                    </div>
                     <div class="row">
                        <div class="mb-1 col-md-4">
                            <h6 style="margin-top:5px;"><strong>Upload Images:</strong></h6>
                       <input class="form-control" type="file" name="item_img"></div>
                       <div class="mb-1 col-md-4"></div>
                       </div>
                       <div class="row">
                            <div class="mb-1 col-md-4"><h6 style="margin-top:5px;"><strong>Add Description:</strong></h6><br/>
                            <textarea class="form-control" name="desp" rows="1">  </textarea>
                        </div>
                       <div class="mb-1 col-md-4"></div>
                      
                      </div>
                     <div class="row">
                       
                        <div class="mb-1 col-md-9"></div>
                        <div class="mb-1 mt-2 col-md-3">
                            <button class="btn btn-primary btn-lg mb-3" name="psubmit" type="submit"> Save</button>
                        </div>
                    </div>
                  </form>
                </div>

                <?php include("includes/footer.php");?>
            </div>
        </div>
        <?php include("includes/js.php");?>
<script type="text/javascript">
    $(document).ready(function () {
        $(".select2").select2({
        tags: true,  // Enable new tag adding
        placeholder: "Select or Add Item",
        allowClear: true,
        ajax: {
            url: 'ajax_get_item1.php',
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return { query: params.term };  // Send search query to PHP
            },
            processResults: function(data) {
                return {
                    results: $.map(data, function(item) {
                        return { id: item.id, text: item.text };
                    })
                };
            }
        },
        createTag: function(params) {
            return { id: params.term, text: params.term, newTag: true };
        }
    });

    // Handle adding new item to database when it's not found
    $('.select2').on('select2:select', function(e) {
        var data = e.params.data;
        if (data.newTag) {
            $.ajax({
                url: 'ajax_add_item.php',
                type: 'POST',
                data: { item_name: data.id },
                success: function(response) {
                    var newItem = JSON.parse(response);
                    var newOption = new Option(newItem.text, newItem.id, true, true);
                    $('.select2').append(newOption).trigger('change');
                }
            });
        }
    });
    var i = 1; // Start row counter

    // Add new row dynamically
    $(document).on('click', '.extra-fields-customer', function () {
        i++;
        var newRow = `
            <tr id="row${i}" class="customer_records">
                <td class="row-count">${i}.</td> 
                <td>
                    <select class="form-control it_id select2data item-dropdown" name="item_name[]">
                        <option value="">Select or Add Item</option>
                    </select>
                </td>
                <td><input type="text" name="qty[]" value="1" class="form-control qty"></td>
                <td>
                    <select class="form-control" name="unit[]">
                        <option value="">Select</option>
                        <?php 
                        $sqlpr = mysqli_query($conn, "SELECT * FROM primery_unit");
                        while($respr = mysqli_fetch_array($sqlpr)) { ?>
                            <option value="<?= $respr['id']; ?>"><?= $respr['unit']; ?></option>
                        <?php } ?>
                    </select>
                </td>
                <td><input type="text" name="unit_amt[]" class="form-control unit_amt"></td>
                <td><input type="text" name="discount[]" class="form-control discount"></td>
                <td><input type="text" name="amount[]" class="form-control amount"></td>
                <td>
                    <select class="form-control tax_gsts" name="tax_rate[]">
                        <option value="">Select</option>
                        <?php 
                        $sql2 = mysqli_query($conn, "SELECT * FROM tax_rate");
                        while($res2 = mysqli_fetch_array($sql2)) { ?>
                            <option value="<?= $res2['id']; ?>" data-wd="<?= $res2['tax_gst']; ?>"><?= $res2['tax_gst']; ?></option>
                        <?php } ?>
                    </select>
                </td>
                <td><input type="text" name="ds_amt[]" class="form-control ds_amt" id="ds_amt"></td>
                <td><input type="text" name="ttl_amt[]" class="form-control ttl_amt" id="ttl_amt"></td>
                <td>
                    <button type="button" id="${i}" class="btn btn-danger btn_remove">X</button>
                </td>
            </tr>`;

        $('.customer_records_dynamic').append(newRow);
        initializeSelect2(`#row${i} .select2data`);
        updateTotal();
    });

    // Remove row dynamically
    $(document).on('click', '.btn_remove', function () {
        var button_id = $(this).attr("id");
        $('#row' + button_id).remove();
        updateRowNumbers();
        updateTotal();
    });

    // Initialize Select2 with AJAX
    function initializeSelect2(selector) {
        $(selector).select2({
            tags: true,
            placeholder: "Select or Add Item",
            allowClear: true,
            ajax: {
                url: 'ajax_get_item1.php',
                type: "POST",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return { query: params.term };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return { id: item.id, text: item.text };
                        })
                    };
                }
            },
            createTag: function (params) {
                return { id: params.term, text: params.term, newTag: true };
            }
        }).on('select2:select', function (e) {
            var data = e.params.data;
            if (data.newTag) {
                $.ajax({
                    url: 'ajax_add_item.php',
                    type: 'POST',
                    data: { item_name: data.id },
                    success: function (response) {
                        var newItem = JSON.parse(response);
                        var newOption = new Option(newItem.text, newItem.id, true, true);
                        $(selector).append(newOption).trigger('change');
                    }
                });
            }
        });
    }

    // Fetch unit options from PHP
    function getUnitOptions() {
        var options = '';
        $.ajax({
            url: 'ajax_get_unit.php',
            type: 'GET',
            async: false,
            success: function (response) {
                options = response;
            }
        });
        return options;
    }

    // Fetch tax rate options from PHP
    function getTaxOptions() {
        var options = '';
        $.ajax({
            url: 'ajax_get_tax.php',
            type: 'GET',
            async: false,
            success: function (response) {
                options = response;
            }
        });
        return options;
    }

    $(document).on("change", ".tax_gsts", function () {  
        var row = $(this).closest("tr");
       var price = parseFloat(row.find(".unit_amt").val()) || 0;
        var qty = parseFloat(row.find(".qty").val()) || 1;
        var discount = parseFloat(row.find(".discount").val()) || 0;
        var total = price * qty;
        var disamt = (total * (discount / 100));
        var finalTotal = total - disamt;
        $.ajax({
            type: 'POST',
            url: 'get_gst_price.php',
            data: { gst_id: $(this).val(), price: finalTotal },
            dataType: 'json',
            success:function(data){
                console.log(data);
                 row.find('#ttl_amt').val(data.total); 
                 row.find('#ds_amt').val(data.taxs); 
                 updateTotal();
            },
            error:function(){}
        });
    });
    // Calculate row totals dynamically
    $(document).on("keyup change", ".qty, .unit_amt, .discount", function () {
        var row = $(this).closest("tr");
        var price = parseFloat(row.find(".unit_amt").val()) || 0;
        var qty = parseFloat(row.find(".qty").val()) || 1;
        var discount = parseFloat(row.find(".discount").val()) || 0;
        var total = price * qty;
        var disamt = (total * (discount / 100));
        var finalTotal = total - disamt;

        /*row.find(".ttl_amt").val(finalTotal.toFixed(2));*/
        row.find(".ttl_amt").val(isNaN(finalTotal) ? "" : finalTotal);
        row.find(".httl_amt").val(isNaN(finalTotal) ? "" : finalTotal);
        row.find(".amount").val(isNaN(disamt) ? "" : disamt);
        updateTotal();
    });

    // Update total amounts
    function updateTotal() {
        var totalAmount = 0;
        $(".ttl_amt").each(function () {
            totalAmount += parseFloat($(this).val()) || 0;
        });
        $("#total_amt, #total_amts, #stotal_amts").val(totalAmount.toFixed(2));
        $("#total_items").text($(".customer_records tr").length);
    }

    // Update row numbering after deletion
    function updateRowNumbers() {
        $(".customer_records tr").each(function (index) {
            $(this).find(".row-count").text((index + 1) + ".");
        });
    }

    // Tax calculation based on selection
    

    // Handle received amount & balance calculation
    /*$(document).on("keyup", ".received_amount", function () {
        var received_amount = parseFloat($(this).val()) || 0;
        var total_amt = parseFloat($("#total_amt").val()) || 0;
        var balance = total_amt - received_amount;
        $("#balance").val(balance.toFixed(2));
    });*/

    $("#received_amount").on("input", function() {
        let total = parseFloat($("#stotal_amts").val()) || 0;
        let paid = parseFloat($(this).val()) || 0;

        // Restrict input if paid amount exceeds total
        if (paid > total) {
            $("#error-message").show();
            $(this).val(total);
        }
        $("#error-message").hide();
        // Update balance
        $("#balance").val((total - parseFloat($(this).val())).toFixed(2));
    });

    // Submit form via AJAX
    $('#submit').click(function () {
        $.ajax({
            url: "add-product.php",
            method: "POST",
            data: $('#add_name').serialize(),
            success: function (data) {
                alert(data);
                $('#add_name')[0].reset();
                $('.customer_records_dynamic').empty(); // Clears previous rows after submission
                i = 1; // Reset row counter
                updateTotal();
            }
        });
    });
  $(document).on("change", "#customer_id", function () {
    var customerId = $(this).val();

    if (customerId) {
        $.ajax({
            type: 'POST',
            url: 'get_balance.php',
            data: { customer_id: customerId },
            dataType: 'json',
            success: function (response) {
                if (response && response.balance !== undefined) {
                    $('#getbalance').html(response.balance.toFixed(2)); // Show balance with 2 decimal places
                    $('#party_phone_no').val(response.party_phone_no);

                    // Show the hidden fields when data is available
                    $("#hideBalance").show();
                    $("#hidePhone").show();
                } else {
                    $('#getbalance').html("0.00"); // Default if no data is found
                    $('#party_phone_no').val("");

                    // Hide fields if no data
                    $("#hideBalance").hide();
                    $("#hidePhone").hide();
                }
            },
            error: function () {
                $('#getbalance').html("Error fetching balance"); // Handle AJAX errors
                $("#hideBalance").hide();
                $("#hidePhone").hide();
            }
        });
    } else {
        // Hide fields if no customer is selected
        $("#hideBalance").hide();
        $("#hidePhone").hide();
        $('#getbalance').html("0.00");
        $('#party_phone_no').val("");
    }
});


    // Fetch unit & tax details on item selection
    $(document).on("change", ".it_id", function () {
        var row = $(this).closest("tr");
        var it_id = $(this).val();

        $.ajax({
            type: 'POST',
            url: 'get_unit_price.php',
            data: { it_id: it_id },
            dataType: 'json',
            success: function (data) {
                row.find('.unit_amt').val(data.purchase_price);
                row.find('.tax_gsts').val(data.tax_rate);
                row.find('.ds_amt').val(data.gst_amt);
                row.find('.discount').val(data.disc_sale);
                row.find('.ttl_amt').val(data.total_amt);
                updateTotal();
            }
        });
    });
});

</script>    
</body>

</html>