<?php
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'general_purchase_new_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 GENERAL PURCHASE</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'], 'general_purchase_list') ) { ?>
          <a href="index.php?page=general_purchase/new_list.php" class="btn btn-danger capital bottom10 custome-btn">VIEW GENERAL PURCHASE 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="general_purchase/new_insert.php" method="post" enctype="multipart/form-data" class="common-frm-validation" id="signupForm">
                <div class="row">
                   <div class="col-md-1">
                      <div class="form-group">
                        <label class="capital">SERIAL</label><span style="color: red">*</span>
                        <input type="text" size="35" id="code" name="code" class="form-control" autocomplete="off" value="<?php echo GeneralPurchase_new($conn);?>" readonly="" autofocus=""/>
                      </div>
                   </div>
                   <div class="col-md-2">
                      <div class="form-group">
                        <label class="capital">INVOICE NO</label><span style="color: red">*</span>
                        <input type="text" size="35" id="bill_no" name="bill_no" class="form-control" autocomplete="off" placeholder="INVOICE NO"/>
                      </div>
                   </div>

                   <div class="col-md-3">
                      <div class="form-group">
                         <label class="capital">vendor</label><span style="color: red">*</span>
                         <select class="form-control select2 required product-name" name="vendor_id" id="vendor_id">
                            <option></option>
                            <?php 
                            $truck     = "SELECT * FROM `act_master` WHERE `account_group` = 'SUNDRY CREDITORS'";
                            $truck_res = mysqli_query($conn,$truck);
                            while ($truck_row = mysqli_fetch_array($truck_res)) { ?>
                            <option value="<?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">INVOICE DATE</label><span style="color: red">*</span>
                          <div class="input-group date date-picker" data-date-format="dd-mm-yyyy">
                            <div class="input-group-addon">
                               <i class="fa fa-calendar"></i>
                            </div>
                            <input type="text" size="35" id="bill_date" name="bill_date" class="form-control date-picker required" placeholder="DATE" autocomplete="off" value="<?php echo date('d-m-Y')?>" />
                         </div>
                      </div>
                   </div>
                   <div class="col-md-2">
                         <div class="form-group pading-left15">
                            <label class="capital">ATTACHMENT</label><span style="color: red">*</span>
                             <input type="file" size="35" id="gp_img" name="gp_img" autocomplete="off" class="image" />
                              <input type="hidden" name="old_gp_img" value="">
                         </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="3%">#</th>
                            <th class="text-left" width="">DESCRIPTION</th>
                            <th class="text-center" width="7%">HSN</th>
                            <th class="text-center" width="15%">QTY</th>
                            <th class="text-center" width="5%">UNIT</th>
                            <th class="text-center" width="8%">RATE</th>
                            <th class="text-center" width="10%">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><input type="text" name="product[<?php echo $i; ?>][description]" class="form-control lr_no description top add-more-table count" placeholder="Enter Description" data-count="<?php echo $i;?>" autocomplete="off">
                              </td>

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

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

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

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

                              <td><input type="text" name="product[<?php echo $i; ?>][amount]" class="form-control amount top add-more-table count" readonly="readonly" tabindex="-1"></td>

                              <td><input type="text" name="product[<?php echo $i; ?>][remark]" class="form-control remark top add-more-table count" autocomplete="off"></td>
                          </tr>
                          <?php $i++; ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
                <legend class="hitz-legend">PAYMENT DETAIL</legend>
                <div class="row">
                  <div class="col-md-4">
                    <div class="col-md-12" id="tax_addition_wapper">
                      <table class="table table-bordered">
                          <tbody>
                            <?php
                              $tax =  "SELECT * FROM `tax_mst` WHERE `sign` = '+' AND FIND_IN_SET('GANERAL PURCHASE', module)";
                              $tax_res = mysqli_query($conn,$tax);

                              $tax_rows = array();
                              while($tax_row = mysqli_fetch_assoc($tax_res)) {
                                $tax_rows[] = $tax_row;
                              }
                            ?>

                            <?php for ($i=1; $i <=4 ; $i++) { ?>
                             <tr>
                                <td>
                                  <select class="form-control chosen-select height29 hitz-add" name="add[<?php echo $i ?>][tax_mst_id]" >
                                      <option value></option>
                                      <?php foreach ($tax_rows as $tax_row) { ?>
                                        <option value="<?php echo $tax_row['id'];?>"><?php echo $tax_row['descr'];?></option>
                                      <?php } ?>
                                  </select>
                                </td>
                                <td width="30%;"><input type="text" name="add[<?php echo $i ?>][amount]" class="form-control hitz_add height29 payment-table number addition" data-count="<?php echo $i ?>" readonly="" autocomplete="off"></td>
                             </tr>
                            <?php } ?>
                            
                          </tbody>
                       </table>
                    </div>
                    <div class="col-md-12">
                      <table class="table table-bordered">
                        <tbody>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">SGST</label></td>

                            <td width="25%;"><input type="text" id="sgst_per" name="sgst_per" class="form-control height29 number payment-table sgst_per gst-cal" autocomplete="off" placeholder="SGST(%)"></td>
                            
                            <td><input type="text" name="sgst_amount" id="sgst_amount" class="form-control height29 number payment-table sgst_amount" autocomplete="off" placeholder="SGST(₹)" readonly=""></td>
                          </tr>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">CGST</label></td>
                            <td width="25%;"><input type="text" id="cgst_per" name="cgst_per" class="form-control height29 number payment-table cgst_per gst-cal" autocomplete="off"  placeholder="CGST(%)"></td>
                             <td><input type="text" name="cgst_amount" id="cgst_amount" class="form-control height29 number payment-table cgst_amount" autocomplete="off" placeholder="CGST(₹)" readonly=""></td>
                          </tr>
                          <tr>
                            <td width="35%;" align="center"><label class="capital">IGST</label></td>
                            <td width="25%;"><input type="text" id="igst_per" name="igst_per" class="form-control height29 number payment-table igst_per gst-cal" autocomplete="off"  placeholder="IGST(%)"></td>
                             <td><input type="text" name="igst_amount" id="igst_amount" class="form-control height29 number payment-table igst_amount" autocomplete="off" placeholder="IGST(₹)" readonly=""></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="col-md-12" id="tax_deduction_wapper">
                      <table class="table table-bordered">
                        <tbody>
                          <?php for ($i=1; $i <=4 ; $i++) { ?>
                          <tr>
                            <td>
                              <?php 
                                $d_tax =  "SELECT * FROM `tax_mst` WHERE `sign` = '-' AND FIND_IN_SET('GANERAL PURCHASE', module)";
                                $d_tax_res = mysqli_query($conn,$d_tax);
                                $d_tax_rows = array();
                                while($d_tax_row = mysqli_fetch_assoc($d_tax_res)) {
                                  $d_tax_rows[] = $d_tax_row;
                                }
                              ?>
                                <select class="form-control chosen-select height29 hitz-del payment-table" name="sub[<?php echo $i ?>][tax_mst_id]">
                                  <option value></option>
                                  <?php foreach ($d_tax_rows as $d_tax_row) { ?>
                                  <option value="<?php echo $d_tax_row['id'];?>"><?php echo $d_tax_row['descr'];?></option>
                                  <?php } ?>
                                </select>
                            </td>
                            
                            <td width="30%;"><input type="text" name="sub[<?php echo $i ?>][amount]" class="form-control hitz_subs height29 number payment-table deduction" data-count="<?php echo $i ?>" readonly="" autocomplete="off"></td>
                          </tr>
                          <?php } ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="col-md-4">
                      <div class="form-group">
                        <label class="capital">TOTAL ADDITION</label>
                        <input type="text" size="35" id="other_add" name="other_add" class="form-control other_add" autocomplete="off" placeholder="TOTAL" readonly="" />
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label class="capital">TOTAL DEDUCTION</label>
                        <input type="text" size="35" id="other_less" name="other_less" class="form-control other_less" autocomplete="off" placeholder="TOTAL" readonly="" />
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label class="capital">TOTAL AMOUNT</label>
                        <input type="text" size="35" id="total_amnt" name="total_amnt" class="form-control" autocomplete="off" placeholder="TOTAL AMOUNT" readonly=""/>
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label class="capital">GROSS AMOUNT</label>
                        <input type="text" size="35" id="gross_amnt" name="gross_amnt" class="form-control" autocomplete="off" placeholder="GROSS AMOUNT" readonly="" />
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="form-group">
                        <label class="capital">NET AMOUNT</label>
                        <input type="text" size="35" id="net_amnt" name="net_amnt" class="form-control" autocomplete="off" placeholder="NET AMOUNT" readonly=""/>
                        <input type="hidden" name="id" value="">
                      </div>
                    </div>
                    <div class="col-md-11">
                      <div class="form-group">
                        <label class="capital">remark</label>
                        <textarea class="form-control hit-textarea" autocomplete="off" name="remarks" id="remarks" style="height: 50px !important;"></textarea>
                      </div>
                    </div>
                  </div>
                </div><br/>
                <input type="hidden" value="<?php echo $_SESSION['branch_id'];?>" name="branch_id" id="branch_id">
                <input type="hidden" value="BILL" name="module" id="module">
                <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=general_purchase/new_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%][description]" value="" class="form-control lr_no description top add-more-table count" placeholder="Enter Description" data-count="<?php echo $i;?>" autocomplete="off">
          </td>

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

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

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

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

          <td><input type="text" name="product[%i%][amount]" class="form-control amount top add-more-table count" readonly="readonly" tabindex="-1"></td>

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

          
      </tr>
   </table>
</div>
<script type="text/javascript">
  jQuery(document).ready(function() {
    $('#vendor_id').select2();
    $(".chosen-select").chosen({disable_search_threshold: 1});
    
    $(document).on('keyup', ".gst-cal", function() {
      calculateFinalAmount();
    });

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

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

    $(document).on('change', '.count', function() {
      var $id = jQuery(this).closest('tr').find('.lr_no').attr('data-count');
      calculateAmount($id);
    });

    $(document).on('change', '.hitz-del', function() {
      var $tr = jQuery(this).closest('tr').find('.deduction').attr('data-count');
      jQuery('input[name="sub[' + $tr + '][tax_per]"]').removeAttr("readonly", "readonly");
      jQuery('input[name="sub[' + $tr + '][amount]"]').removeAttr("readonly", "readonly");
    });

    $(document).on('change', '.hitz-add', function() {
      var $trs = jQuery(this).closest('tr').find('.addition').attr('data-count');
      jQuery('input[name="add[' + $trs + '][amount]"]').removeAttr("readonly", "readonly");
    });

    var $length = 0;
    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('.lr_no').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();
      jQuery('.date-picker').datepicker({
        orientation     : "center",
        todayHighlight  : true,
        todayBtn        :  1,
        autoclose       : true,
        format: 'dd-mm-yyyy',
      });
    });

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

function calculateAmount($id){
  var $tr = jQuery('input[name="product[' + $id + '][description]"]').closest('tr');
  var $qty = parseFloat($tr.find('.qty').val());
  if ($qty == '' || $qty == undefined || isNaN($qty)) {
    $qty = 0;
  }

  var $rate = parseFloat($tr.find('.rate').val());
  if ($rate == '' || $rate == undefined || isNaN($rate)) {
    $rate = 0;
  }
  
  var $amount = $qty * $rate;
  $tr.find('.amount').val($amount.toFixed(2));
  calculateFinalAmount();
}

function calculateFinalAmount() {
  var $product_wapper      = jQuery('#product-wapper').find('table tbody tr');
  var $tax_addition_wapper = jQuery('#tax_addition_wapper').find('table tbody tr');
  var $tax_deduction_wapper= jQuery('#tax_deduction_wapper').find('table tbody tr');

  var $amount = 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;
    }
    $amount += $tmp_amt;
  });
  
  // ADDITION
  var $net_amts = 0;
  $tax_addition_wapper.each(function(i, v) {
    $add_amnt  = parseFloat(jQuery(v).find('.hitz_add').val());
      if ($add_amnt == '' || $add_amnt == undefined || isNaN($add_amnt)) {
        $add_amnt = 0;
      }
    $net_amts += $add_amnt;
  });
  $other_add  = $net_amts;

  //DEDUCTION
  var $sub_amnts = 0;
  $tax_deduction_wapper.each(function(i, v) {
    $sub_amnt  = parseFloat(jQuery(v).find('.hitz_subs').val());
      if ($sub_amnt == '' || $sub_amnt == undefined || isNaN($sub_amnt)) {
        $sub_amnt = 0;
      }
    $sub_amnts += $sub_amnt;
  });

  /* GST CALCULATION */

    $total_net_amount = $amount + $other_add;
    var $sgst = parseFloat(jQuery('#sgst_per').val());
    if ($sgst == '' || $sgst == undefined || isNaN($sgst)) {
      $sgst = 0;
    }
    
    var $cgst = parseFloat(jQuery('#cgst_per').val());
    if ($cgst == '' || $cgst == undefined || isNaN($cgst)) {
      $cgst = 0;
    }

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


    if($sgst !='' || $cgst !=''){
      jQuery('input[name="igst_per"]').attr("readonly", "readonly");
    }else{
      jQuery('input[name="igst_per"]').removeAttr("readonly", "readonly");
    }

    if($igst !=''){
      jQuery('input[name="sgst_per"]').attr("readonly", "readonly");
      jQuery('input[name="cgst_per"]').attr("readonly", "readonly");
    }else{
      jQuery('input[name="sgst_per"]').removeAttr("readonly", "readonly");
      jQuery('input[name="cgst_per"]').removeAttr("readonly", "readonly");
    }

    $sgst_amount   = ($sgst * $total_net_amount)/100;
    $cgst_amount   = ($cgst * $total_net_amount)/100;
    $igst_amount   = ($igst * $total_net_amount)/100;
    
    $other_less       = $sub_amnts;
    $net_amount       = $amount + $other_add - $other_less  + $sgst_amount + $cgst_amount + $igst_amount;
    $total_amount     = $amount;
    
    jQuery('#sgst_amount').val($sgst_amount.toFixed(2));
    jQuery('#cgst_amount').val($cgst_amount.toFixed(2));
    jQuery('#igst_amount').val($igst_amount.toFixed(2));

    jQuery('#other_add').val($other_add.toFixed(2));
    jQuery('#other_less').val($other_less.toFixed(2));
    jQuery('#total_amnt').val($total_amount.toFixed(2));
    jQuery('#gross_amnt').val($total_amount.toFixed(2));
    jQuery('#net_amnt').val($net_amount.toFixed(2));
}

</script>