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

  if (isset($_REQUEST['p1']) && !empty($_REQUEST['p1'])){
    $payment = mysqli_query($conn, "SELECT * FROM `payment` WHERE `voucher_no` = '".$_REQUEST['p1']."' AND flag = 'BR' GROUP BY voucher_no");
    $payment_row = mysqli_fetch_assoc($payment);
    $id         = $payment_row['id'];
    $code       = $payment_row['voucher_no'];
    $b_date     = $payment_row['b_date'];
    $bank       = $payment_row['bank'];
    $bank_name  = $payment_row['bank_name'];
    $branch_data= $payment_row['branch'];
    $cheq_no    = $payment_row['cheq_no'];
    $cheq_date  = $payment_row['cheq_date'];

    $paymnt_details = mysqli_query($conn, "SELECT * FROM `payment` WHERE `voucher_no` = '".$_REQUEST['p1']."' AND flag = 'BR' ORDER BY id ASC");
    $detail = array();
    while ($rows = mysqli_fetch_assoc($paymnt_details)) {
      $detail[] = $rows;
    }

  }else{
    $id         = '';
    $code       = brCode($conn);
  }
?>

<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"><?php echo ($id == 0) ? 'ADD NEW BANK RECEIPT' : 'EDIT BANK RECEIPT'; ?></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_receipt/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW BANK RECEIPT 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_receipt/insert.php" method="post" enctype="multipart/form-data" class="common-frm-validation" id="signupForm">
                <div class="row">
                  <div class="col-md-7">
                    <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 $code;?>" readonly="" autofocus=""/>
                        </div>
                      </div>
                      
                      <div class="col-md-3">
                        <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 risFormatDate($b_date, 'd-m-Y')?>" />
                            </div>
                        </div>
                      </div>
                      
                      <div class="col-md-5">
                        <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)) { ?>
                              <option <?php if($truck_row['id'] == $bank) { echo "selected='selected'"; } ?> value="<?php echo $truck_row['id']?>"><?php echo $truck_row['ac_name']?></option>
                              <?php } ?>
                          </select>
                        </div>
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-xs-12 col-sm-12">
                        <div id="product-wapper">
                          <table class="table table-bordered">
                            <thead>
                              <tr>
                                <th class="text-center" width="10">#</th>
                                <th class="text-center">ACCOUNT NAME</th>
                                <th class="text-center" width="120">AMOUNT</th>
                                <th class="text-center" width="170">NARRATION</th>
                              </tr>
                            </thead>
                            <tbody>
                              <?php $i = 0;?>
                              <?php if(isset($detail) && count($detail) > 0) {
                                foreach ($detail as $key => $detail_data) { 
                                $act_mst = mysqli_query($conn, "SELECT * FROM `act_master` WHERE `act_code` = '".$detail_data['account_name']."'");
                                $act_mst_row = mysqli_fetch_assoc($act_mst);
                              ?>
                              <tr>
                                <td>
                                  <a href="javascript:;" class="btn red btn-block remove-me"><i class="fa fa-minus"></i></a>
                                </td>
                                <td>
                                  <input type="text" name="product[<?php echo $key; ?>][sub_acc]" class="form-control product-name top add-more-table count" placeholder="Search By Account Name" data-count="<?php echo $key;?>" value="<?php echo $act_mst_row['ac_name']?>">

                                  <input type="hidden" name="product[<?php echo $key; ?>][account_id]" class="form-control product-id top add-more-table count" data-count="<?php echo $key;?>" value="<?php echo $act_mst_row['id']?>">

                                  <input type="hidden" name="product[<?php echo $key; ?>][account_code]" class="form-control account-code top add-more-table count" value="<?php echo $detail_data['account_name']?>" value="<?php echo $act_mst_row['act_code']?>">

                                </td>

                                <td>
                                  <input type="text" name="product[<?php echo $key; ?>][amount]" class="form-control top add-more-table number amount count" min="0.001" autocomplete="off" value="<?php echo $detail_data['amount']?>">
                                </td>

                                <td>
                                  <input type="text" name="product[<?php echo $key; ?>][remarks]" class="form-control top add-more-table remarks count" autocomplete="off" value="<?php echo $detail_data['narration']?>">
                                </td>
                              </tr>
                              <?php $i++; ?>
                              <?php } } ?>
                              <tr>
                                <td>
                                  <a href="javascript:;" class="btn green btn-block add-more" style="display: block;"><i class="fa fa-plus"></i></a>
                                  <a href="javascript:;" class="btn red btn-block remove-me" style="display: none;"><i class="fa fa-minus"></i></a>
                                </td>
                                <td>
                                  <input type="text" name="product[<?php echo $i; ?>][sub_acc]" value="" class="form-control product-name top add-more-table count" placeholder="Search By Account Name" data-count="<?php echo $i;?>">

                                  <input type="hidden" name="product[<?php echo $i; ?>][account_id]" value="" class="form-control product-id top add-more-table count" data-count="<?php echo $i;?>">

                                  <input type="hidden" name="product[<?php echo $i; ?>][account_code]" value="" class="form-control account-code top add-more-table count">

                                </td>

                                <td>
                                  <input type="text" name="product[<?php echo $i; ?>][amount]" class="form-control top add-more-table number amount count" min="0.001" autocomplete="off">
                                </td>

                                <td>
                                  <input type="text" name="product[<?php echo $i; ?>][remarks]" class="form-control top add-more-table remarks count" autocomplete="off">
                                </td>
                              </tr>
                              
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-5">
                    <div class="row">
                      <div class="col-sm-6">
                      <div class="form-group">
                        <label class="capital">BANK NAME</label>
                        <input type="text" size="35" id="bank_name" name="bank_name" class="form-control" autocomplete="off" placeholder="BANK NAME" value="<?php echo $bank_name?>" />
                      </div>
                    </div>
                    <div class="col-sm-6">
                      <div class="form-group">
                        <label class="capital">BRANCH</label>
                        <input type="text" size="35" id="branch" name="branch" class="form-control" autocomplete="off" placeholder="BRANCH" value="<?php echo $branch_data?>"/>
                      </div>
                    </div>
                    <div class="col-sm-6">
                      <div class="form-group">
                        <label class="capital">CHEQUE NO</label>
                        <input type="text" size="35" id="cheq_no" name="cheq_no" class="form-control" autocomplete="off" placeholder="CHEQUE NO" value="<?php echo $cheq_no?>"/>
                      </div>
                    </div>
                    <div class="col-sm-4">
                      <div class="form-group">
                        <label class="capital">CHEQUE DATE</label>
                          <div class="input-group date">
                            <div class="input-group-addon">
                               <i class="fa fa-calendar"></i>
                            </div>
                            <input type="text" size="35" id="cheq_date" name="cheq_date" class="form-control date-picker" placeholder="CHEQUE DATE" autocomplete="off" value="<?php echo $cheq_date?>"/>
                          </div>
                      </div>
                    </div>
                    </div>
                  </div>
                </div>
                <hr>
                <div class="row" align="center">
                  <input type="hidden" name="id" id="id" value="<?php echo $id?>">
                  <button id="btn" class="btn btn-primary ajax-submit capital" type="submit"> <?php echo ($id == '') ? 'Save & List' : 'Update & save'; ?></button>
                  <a href="index.php?page=bank_receipt/list.php" class="btn btn-danger capital"> Cancel</a>
                </div>
              </form>
            </div>
         </div>
      </div>
   </div>
