<?php include("includes/db_config.php");
if (isset($_POST['psubmit'])) {
//var_dump($_POST); 
extract($_POST);
date_default_timezone_set('Asia/Kolkata');
$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);
$sql="INSERT into ah_sale_return_details(customer_id,return_no,return_date,bill_no,bill_date,total_amt,received_amount,balance,payment_by,desp,image) values ('$customer_id','$return_no','$return_date','$bill_no','$bill_date','$total_amts','$received_amount','$total_amt','$payment_by','$desp','$itm_img')"; 
if  (mysqli_query($conn, $sql)) {
$last_id= mysqli_insert_id($conn);
  if(count($_POST["item_name"]) > 0)  {
    for($i = 0; $i < count($_POST["item_name"]); $i++){
     $item_name = mysqli_real_escape_string($conn,$_POST['item_name'][$i]);
     $qty = mysqli_real_escape_string($conn,$_POST['qty'][$i]);
     $unit = mysqli_real_escape_string($conn,$_POST['unit'][$i]);
     $unit_amt = mysqli_real_escape_string($conn,$_POST['unit_amt'][$i]);
     $discount = mysqli_real_escape_string($conn,$_POST['discount'][$i]);
     $amount = mysqli_real_escape_string($conn,$_POST['amount'][$i]);
     $tax_rate = mysqli_real_escape_string($conn,$_POST['tax_rate'][$i]);
     $ds_amt = mysqli_real_escape_string($conn,$_POST['ds_amt'][$i]);
     $ttl_amt = mysqli_real_escape_string($conn,$_POST['ttl_amt'][$i]);
    $sql_prd="INSERT into ah_sale_return(return_id,item_name,quantity,unit_id,price_unit_id,discount,tax_rate,amount) values ('$last_id','$item_name','$qty','$unit','$unit_amt','$discount','$tax_rate','$ttl_amt')";
    $prd_res=mysqli_query($conn, $sql_prd) or die(mysqli_error());
  }
}
     echo "<script>location.replace('return.php');</script>";
}
}
 ?>
