<?php include("includes/db_config.php");
if (isset($_POST['psubmit'])) {
extract($_POST);
date_default_timezone_set('Asia/Kolkata');
$datetime = date('Y-m-d H:i:s');
$id = $_POST['id'];
$sql ="UPDATE  ah_expences SET exp_cat_id='$exp_cat_id',exp_no='$exp_no',exp_date='$exp_date',total_amt='$total_amt' WHERE id='$id'";
if  (mysqli_query($conn, $sql)) {
  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_amt = mysqli_real_escape_string($conn,$_POST['unit_amt'][$i]);
     $tax_rate = mysqli_real_escape_string($conn,$_POST['tax_rate'][$i]);
     $ttl_amt = mysqli_real_escape_string($conn,$_POST['ttl_amt'][$i]);
    $sql_prd ="UPDATE ah_expences_item_details SET exp_id='$id',item_name='$item_name',quantity='$qty',unit='$unit_amt',tax_rate='$tax_rate',amount='$ttl_amt' WHERE id='$sid'";
    $prd_res=mysqli_query($conn, $sql_prd) or die(mysqli_error());
  }
}
     echo "<script>location.replace('all-expences.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">Edit Expences</h3>
                                    </div> 
                                </div>
                                <?php $idd=$_GET['id'];
                                $sql="select * from ah_expences where id='".$idd."'"; 
                                $result = mysqli_query($conn, $sql); 
                                $res= mysqli_fetch_array($result);
                                $cid=$res['exp_cat_id'];
                                $sqlpt=mysqli_query($conn,"SELECT * from expenses_category 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-4 mt-2">
                                                    <select class="form-control" name="exp_cat_id" required>
                                                       <option value="<?= $restpy['id'];?>"><?= $restpy['ename'];?></option>
                                                         <?php $sqlct=mysqli_query($conn,"select * from expenses_category");
                                                        while($resct= mysqli_fetch_array($sqlct)){ ?>
                                                        <option value="<?= $resct['id'];?>"><?= $resct['ename'];?></option>
                                                        <?php } ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-2">
                                                <label class="form-label">Expences No</label>
                                                <input type="text" value="<?= $res['exp_no'];?>" name="exp_no" placeholder="Enter Expences Number" class="form-control">
                                                <input type="hidden" value="<?= $res['id'];?>" name="id" class="form-control"></td>
                                            </div>
                                            <div class="mb-2">
                                                <label class="form-label">Expences Date</label>
                                                <input type="text"  name="exp_date" value="<?= $res['exp_date'];?>" 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;">Price/Unit</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>
                                                 
                                          </tr>  
                                     </thead>
                                        <tbody id="">
                                        <?php $i=1; $idd=$_GET['id'];
                                        $sqlsl=mysqli_query($conn,"Select ads.*,ait.item_name from ah_expences_item_details ads join ah_expense_item ait on ads.item_name=ait.id where ads.exp_id='".$idd."'"); 
                                         while($resl= mysqli_fetch_array($sqlsl)){ 
                                         $tid=$resl['tax_rate'];
                                         $sqlts=mysqli_fetch_array(mysqli_query($conn,"select * from tax_rate where id='".$tid."'"));
                                        $tax=$sqlts['tax_gst'];
                                        $prc=$resl['unit'] * $resl['quantity'];
                                        $tax_rate=filter_var($tax, FILTER_SANITIZE_NUMBER_INT);
                                        $taxtd=$prc*$tax_rate/100;   
                                            ?>
                                            <tr  class="dynamic_field customer_records">
                                                <td><?php echo $i; $i++; ?>.</td>
                                                <td> <select class="form-control it_id" name="item_name[]" id="item_name">
                                                     <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" name="qty[]" id="qty" class="form-control qty" value="<?= $resl['quantity'];?>" style="border:0px solid #ccc;border-bottom:1px solid #ccc">
                                               <input type="hidden" value="<?= $resl['id'];?>" name="sid" class="form-control"></td></td> 

                                                <td><input type="text" name="unit_amt[]" id="unit_amt" class="form-control unit_amt" value="<?= $resl['unit'];?>" 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="<?= $sqlts['id'];?>"><?= $sqlts['tax_gst'];?></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" value="<?= $taxtd;?>" style="border:0px solid #ccc;border-bottom:1px solid #ccc"></td> 
                                                    <td><input type="text" id="ttl_amt" value="<?= $resl['amount'];?>" 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>
                                            <?php } ?>
                                          <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="3"><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="2" 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-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" value="<?= $res['total_amt']; ?>" 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">
                        </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" value="<?= $res['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">
                        </div>
                       <div class="mb-1 col-md-4"></div>
                      
                        <div class="mb-1 col-md-4" style="margin-top:5px;">
                            
                        </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", ".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 total = price * qty;
      var rtotal =total;
      row.find("#ttl_amt").val(isNaN(rtotal) ? "" : rtotal);
      row.find("#httl_amt").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", ".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_item_expences.php',
            data:{it_id: it_id},
            dataType:'json',
            success:function(data){
                console.log(data);
                row.find('#unit_amt').val(data.price);
                 row.find('#tax_gst').val(data.tax_rate); 
                 row.find('#ttl_amt').val(data.price); 
                 row.find('#httl_amt').val(data.price); 
             //$('#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>