</section>
<div id="product-template" style="display:none;">
  <table>
    <tr>
      <td>
        <a href="javascript:;" class="btn green btn-block add-more" style="display: block;"><i class="fa fa-plus"></i></a>
        <a href="javascript:;" class="btn red btn-block remove-me" style="display: none;"><i class="fa fa-minus"></i></a>
      </td>
      <td>
        <input type="text" name="product[%i%][sub_acc]" value="" class="form-control product-name top add-more-table count" placeholder="Search By Account Name" data-count="%i%">

        <input type="hidden" name="product[%i%][account_id]" value="" class="form-control product-id top add-more-table count">

        <input type="hidden" name="product[%i%][account_code]" value="" class="form-control account-code top add-more-table count">
      </td>

      <td>
        <input type="text" name="product[%i%][amount]" class="form-control top add-more-table number amount count" min="0.001" autocomplete="off">
      </td>

      <td>
        <input type="text" name="product[%i%][remarks]" class="form-control top add-more-table remarks count" autocomplete="off">
      </td>
    </tr>
  </table>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery('#bank').select2();
  
  jQuery(document).on('click', '.add-more', function(e) {
    $length = jQuery('#product-wapper').find('table tbody tr').length;
    var $clone = jQuery('#product-template table tr').clone();
    $clone.find('input').each(function() {
      this.name = this.name.replace('[%i%]', '[' + $length + ']');
    });
    
    $clone.find('.product-name').attr('data-count', $length);

    jQuery('#product-wapper table tbody').append($clone);
    jQuery('#product-wapper table tbody').find('.remove-me').show();
    jQuery('#product-wapper table tbody').find('.add-more').hide();

    jQuery('#product-wapper table tbody').find('.remove-me:last').hide();
    jQuery('#product-wapper table tbody').find('.add-more:last').show();
    materialDetaIlsautocomplete(material_details_autocomplete);
  });

  jQuery(document).on('click', '.remove-me', function(e) {
    e.preventDefault();
    jQuery(this).closest('tr').remove();
  });

  material_details_autocomplete = {
    minLength: 1,
    source: "config/ajax.php",
    position: {
       my: "left top",
       at: "left bottom",
       collision: "flip"
    },
    focus: function(event, ui) {
       return false;
    },
    select: function(event, ui) {
      if( ui.item.id != undefined ) {
        $checkpoint = false;
        $checkpoint = checkProductExit(ui.item.code, ui.item.id);
        if( $checkpoint ) {
          var $i    = jQuery(this).attr('data-count');
          var $tr   = jQuery('input[name="product[' + $i + '][sub_acc]"]').closest('tr');
          var $sales= jQuery('input[name="product[' + $i + '][sub_acc]"]');
          $sales.val(ui.item.name);
          $tr.find('.product-name').val(ui.item.label);
          $tr.find('.product-id').val(ui.item.id);
          $tr.find('.account-code').val(ui.item.code);
        }else{
          var $this = jQuery(this);
          setTimeout(function(){
          $this.focus();
          $this.select();
          }, 100);
        }
      }
      return false;
    }
  };
  materialDetaIlsautocomplete(material_details_autocomplete);

  jQuery(document).on('keyup', "#product-wapper .product-name", function() {
    var $id = jQuery(this).closest('tr').find('.product-name').attr('data-count');
    CheckValidation($id);
  });
});