<!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">
    <?php include("includes/css.php");?>
    <style>
        .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;
        }
    </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 Sale Return Details</h3>
                                    </div> 
                                </div>
                                <div class="portlet-body">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="row">
                                                <div class="col-md-4 mt-2">
                                                    <select class="form-control" name="customer_id" required>
                                                        <option value="">Select Customer Name</option>
                                                        <?php $sqlct=mysqli_query($conn,"select * from ah_party");
                                                        while($resct= mysqli_fetch_array($sqlct)){ ?>
                                                        <option value="<?= $resct['id'];?>"><?= $resct['party_name'];?></option>
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-2">
                                                <label class="form-label">Return Number</label>
                                                <input type="text" name="return_no" placeholder="Enter Return Number" class="form-control">
                                            </div>
                                            <div class="mb-2">
                                                <label class="form-label">Bill Number</label>
                                                <input type="text" name="bill_no" placeholder="Enter Bill Number" class="form-control">
                                            </div>
                                            <div class="mb-2">
                                                <label class="form-label">Bill Date</label>
                                                <input type="date" name="bill_date" placeholder="Enter Bill Number" class="form-control">
                                            </div>
                                            <div class="mb-2">
                                                <label class="form-label">Return Date</label>
                                                <input type="text" name="return_date" value="<?= date("Y/m/d");?>" placeholder="" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                 <hr />
                                <div class="portlet-body table-responsive">
                                    <table id="datatable" class="table table-bordered table-striped table-hover 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">MRP</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>
                                                <th style="text-align:center;" rowspan="2">Action</th>
                                                </tr>
                                          <tr>
                                                <th><select class="form-control">
                                                    <option>WithTax</option>
                                                    <option>WithoutTax</option>
                                                </select>
                                                </th>
                                                <th>%</th>
                                                <th>Amount</th>
                                                 <th>%</th>
                                                 <th>Amount</th>
                                                 
                                          </tr>  
                                     </thead>
                                        <tbody id="">
                                            <tr  class="dynamic_field customer_records">
                                                <td>1.</td>
                                                <td> <select class="form-control it_id" name="item_name[]" id="item_name">
                                                    <option value="">Select</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="price[]" id="price" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td> -->
                                                <td> <input type="text" name="qty[]" id="qty" class="form-control qty" value="1" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></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" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                
                                                <td><input type="text" name="discount[]" id="discount" class="form-control discount" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                <td><input type="text" name="amount[]" id="amount" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></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" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td> 
                                                    <td><input type="text" id="ttl_amt" name="ttl_amt[]" class="form-control ttl_amt" style="border:0px solid #ccc;border-bottom:1px solid #ccc">
                                                    <input type="hidden" id="httl_amt" class="form-control httl_amt" >
                                                    <td>
                                                    </td>
                                            </tr>
                                                  <tr>
                                        <th colspan="10" 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="6"><strong>Total:</strong> </td> 
                                                <td class="text-center"> <input type="text" value="" id="" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly></td>
                                                 <td colspan="3" class="text-center"><input type="text" 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">
                                <option>Cash</option>
                                <option>Cheque</option>
                            </select>
                        </div>
                        <div class="mb-1 col-md-2"></div>
                        <div class="mb-1 col-md-2">
                      
                        </div>
                         <div class="mb-1 col-md-4 ttl-cls"><strong>Total:</strong><br/><input type="text" name="total_amt" id="stotal_amts" class="form-control stotal_amts" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></div>
                          <!-- <div class="mb-1 col-md-2"> <div class="form-check"><input class="form-check-input" type="checkbox" value="" id="flexCheckChecked" checked="checked"> <label class="form-check-label" for="flexCheckChecked">Round Off</label></div> </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 class="mb-1 col-md-4" style="margin-top:5px;"><strong>Recieved:</strong><br/><input type="text" class="form-control" name="received_amount" id="received_amount" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></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 class="mb-1 col-md-4" style="margin-top:5px;"><strong>Balance:</strong> <br/>
                            <input type="text" id="total_amts" name="total_amts" class="form-control total_amts" style="border:0px solid #ccc; background-color:transparent;" readonly></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">
     $('.extra-fields-customer').click(function() {
            $('.customer_records').clone().appendTo('.customer_records_dynamic');
            $('.customer_records_dynamic .customer_records').addClass('single remove');
            $('.single .extra-fields-customer').remove();
            $('.single').append('<a href="#" class="remove-field btn-remove-customer">X</a>');
            $('.customer_records_dynamic > .single').attr("class", "remove");

            $('.customer_records_dynamic input').each(function() {
                var count = 0;
                var fieldname = $(this).attr("name");
                $(this).attr('name', fieldname + count);
                count++;
            });

        });
        $(document).on('click', '.remove-field', function(e) {
            $(this).parent('.remove').remove();
            e.preventDefault();
            someFunction();
        });
(function() {
    "use strict";
    $("table").on("keyup", ".discount,.qty", function() {
               var totals = 0;
      var row = $(this).closest("tr");
      var price = parseFloat(row.find("#unit_amt").val());
      var qty = parseFloat(row.find("#qty").val());
      var discount = parseFloat(row.find("#discount").val());
      var total = price * qty;
      if(!isNaN(discount)){
      var disamt = (total * (discount / 100));
      var rtotal = total - disamt;
      }else{
       var rtotal =total;
      } 
     // row.find("#ttl_amt").val(isNaN(total) ? "" : total);
      row.find("#ttl_amt").val(isNaN(rtotal) ? "" : rtotal);
      row.find("#httl_amt").val(isNaN(rtotal) ? "" : rtotal);
      row.find("#amount").val(isNaN(disamt) ? "" : disamt);
    });
  })();
(function() {
    $('body').on('keyup', '#received_amount', function(){
      var ramt = $(this).val();  
      var $container = $(this).closest(".container-fluid");
      var prc = $container.find("#stotal_amts").val();
      var total = prc - ramt;
      $("#total_amts").val(isNaN(total) ? "" : total);
    });
  })();
$(document).on("keyup", ".discount,.qty", function() {
    var sum = 0;
    $(".ttl_amt").each(function(){
        sum += +$(this).val();
    });
    $("#total_amt").val(sum);
    $("#total_amts").val(sum);
    $("#stotal_amts").val(sum);
}); 
function someFunction() {
    var sum = 0;
    $(".ttl_amt").each(function(){
        sum += +$(this).val();
    });
    $("#total_amt").val(sum);
    $("#total_amts").val(sum);
    $("#stotal_amts").val(sum);
}  
(function() {
    "use strict";
    $("table").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){
                console.log(data);
                row.find('#unit_amt').val(data.sale_price);
                 row.find('#tax_gst').val(data.tax_rate); 
                 row.find('#utid').val(data.punit); 
                 row.find('#discount').val(data.disc_sale); 
                 row.find('#ttl_amt').val(data.total_amt); 
                 row.find('#httl_amt').val(data.total_amt); 
                 row.find('#ds_amt').val(data.gst_amt); 
             //$('#container').container('show'); 
                 someFunction();
            },
            error:function(){}
        });
    });
  })(); 
(function() {
    "use strict";
    $("table").on("keyup", ".qty", function() {    
        var row = $(this).closest("tr");
        var qty=$(this).val();
        var it_id = parseFloat(row.find(".it_id").val());
        $.ajax({
            type:'post',
            url:'get_qty.php',
            data:{it_id: it_id, qty: qty},
            dataType:'json',
            success:function(data){
                console.log(data);
                alert(data);
                //someFunction();
            },
            error:function(){}
        });
    });
  })(); 

(function() {
    "use strict";
    $("table").on("change", ".tax_gsts", function() {    
        var row = $(this).closest("tr");
        var gst_id=$(this).val();
        var price = parseFloat(row.find(".httl_amt").val());
        $.ajax({
            type:'post',
            url:'get_gst_price.php',
            data:{gst_id: gst_id , price: price},
            dataType:'json',
            success:function(data){
                console.log(data);
                 row.find('#ttl_amt').val(data.total); 
                 row.find('#ds_amt').val(data.taxs); 
                // row.find('#amount').val(data.taxs); 
                //$('#container').container('show'); 
                 someFunction();
            },
            error:function(){}
        });
    });
  })(); 
</script>
</body>

</html>