<?php
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'jv_add') ) {
    echo '<script>window.location.href="index.php?page=no_permission.php"</script>';die();
  }
?>
<link rel="stylesheet" href="assets/plugins/toaster/jquery.toast.css">
<link rel="stylesheet" href="assets/plugins/toaster/jquery.toast.min.css">
<script src="assets/plugins/toaster/jquery.toast.js"></script>
<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">ADD NEW JOURNAL VOUCHER</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'], 'jv_list') ) { ?>
          <a href="index.php?page=journal_voucher/list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW JOURNAL VOUCHER 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="journal_voucher/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">JOURNAL VOUCHER NO</label><span style="color: red">*</span>
                      <input type="text" size="35" id="jv_no" name="jv_no" class="form-control lr_number" autocomplete="off" placeholder="INVOICE NO" value="<?php echo jvCode($conn);?>" 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="jv_date" name="jv_date" class="form-control date-picker required" placeholder="DATE" autocomplete="off" value="<?php echo risFormatDate(date())?>" />
                       </div>
                    </div>
                  </div>

                  <div class="col-md-3">
                    <div class="form-group">
                       <label class="capital">ACCOUNT</label><span style="color: red">*</span>
                       <select class="form-control select2 required" name="main_acc" id="main_acc" onchange="productAutoComplete()">
                          <option></option>
                          <?php 
                            $truck     = "SELECT * FROM `act_master`";
                            $truck_res = mysqli_query($conn,$truck);
                            while ($truck_row=mysqli_fetch_array($truck_res)) { ?>f
                              <option value="<?php echo $truck_row['act_code']?>"><?php echo $truck_row['ac_name']?></option>
                          <?php } ?>
                       </select>
                       <input type="hidden" name="v_id" id="v_id">
                    </div>
                  </div>
                  <div class="col-md-1">
                    <div class="form-group">
                      <label class="capital">MODE</label><span style="color: red">*</span>
                      <select class="form-control select2 required" name="t_mode" id="t_mode">
                        <option value></option>
                        <option value="CR">CR</option>
                        <option value="DR">DR</option>
                      </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" name="total_amount" id="total_amount" class="form-control number total_amount required">
                    </div>
                  </div>
                  <div class="col-md-2">
                    <div class="form-group">
                      <label class="capital">ADJUST AMOUNT</label>
                      <input type="text" name="total_adjust" id="total_adjust" class="form-control number" readonly="">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-xs-12 col-sm-12">
                    <div id="product-wapper">
                      <table class="table table-bordered table-responsive">
                        <thead>
                          <tr>
                            <th class="text-center" width="5%">#</th>
                            <th class="text-center">ACCOUNT</th>
                            <th class="text-center" width="15%">REF.NO</th>
                            <th class="text-center" width="15%">AMOUNT</th>
                            <th class="text-center" width="15%">REMARK</th>
                            
                          </tr>
                        </thead>
                        <tbody>
                          <?php $i = 0;?>
                          <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 id="lrno">
                              <input type="text" name="product[<?php echo $i; ?>][sub_acc]" value="" class="form-control product-name top add-more-table  jv_cal sub_acc" placeholder="Search By Account Name" data-count="<?php echo $i;?>" onchange="CheckDuplicateRow(this);CheckAccount(this);">

                              <input type="hidden" name="product[<?php echo $i; ?>][act_code]" class="form-control top add-more-table jv_cal act_code">

                             </td>
                            <td><input type="text" name="product[<?php echo $i; ?>][ref_no]" class="form-control top add-more-table jv_cal ref_no"></td>
                            
                            <td><input type="text" name="product[<?php echo $i; ?>][amount]" class="form-control top add-more-table jv_cal number amount check_amount"></td>

                            <td><input type="text" name="product[<?php echo $i; ?>][remarks]" class="form-control top add-more-table jv_cal remarks"></td>
                          </tr>
                          <?php $i++; ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
                <input type="hidden" value="" name="id" id="id">
                <hr>
                <div class="row" align="center">
                  <button id="btn" class="btn btn-primary ajax-submit capital" type="submit"> Save & List</button>
                  <a href="index.php?page=journal_voucher/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 id="lrno">
            <input type="text" name="product[%i%][sub_acc]" class="form-control product-name top add-more-table jv_cal sub_acc" placeholder="Search By Account Name" onchange="CheckDuplicateRow(this);CheckAccount(this);">
            <input type="hidden" name="product[%i%][act_code]" class="form-control top add-more-table jv_cal act_code">
          </td>

          <td><input type="text" name="product[%i%][ref_no]" class="add-more-table jv_cal form-control top ref_no"></td>

          <td><input type="text" name="product[%i%][amount]" class="add-more-table jv_cal form-control top amount check_amount"></td>
          <td><input type="text" name="product[%i%][remarks]" class="add-more-table jv_cal form-control top remarks"></td>
          
      </tr>
   </table>