function materialDetaIlsautocomplete(material_details_autocomplete) {
  jQuery(".product-name").autocomplete(material_details_autocomplete).each(function() {
    jQuery(this).autocomplete("instance")._renderItem = function(ul, item) {
      $str = '<a><span> ACCOUNT NAME - ' + item.label + ' </span> <br/> <span>ACCOUNT CODE - ' + item.code + ' </span></a>';
        return jQuery("<li>").append($str).appendTo(ul);
    };
  });
}

function checkProductExit(product_code, product_id){
  var $container = jQuery('#product-wapper');
  var $check = true;

  jQuery.each($container.find('tbody tr'), function(i, v){
    var $tmp_data_count     = jQuery(v).find('.count').attr('data-count');
    var $tmp_product_id     = jQuery('input[name="product['+ $tmp_data_count +'][account_id]"]').val();
   if( $tmp_product_id == product_id ) {
      $check = false;
      return false;
    }
  });

  if( $check ) {
    return true;
  } else {
    showNotification('Alert', 'THIS PRODUCT ALREADY ABOVE MENTION...!!!', 'error');
    return false;
  }
}

function CheckValidation($id) {
  var $tr = jQuery('input[name="product[' + $id + '][sub_acc]"]').closest('tr');
  var $bank = jQuery('#bank').val();
  
  var $account_id = parseFloat($tr.find('.product-id').val());
  if ($account_id == '' || $account_id == undefined || isNaN($account_id)) {
    $account_id = 0;
  }
  if($bank == $account_id){
    showNotification('Alert', 'SAME ACCOUNT DETECT...!!!', 'error');
    $tr.find('.product-name').val('');
    $tr.find('.product-id').val('');
    $tr.find('.account-code').val('');
  }
}
</script>
