<?php
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'bank_payment_edit') ) {
    echo '<script>window.location.href="index.php?page=no_permission.php"</script>';die();
  }

  if (isset($_REQUEST['eid']) && !empty($_REQUEST['eid']) && $_REQUEST['eid']!=0){
    $select_update     = "SELECT * FROM payment WHERE id='".$_REQUEST['eid']."' AND company_id = '".$_SESSION['company_id']."' AND branch_id = '".$_SESSION['branch_id']."'";
    $select_update_res = mysqli_query($conn,$select_update);
    $update_row        = mysqli_fetch_array($select_update_res,MYSQLI_BOTH);
    
    $master_accounts = combine(getAllRecords('act_master'), 'act_code', 'party_code');
    $party_code      = @$master_accounts[$update_row['account_name']];
    $vendor          = "SELECT * FROM `vendor_master` WHERE `code` = '".$party_code."'";
    $vendor_res      = mysqli_query($conn, $vendor);
    $vendor_row      = mysqli_fetch_assoc($vendor_res);
    $lrs             = explode(',', trim($update_row['lr_no']));
  }
  

?>
<style type="text/css">
 .height29 {
    height: 60px !important;
  }
</style>
<section class="content-header">
  <div class="row">
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 bottom20">
        <h3 class="capital font15 padding5 bold">UPDATE BANK PAYMENT</h3>
      </div>
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 text-right bottom20">
        <h3>
          <?php if( hasPermission($_SESSION['user_detail']['role_id'], 'bank_receipt_list') ) { ?>
          <a href="index.php?page=bank_payment/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW BANK PAYMENT DETAILS</a>
          <?php } ?>
        </h3>
      </div>
  </div>