</div>
<script type="text/javascript">
  jQuery(document).ready(function() {
    $('#main_acc').select2();
    $('#t_mode').select2();
    $(".chosen-select").chosen({disable_search_threshold: 1});
    var $length = 0;
    productAutoComplete();

    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);

       productAutoComplete();
       calculateFinalAmount();
       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();
    });

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

  });
  $(document).on('keyup', ".jv_cal", function() {
    calculateFinalAmount();
  });

  $(document).on('keyup', ".total_amount", function() {
    calculateFinalAmount();
  });

  function productAutoComplete(ele) {
    var $main_acc      = $("#main_acc").val();
    $( ".product-name" ).autocomplete({
      position: { my: "left bottom", at: "left top", collision: "flip" },
      source: function( request, response ) {
        $.ajax({
          url: "journal_voucher/get_account_data.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term,
            main_acc:$main_acc,
          },
          success: function( data ) {
            response( data );
          }
        });
      },
      select: function (event, ui) {
        var $parent = jQuery(this).parents('tr');
        var $i = jQuery(this).attr('data-count');
        $checkpoint = false;
        $checkpoint = CheckDuplicateRow(ui.item.ac_name, ui.item.id);
        if( $checkpoint ) {
          $parent.find('.product-name').val(ui.item.ac_name);
          $parent.find('.act_code').val(ui.item.act_code);
        }else{
          var $this = jQuery(this);
          setTimeout(function(){
            $this.focus();
            $this.select();
          }, 100);
        }
        
        return false;
      }
    }).each(function() {
       $(this).autocomplete( 'instance' )._renderItem = function( ul, item ) {
          return $( "<li>" )
             .append( "<a><span>" + item.ac_name + '</span></a>' )
             .appendTo( ul );
        };
    });
  }

  function CheckAccount(ele){
    var lr_no = $(ele).val();
    var $tr = jQuery(ele).closest('tr');
    $.ajax({
      'type': 'POST',
      'url': 'journal_voucher/check_account.php',
      'data': {
        'lr_no' : lr_no
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          $tr.find('.sub_acc').val(result.sub_acc);
          $tr.find('.act_code').val(result.act_code);
          $.toast({
            heading: 'Error',
            text: 'INVALID ACCOUNT NAME...',
            showHideTransition: 'fade',
            position: 'top-right',
            icon: 'error'
          })  
          $tr.find('.act_code').focus();
          $tr.find('.sub_acc').focus();
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  }
  
  function CheckDuplicateRow(bill_no){
    var $container = jQuery('#product-wapper');
    var $check = true;
    jQuery.each($container.find('tbody tr'), function(i, v){
      var $tmp_data_count     = jQuery(v).find('.jv_cal').attr('data-count');
      var $tmp_bill_no        = jQuery('input[name="product['+ $tmp_data_count +'][sub_acc]"]').val();
      if( $tmp_bill_no == bill_no) {
        $check = false;
        return false;
      }
    });
    if( $check ) {
      return true;
    } else {
      $.toast({
        heading: 'Error',
        text: 'ALREADY EXISTS ABOVE...',
        showHideTransition: 'fade',
        position: 'top-right',
        icon: 'error'
      })  
      return false;
    }
  }

  function calculateFinalAmount(){
    var $product_wapper  = jQuery('#product-wapper').find('table tbody tr');
    var $total_amt = 0;
    var $set_amt = parseFloat(jQuery('#total_amount').val());
    if ($set_amt == '' || $set_amt == undefined || isNaN($set_amt)) {
      $set_amt = 0;
    }

    var $adj_amt = parseFloat(jQuery('#total_adjust').val());
    if ($adj_amt == '' || $adj_amt == undefined || isNaN($adj_amt)) {
      $adj_amt = 0;
    }

    $product_wapper.each(function(i, v) {
      $tmp_amt  = parseFloat(jQuery(v).find('.amount').val());
      if ($tmp_amt == '' || $tmp_amt == undefined || isNaN($tmp_amt)) {
        $tmp_amt = 0;
      }
      $total_amt += $tmp_amt;
      $rem = $set_amt - $total_amt;
      if($total_amt > $set_amt){
        $.toast({
          heading: 'Error',
          text: 'AMOUNT NOT MATCH...',
          showHideTransition: 'fade',
          position: 'top-right',
          icon: 'error'
        })
        jQuery(v).find('.amount').val('').trigger('focus');
        jQuery('#total_adjust').val($set_amt);   
      }
    });
    
    
    jQuery('#total_adjust').val($rem.toFixed(2));
    $(".ajax-submit").attr('disabled', true);
    if($rem == 0){
      $(".ajax-submit").removeAttr('disabled', false); 
    }
    
  }
</script>