<?php include("includes/db_config.php");
if (isset($_POST['psubmit'])) {
//var_dump($_POST); exit();
extract($_POST);
date_default_timezone_set('Asia/Kolkata');
$datetime = date('Y-m-d H:i:s');
$id = $_POST['id'];
$sql ="UPDATE  sale_details  SET customer_id='$customer_id',bill_no='$invoice_no',bill_date='$invoice_date', total_amt='$total_amts',received_amount='$received_amount',payment_by='$payment_by' WHERE id='$id'";
if  (mysqli_query($conn, $sql)) {
     $item_name = mysqli_real_escape_string($conn,$_POST['item_name']);
     $qty = mysqli_real_escape_string($conn,$_POST['qty']);
     $unit = mysqli_real_escape_string($conn,$_POST['unit']);
     $price_unit = mysqli_real_escape_string($conn,$_POST['price_unit']);
     $discount = mysqli_real_escape_string($conn,$_POST['discount']);
     $tax_rate = mysqli_real_escape_string($conn,$_POST['tax_rate']);
     $ttl_amt = mysqli_real_escape_string($conn,$_POST['ttl_amt']);
    $sql_prd ="UPDATE sale_item_details SET sale_id='$id',item_name='$item_name',quantity='$qty',unit='$unit',price_unit='$price_unit',discount='$discount',tax_rate='$tax_rate',amount='$ttl_amt' WHERE id='$sid'";
    $prd_res=mysqli_query($conn, $sql_prd) or die(mysqli_error());
  }
}
 ?>