</section>
<hr class="bottom35"> 
<section class="hitz-top-header">
   <div class="row bottom40">
      <div class="col-xs-12">
         <div class="box box-success">
            <div class="box-body">
              <form action="bank_payment/insert.php" method="post" enctype="multipart/form-data" class="common-frm-validation" id="signupForm">
                <div class="row">
                  <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">VOUCHER NO</label><span style="color: red">*</span>
                      <input type="text" size="35" id="voucher_no" name="voucher_no" class="form-control" autocomplete="off" placeholder="VOUCHER NO" value="<?php echo $update_row['voucher_no'];?>" readonly="" autofocus=""/>
                    </div>
                  </div>

                  <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">DATE</label><span style="color: red">*</span>
                        <div class="input-group date">
                          <div class="input-group-addon">
                             <i class="fa fa-calendar"></i>
                          </div>
                          <input type="text" size="35" id="b_date" name="b_date" class="form-control date-picker" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y', strtotime($update_row['b_date']));?>" />
                        </div>
                    </div>
                  </div>

                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">BANK</label><span style="color: red">*</span>
                      <select class="form-control select2 required" name="bank" id="bank">
                        <option></option>
                        <?php 
                          $truck     = "SELECT * FROM `act_master` WHERE `account_group` ='BANK'";
                          $truck_res = mysqli_query($conn,$truck);
                          while ($truck_row=mysqli_fetch_array($truck_res)) { ?>f
                          <option <?php if($truck_row['id'] == $update_row['bank']) { echo "selected='selected'"; } ?> value="<?php echo $truck_row['id']?>"><?php echo $truck_row['ac_name']?></option>
                          <?php } ?>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">ACCOUNT NAME</label><span style="color: red">*</span>
                      <select class="form-control select2 required" name="account_name" id="account_name" onchange="Checkbank(this.value);GetLrData(this);">
                        <option></option>
                          <?php 
                            $truck     = "SELECT * FROM `act_master`";
                            $truck_res = mysqli_query($conn,$truck);
                            while ($truck_row=mysqli_fetch_array($truck_res)) { ?>
                              <option <?php if($truck_row['act_code'] == $update_row['account_name']) { echo "selected='selected'"; } ?> value="<?php echo $truck_row['id']?>"><?php echo $truck_row['act_code']?> - <?php echo $truck_row['ac_name']?></option>
                            <?php } ?>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">AMOUNT</label><span style="color: red">*</span>
                      <input type="text" size="35" id="amount" name="amount" class="form-control amount required number" autocomplete="off" placeholder="AMOUNT" value="<?php echo $update_row['amount'];?>" />
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">NARRATION</label>
                      <textarea class="form-control height29" autocomplete="off" placeholder="NARRATION" name="narration"><?php echo $update_row['narration'];?></textarea>
                    </div>
                  </div>
                 <div class="col-md-3">
                    <div class="form-group">
                        <label class="capital">LR NO</label>
                        <select class="form-control select2" name="lr_no[]" id="lr_no" multiple="multiple">
                            <?php
                            session_start(); 
                            $company_id = $_SESSION['company_id'];
                            $branch_id = $_SESSION['branch_id'];
                            $lrs = isset($lrs) ? $lrs : array(); 
                            $query = "SELECT lr_no FROM lr_mst WHERE company_id = '$company_id' AND branch_id = '$branch_id' ";
                            $result = mysqli_query($conn, $query);
                            
                            if ($result) {
                                while ($row = mysqli_fetch_assoc($result)) {
                                    $selected = in_array($row['lr_no'], $lrs) ? 'selected' : '';
                                    echo "<option value='{$row['lr_no']}' {$selected}>{$row['lr_no']}</option>";
                                }
                            } else {
                                echo "<option value=''>No LR NOs Found</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>

                  <input type="hidden" name="id" id="id" value="<?php echo $_GET['eid'];?>">
                </div>
                <hr>
                <div class="row" align="center">
                  <button id="btn" class="btn btn-primary ajax-submit capital" type="submit"> UPDATE & SAVE</button>
                  <a href="index.php?page=bank_payment/list.php" class="btn btn-danger capital"> Cancel</a>
                </div>
              </form>
              
            </div>
         </div>
      </div>
   </div>
</section>

<script type="text/javascript">
  jQuery(document).ready(function() {
    $('#vendor_id').select2();
    $('#account_name').select2();
    $('#location_id').select2();
    $('#lr_no').select2();
    $(document).on('keyup', 'input[name="adv_amnt"]', function() {
      var dv = $(this).val();
      var net_payable_amt = $('input[name="total"]').val();
      var due_amnt = net_payable_amt - dv;
      $('input[name="balance"]').val(due_amnt);
    });

    $('#payment_mode').select2();
    $('#bank').select2();
    $(document).on('keyup', ".adj_amnt", function() {
      FinalAmount();
    });
  });

  $(document).ready(function() {
    $('#lr_no').select2();
});
  
  function calculateFinalAmount(e) {
    var $partent = jQuery(e).closest('tr');
    $a = parseFloat($partent.find('.due_amnt').val());
    if ($a == '' || $a == undefined || isNaN($a)) {
      $a = 0;
    }
    
    $b = parseFloat($partent.find('.adj_amnt').val());
    if ($b == '' || $b == undefined || isNaN($b)) {
      $b = 0;
    }
    
    $c = $a - $b;
    $partent.find('.balance').val($c);
  }

  function FinalAmount() {
    var $product_wapper = jQuery('#product-wapper').find('table tbody tr');
    var $amount = 0;
    $product_wapper.each(function(i, v) {
      $tmp_amt  = parseFloat(jQuery(v).find('.adj_amnt').val());
      if ($tmp_amt == '' || $tmp_amt == undefined || isNaN($tmp_amt)) {
        $tmp_amt = 0;
      }
      $amount += $tmp_amt;
    });
    jQuery('#amount').val($amount.toFixed(2));
  }
  
  function Checkbank() {
    var account_name = $("#account_name").val();
    var bank         = $("#bank").val();

    $.ajax({
         'type': 'POST',
         'url': 'bank_receipt/check_bank.php',
         'data': {
            'bank': bank,
            'account_name': account_name
         },
         dataType: 'JSON',
         success: function (result) {
            if(result.status == 1) {
               jQuery('.submit').attr('disabled', false);
            }else{
              jQuery('.submit').attr('disabled', true);
              swal("Opps !!", "SAME ACCOUNT DETECT...!!!", "info")
              setTimeout("location.reload(true);",2000);      
            }
         }
      });

  }
  function get_voucher_details(str) {
    if (str == "") {
      document.getElementById("txtHints01").innerHTML = "";
      return;
    }
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHints01").innerHTML = this.responseText;
      }
    }
    xmlhttp.open("GET", "bank_receipt/get_voucher.php?q=" + str, true);
    xmlhttp.send();
  }

function GetLrData(ele) {
    var account_name = $("#account_name").val(); 
    $.ajax({
        type: "POST",
        url: "bank_payment/get_lr_data.php",
        data: { 'account_name': account_name },
        beforeSend: function() {
            $("#lr_no").addClass("loader");
        },
        success: function(data) {
            if (data.trim()) {
                $("#lr_no").html(data); 
            } else {
                console.log("No matching LR numbers found.");
            }
        },
        complete: function() {
            $("#lr_no").removeClass("loader");
        }
    });
}
</script>