<!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="multiple/form-data">
                    <div class="row">
                        <div class="col-12">
                            <div class="portlet">
                                <div class="row portlet-header portlet-header-bordered">
                                         <h3 class="portlet-title">Edit Sales Details</h3>
                                    </div> 
                                </div>
                                 <?php $idd=$_GET['id'];
                                $sql="select * from tbl_ah_items where type = 'Sale' And id='".$idd."'"; 
                                $result = mysqli_query($conn, $sql); 
                                $res= mysqli_fetch_array($result);
                                $cid=$res['customer_id'];
                                $sqlpt=mysqli_query($conn,"SELECT * from ah_party where id='".$cid."'");
                                $restpy=mysqli_fetch_array($sqlpt); ?>
                               
                                <div class="portlet-body">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="row">
                                                <div class="col-md-2 form-check form-switch">
                                                    &nbsp; &nbsp; <input class="form-check-input" type="checkbox" role="switch" id="flexSwitchCheckChecked" checked="checked"> <label class="form-check-label" for="flexSwitchCheckChecked" style="margin-top:0px;">Credit</label>
                                                </div>

                                                <div class="col-md-2 form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" role="switch" id="flexSwitchCheckChecked"> <label class="form-check-label" for="flexSwitchCheckChecked" style="margin-top:0px;"> Cash</label>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mt-2">
                                                    <select class="form-control" name="customer_id">
                                                        <option value="<?= $restpy['id'];?>"><?= $restpy['party_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">Invoice Number</label>
                                                <input type="text" placeholder="Enter Invoice Number" value="<?= $res['bill_no'];?>" name="invoice_no" class="form-control">
                                                <input type="hidden" value="<?= $res['id'];?>" name="id" class="form-control">
                                            </div>
                                            <div class="mb-2">
                                                <label class="form-label">Invoice Date</label>
                                                <input type="text" name="bill_date" value="<?= $res['bill_date'];?>" placeholder="" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                 <hr />
                                <div class="portlet-body table-responsive">
                                    <table id="datatable-1" 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">Unit Detail</th>
                                                 <th style="text-align:center;" rowspan="2">Quatity</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>%</th>
                                                <th>Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                               <?php $sid=$res['id']; $i=1;
                               $sqlsl=mysqli_query($conn,"select ads.*,ait.item_name,ait.item_hsn from sale_item_details ads join ah_item_details ait on ads.item_name=ait.id where ads.sale_id='".$sid."'");
                                    $resl= mysqli_fetch_array($sqlsl); 
                                        $slid=$resl['unit'];
                                        $tid=$resl['tax_rate'];
                                        $dis=$resl['discount'];
                                    $sqlfts=mysqli_fetch_array(mysqli_query($conn,"select * from primery_unit where id='".$slid."'"));
                                    $sqlts=mysqli_fetch_array(mysqli_query($conn,"select * from tax_rate where id='".$tid."'"));
                                    if(!empty($sqlts['tax_gst'])){
                                    $tax=$sqlts['tax_gst'];
                                    $prc=$resl['price_unit'] * $resl['quantity'];
                                    $dis_pre = ($prc * ($dis / 100));
                                    $dis_price = $prc - $dis_pre;
                                    $tax_rate=filter_var($tax, FILTER_SANITIZE_NUMBER_INT);
                                    $taxtd=$dis_price*$tax_rate/100; }else{
                                    $dis_pre=0;
                                    $taxtd=0;
                                    $tax=0;
                                    $totalamt = $dis_price + $taxtd; 
                                    }
                                     ?>
                                            <tr>
                                                <td>1.</td>
                                                <td> <select name="item_name" class="form-control">
                                                    <option value="<?= $resl['id'];?>"><?= $resl['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" value="<?= $resl['item_hsn'];?>" name="item_hsn" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td> -->
                                               <td width="180px"> <input type="text" name="unit_details[]" id="unit_details" class="form-control" readonly value="1 box = 10 Piece" style="background-color:#e2ecf1!important;border:0px solid #ccc;widhth:180px;font-size:12px;border-bottom:1px solid #ccc"></td>
                                                <td> <input type="text" value="<?= $resl['quantity'];?>" name="qty" id="qty" class="form-control qty" style="border:0px solid #ccc;border-bottom:1px solid #ccc">
                                                    <input type="hidden" value="<?= $resl['id'];?>" name="sid" class="form-control"></td> 
                                                <td> <select class="form-control" name="unit">
                                                     <option value="<?= $sqlfts['id'];?>"><?= $sqlfts['unit'];?></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" value="<?= $resl['price_unit'];?>" name="price_unit" id="unit_amt" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                
                                                <td><input type="text" value="<?= $dis_pre;?>" name="discount" class="form-control discount" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                <td><input type="text" value="" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                <td> <select class="form-control tax_gsts" name="tax_rate">
                                                        <option value="<?= $sqlts['id'];?>"><?= $sqlts['tax_gst'];?></option>
                                                    </select> </td>
                                                    <td><input type="text" value="<?= $taxtd;?>" name="ds_amt" class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                                    <td><input type="text" value="<?= $totalamt;?>" name="ttl_amt" id="ttl_amt" class="form-control ttl_amt" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td>
                                              
                                            </tr>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="6"><strong>Total:</strong> </td> 
                                                <td class="text-center"> <input type="text"  class="form-control" style="border:0px solid #ccc;border-bottom:1px solid #ccc" readonly></td>
                                                 <td colspan="3" class="text-center"><input type="text" value="<?= $res['total_amt']; ?>" name="total_amts" class="form-control" 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 value="<?= $res['payment_by']; ?>"><?= $res['payment_by']; ?></option>
                                <option>Cash</option>
                                <option>Cheque</option>
                            </select>
                        </div>
                        <div class="mb-1 col-md-2"></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 class="mb-1 col-md-4 ttl-cls"><strong>Total:</strong><br/><input type="text" name="total_amt" id="stotal_amts" value="<?= $res['total_amt']; ?>" class="form-control stotal_amts" 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>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" value="<?= $res['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"><?= $res['desp']; ?></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" value="<?= $res['balance']; ?>" 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">
 (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 rtotal = total - (total * (discount / 100));
      }else{
       var rtotal =total;
      } 
     // row.find("#ttl_amt").val(isNaN(total) ? "" : total);
      row.find("#ttl_amt").val(isNaN(rtotal) ? "" : rtotal);
      row.find("#amount").val(isNaN(rtotal) ? "" : rtotal);
    });
  })();
(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);
});    
$(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>