<?php




  //invoice.php  




  include('db_con.php');




  include('header.php');




  include('function.php');




  




  if (isset($_SESSION['user_id'])) {




    $user_type = $_SESSION['user_type'];




    $user_id = $_SESSION['user_id'];




    $user_name = $_SESSION['user_name'];




    $branch_id = $_SESSION['branch_id'];




    $branch_name = $_SESSION['branch_name'];




    $store_id = $_SESSION['store_id'];




    $store_name = $_SESSION['store_name'];




}else{




  header('Location: login');




  die();




}




$dated = date('Y-m-d');




$store_name = 'Select Store';









  $po_no = $_GET["id"];




  $default_store = $_GET['store'];




  if($default_store !='')




  {




     $sql = "SELECT store_name FROM store WHERE store_id = '".$default_store."' ";




            $statement = $connect->prepare($sql);




            $statement->execute(); // no need to add `$sql` here, you can take that out




            $store_name = $statement->fetchColumn();




  }









 














  




  














if(isset($_POST["save"]))




  {














   




    









    









    




    $statement = $connect->prepare("




      INSERT INTO purchase




        (po_no,branch_id,inv_no,dated,v_id,description,discount,inv_amt,inv_type,freight,others,item_cost_sm,cur_name,cur_rate,user_id,status)




        VALUES (:po_no, :branch_id, :inv_no, :dated, :v_id, :description, :discount, :inv_amt, :inv_type, :freight, :others, :item_cost_sm,




           :cur_name, :cur_rate, :user_id, :status)




    ");




    $statement->execute(




      array(




          ':po_no'             =>  trim($_POST["po_no"]),




          ':branch_id'             =>  $branch_id,




          ':inv_no'             =>  trim($_POST["inv_no"]),




          ':dated'             =>  $_POST['dated'],




          ':v_id'          =>  trim($_POST["v_id"]),




          ':description'       =>  $_POST["description"],




          ':discount'       =>  trim($_POST["discount"]),




          ':inv_amt'       =>  trim($_POST["inv_amt"]),




          ':inv_type'       =>  $_POST["inv_type"],          




          ':freight'       =>  trim($_POST["freight"]),




          ':others'       =>  trim($_POST["others"]),




          ':item_cost_sm'       =>  trim($_POST["item_cost_sm"]),




          ':cur_name'       =>  $_POST["cur_name"],




          ':cur_rate'       =>  trim($_POST["cur_rate"]),




          ':user_id'       =>  $user_id,          




          ':status'       =>  'Active'




          




      )




    );









      $statement = $connect->query("SELECT LAST_INSERT_ID()");




      $p_id = $statement->fetchColumn();









      $sql = "delete from p_detail";









          $statement = $connect->prepare($sql);









          $statement->execute();









      for($count=0; $count<$_POST["total_item"]; $count++)




      {














        $statement = $connect->prepare("




          INSERT INTO p_detail




          (p_id,item_no,store_id,qty,rate,ln_no)




          VALUES(:p_id, :item_no, :store_id, :qty, :rate,:ln_no)




        ");









        $statement->execute(




          array(




            ':p_id'               =>  $p_id,            




            ':item_no'              =>  trim($_POST["item_no"][$count]),




            ':store_id'              =>  trim($_POST["store_id"][$count]),




            ':qty'          =>  trim($_POST["qty"][$count]),




            ':rate'           =>  trim($_POST["rate"][$count]),




            ':ln_no'        => $count




        




          )




        );




      }














     














        $sql ="




          INSERT INTO purchase_detail SELECT p_id,item_no,store_id,sum(qty) qty,rate,ln_no,




          0 as cur_rated, 0 as pre_stock, 0 as pre_cost, 0 as pre_cost_sm,0 as cur_amount,




          0 as pre_amount,0 as total_stock, 0 as total_amount,0 as item_cost, 0 as item_cost_sm,




          0 as cost_up, 0 as cost_up_sm,0 as cost_rate,0 as cost_rate_sm,0 as adj_cost




          from p_detail group by p_id,item_no,store_id 




          




          ";




        $statement = $connect->prepare($sql);









        $statement->execute();



















 $sql ="




          select sum(qty*rate) from purchase_detail where p_id = '".$p_id."'




          




          ";




        $statement = $connect->prepare($sql);









        $statement->execute();














        $inv_amt = $statement->fetchColumn();









         $sql ="




          update purchase set inv_amt = '".$inv_amt."' where p_id = '".$p_id."'




          




          ";




        $statement = $connect->prepare($sql);









        $statement->execute();














          $sql = "update purchase set or_inv_amt = inv_amt*cur_rate,




          or_freight = freight*cur_rate where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();


































          $sql = "select inv_amt from purchase where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $inv_amt = $statement->fetchColumn();



















          $sql = "select discount from purchase where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();














          $discount = $statement->fetchColumn();









     




           stock_update($connect);














          




          $cur_rate = trim($_POST["cur_rate"]);









          $freight =  trim($_POST["freight"]);









          $others = trim($_POST["others"]); 









          $item_cost_sm = trim($_POST["item_cost_sm"]); 









         









         









          $or_inv_amt = $inv_amt * $cur_rate;









          $or_freight = $freight * $cur_rate;









          $tot_exp = $or_freight + $others;









         if($tot_exp > 0)




          {




           $cost_up = $tot_exp / $or_inv_amt; 




          }









          if($item_cost_sm > 0)




          {




            $cost_up_sm = $item_cost_sm / $or_inv_amt;




          }









          $cost_down = 0;




          $or_discount = 0;









          if($discount > 0)




          {




            $or_discount = $discount * $cur_rate;




            $cost_down = $or_discount / $or_inv_amt;




            $cost_up = $cost_up - $cost_down;









          }
























          $sql = "update purchase_detail set cost_up = '".$cost_up."' where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update purchase_detail set cost_up_sm = '".$cost_up_sm."' where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();





























          $sql = "update purchase_detail set cur_rated = rate * '".$cur_rate."' where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();














          $sql = "update purchase_detail set cost_rate = cur_rated * cost_up where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update purchase_detail set cost_rate_sm = cur_rated * cost_up_sm where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update purchase_detail set adj_cost = cur_rated + cost_rate where p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();














          $sql = "update purchase_detail d, items i set d.pre_cost = i.item_cost,




          d.pre_stock=i.stock-d.qty where i.item_no=d.item_no and d.p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();














           $sql = "update purchase_detail set pre_stock = 0




          where pre_stock < 0 and p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update purchase_detail set pre_stock = 0




          where pre_cost = 0 and p_id = '".$p_id."'";









          $statement = $connect->prepare($sql);









          $statement->execute();














            $sql = "update purchase_detail set pre_amount = pre_cost*pre_stock,




            cur_amount = qty*adj_cost where p_id = '".$p_id."'";














          $statement = $connect->prepare($sql);









          $statement->execute();














           $sql = "update purchase_detail set total_amount = pre_amount+cur_amount,




            total_stock = qty+pre_stock where p_id = '".$p_id."'";




            









          $statement = $connect->prepare($sql);









          $statement->execute();














           $sql = "update purchase_detail set item_cost = total_amount / total_stock




             where p_id = '".$p_id."'";




            









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update purchase_detail set item_cost_sm = item_cost + cost_rate_sm




             where p_id = '".$p_id."'";




            









          $statement = $connect->prepare($sql);









          $statement->execute();
























          $sql = "update items i,purchase_detail d set i.item_cost =




         d.item_cost where d.p_id = '".$p_id."' and d.item_no=i.item_no";









          $statement = $connect->prepare($sql);









          $statement->execute();









          $sql = "update items i,purchase_detail d set i.item_cost_sm = d.item_cost_sm where d.p_id = '".$p_id."' and d.item_no=i.item_no";









          $statement = $connect->prepare($sql);









          $statement->execute();





























          //create jv



















          $inv_type = $_POST["inv_type"];




          $ref_id = $p_id;




           $inv_amt =  $inv_amt - $discount;




          $or_inv_amt = $or_inv_amt - $or_discount;














          if($inv_type=='Cash')









          {




             $sql = "SELECT IFNULL(max(jv_no),0) FROM jv WHERE branch_id = '".$branch_id."'";




            $statement = $connect->prepare($sql);




            $statement->execute(); // no need to add `$sql` here, you can take that out




            $jv_no = $statement->fetchColumn();









            $jv_no++;









            




         




          









         




            $inv_no = $_POST["inv_no"];














            $source = 'AP Inv';




            $description = 'AP Cash Invoice ' .$p_id .', ' .$_POST['description'];




            //$inv_amt = $_POST["inv_amt"];




            //$cur_rate = $_POST["cur_rate"];




            //$or_amt =$inv_amt * $cur_rate; 









            $statement = $connect->prepare("




              INSERT INTO jv 




                (jv_no,branch_id,dated,source,ref_id,description,cur_name,cur_rate,user_id)




                VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :cur_name, :cur_rate, :user_id)




    ");




    $statement->execute(




      array(




          ':jv_no'             =>  $jv_no,




          ':branch_id'             =>  $branch_id,




          ':dated'             =>  $_POST['dated'],




          ':source'          =>  $source,




          ':ref_id'          =>  $ref_id,




          ':description'       =>  $description,




          ':cur_name'          =>  $_POST["cur_name"],




          ':cur_rate'          =>  trim($_POST["cur_rate"]),        




          ':user_id'       =>  $user_id




      )




    );









     $statement = $connect->query("SELECT LAST_INSERT_ID()");




      $jv_id = $statement->fetchColumn();









      














        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  11110001,




            ':debit'          =>  0,




            ':credit'           =>  $inv_amt,




            ':or_debit'           =>  0,




            ':or_credit'           =>  $or_inv_amt,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );




        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  1005,




            ':debit'          =>  $inv_amt,




            ':credit'           =>  0,




            ':or_debit'           =>  $or_inv_amt,




            ':or_credit'           =>  0,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );









      }









        if($inv_type =='Credit')









        {




         




             $sql = "SELECT IFNULL(max(jv_no),0) FROM jv WHERE branch_id = '".$branch_id."'";




            $statement = $connect->prepare($sql);




            $statement->execute(); // no need to add `$sql` here, you can take that out




            $jv_no = $statement->fetchColumn();









            $jv_no++;









            




            




          









         




            $inv_no = $_POST["inv_no"];














            $source = 'AP Inv';




            $description = 'AP Credit Invoice ' .$p_id;




            $inv_amt = $_POST["inv_amt"];




            $cur_rate = $_POST["cur_rate"];




            $or_amt =$inv_amt * $cur_rate; 









            $statement = $connect->prepare("




              INSERT INTO jv 




                (jv_no,branch_id,dated,source,ref_id,description,cur_name,cur_rate,user_id)




                VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :cur_name, :cur_rate, :user_id)




    ");




    $statement->execute(




      array(




          ':jv_no'             =>  $jv_no,




          ':branch_id'             =>  $branch_id,




          ':dated'             =>  $_POST['dated'],




          ':source'          =>  $source,




          ':ref_id'          =>  $ref_id,




          ':description'       =>  $description,




          ':cur_name'          =>  $_POST["cur_name"],




          ':cur_rate'          =>  trim($_POST["cur_rate"]),        




          ':user_id'       =>  $user_id




      )




    );









     $statement = $connect->query("SELECT LAST_INSERT_ID()");




      $jv_id = $statement->fetchColumn();     














        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  1003,




            ':debit'          =>  0,




            ':credit'           =>  $inv_amt,




            ':or_debit'           =>  0,




            ':or_credit'           =>  $or_inv_amt,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );




        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  1005,




            ':debit'          =>  $inv_amt,




            ':credit'           =>  0,




            ':or_debit'           =>  $or_inv_amt,




            ':or_credit'           =>  0,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );









      }




      




      $freight=$_POST['freight'];














           














           $source = 'AP Exp';




            $description = 'AP Credit Invoice ' .$ref_id;




    $jv_no++;




    $statement = $connect->prepare("




      INSERT INTO jv 




        (jv_no,branch_id,dated,source,ref_id,description,cur_name,cur_rate,user_id)




        VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :cur_name, :cur_rate, :user_id)




    ");




    $statement->execute(




      array(




          ':jv_no'             =>  $jv_no,




          ':branch_id'             =>  $branch_id,




          ':dated'             =>  $_POST['dated'],




          ':source'          =>  $source,




          ':ref_id'          =>  $ref_id,




          ':description'       =>  $description,




          ':cur_name'          =>  $_POST['cur_name'],




          ':cur_rate'          =>   trim($_POST["cur_rate"]),         




          ':user_id'       =>  $user_id




      )




    );









     $statement = $connect->query("SELECT LAST_INSERT_ID()");




      $jv_id = $statement->fetchColumn();









      














        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  1003,




            ':debit'          =>  0,




            ':credit'           =>  $freight,




            ':or_debit'           =>  0,




            ':or_credit'           =>  $freight,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );




        $statement = $connect->prepare("




          INSERT INTO jv_detail 




          (jv_id,acc_no,debit,credit,or_debit,or_credit,status,cl_date)




          VALUES(:jv_id, :acc_no, :debit, :credit, :or_debit, :or_credit, :status, :cl_date)




        ");









        $statement->execute(




          array(




            ':jv_id'               =>  $jv_id,




            ':acc_no'              =>  1014,




            ':debit'          =>  $freight,




            ':credit'           =>  0,




            ':or_debit'           =>  $freight,




            ':or_credit'           =>  0,




            ':status'           =>  'Active',




            ':cl_date'           =>  $_POST['dated']             




          )




        );




           




      //$result = $statement->fetchAll();









      header("location:purchase.php");




  }




  




     




  




  ?>




  <!DOCTYPE html>




<html lang="en">




  <head>




    <title>New Purchase Invoice</title>




    




    <style>




      /* Remove the navbar's default margin-bottom and rounded borders */ 




      .navbar {




      margin-bottom: 4px;




      border-radius: 0;




      }




      /* Add a gray background color and some padding to the footer */




      footer {




      background-color: #f2f2f2;




      padding: 25px;




      }




      .carousel-inner img {




      width: 100%; /* Set width to 100% */




      margin: auto;




      min-height:200px;




      }




      




      .navbar-brand:hover




      {




      background-color:#ffffff;




      }




      /* Hide the carousel text when the screen is less than 600 pixels wide */




      @media (max-width: 600px) {




      .carousel-caption {




      display: none; 




      }




      }




    </style>




     









    <title>Edit Purchase Invoice</title>









    <!-- Bootstrap Core CSS -->




   




  </head>




  <body>




    <style>




      .box




      {




      width: 100%;




      max-width: 1390px;




      border-radius: 5px;




      border:1px solid #ccc;




      padding: 15px;




      margin: 0 auto;                




      margin-top:50px;




      box-sizing:border-box;




      }




    </style>




    <link rel="stylesheet" href="css/datepicker.css">




    <script src="js/bootstrap-datepicker1.js"></script>




    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">




    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />




    <script>




      $(document).ready(function(){




        $('#dated').datepicker({




          format: "yyyy-mm-dd",




          autoclose: true




        });




      });




    </script>




    <div class="container-fluid">




  <?php




if(isset($_GET["update"]) && isset($_GET["id"]))




      {




        




        $statement = $connect->prepare("




          SELECT * FROM po 




            WHERE po_no = :po_no




            LIMIT 1




        ");




        $statement->execute(




          array(




            ':po_no'       =>  $_GET["id"]




            )




          );




        $result = $statement->fetchAll();




        foreach($result as $row)




        {




        ?>




        <script>




        $(document).ready(function(){




          




          




          $('#cur_name').val("<?php echo $row["cur_name"]; ?>");




          $('#po_no').val("<?php echo $po_no; ?>");




          




          $('#cur_rate').val("<?php echo $row["cur_rate"]; ?>");




          




          $('#v_id').val("<?php echo $row["v_id"]; ?>");




         
























          




        });




        </script>









        <?php include('top-pannel.php');?>




 <form method="post" id="purchase_form" AutoComplete="off" />




        <div class="table-responsive">




          <table class="table table-bordered">




            <tr>




              <td colspan="2" align="center"><h2 style="margin-top:10.5px">New Purchase Invoice</h2></td>




            </tr>




            <tr>




                <td colspan="2">




                  <div class="row">




                    <div class="col-md-8">




                      <br />









                        <select name="v_id" id="v_id" class="form-control input-sm v_id selectpicker" data-show-subtext="true" data-live-search="true" />









                           <?php echo fill_v_name($connect);?>









                        </select>




                        <br />




                        <br />




                        <input type="text" name="description" id="description" class="form-control" placeholder="Enter Description"/>




                        <br />



















                        <table id="expense" class="table table-bordered">














                          




                          <td><input type="text" name="freight" id="freight" class="form-control freight" placeholder="Freight Or VAT"  /></td>




                          <td><input type="text" name="others" id="others" class="form-control others" placeholder="Other Exp" /></td>




                          <td><input type="text" name="item_cost_sm" id="item_cost_sm" class="form-control item_cost_sm" placeholder="item_cost_sm" /></td>




                          </tr>




                        
























                        </table>




                    </div>









                    <div class="col-md-4">




                      <br />




                      <input type="text" name="po_no" id="po_no" class="form-control input-sm" placeholder="Po No." />




                      <br />




                    




                  




                  




                      <input type="text" name="inv_no" id="inv_no" class="form-control input-sm" placeholder="Invoice No." />




                      <br />









                      <select name="inv_type" id="inv_type" class="form-control inv_type" />




                      <option value="">Select Invoice Type</option>




                      <option value="Credit">Credit</option>




                      <option value="Cash">Cash</option>









                      </select>




                      <br />




                      <select name="cur_name" id="cur_name" class="form-control cur_name" />




                        <?php echo fill_currency($connect);?>




                      </select>




                      <br />




                      




                      <input type="text" name="cur_rate" id="cur_rate" class="form-control number_only cur_rate" placeholder="Currency rate" />




                      <br />




                      <input type="text" name="dated" id="dated" class="form-control input-sm" readonly placeholder="Select Date" AutoComplete="off" />














                      <br />




                      <input type="text" name="inv_amt" style="text-align:right" id="inv_amt" class="form-control number_only inv_amt" placeholder="Invoice Amount" />









                      <br />




                    <input type="text" name="discount" style="text-align:right" id="discount" class="form-control number_only discount" placeholder="Discount"/>




                  <br />




                  <input type="text" name="discount_percent" style="text-align:right" id="discount_percent" class="form-control input-sm number_only discount_percent" placeholder="Discount(%)"/>




                    </div>




                  </div>




                  <br />




                  <table id="invoice-item-table" class="table table-bordered">




                    <tr>




                      <th width="2%">Sr#.</th>




                      <th width="20%">Select Item</th>




                      <th width="20%">Select Store</th>




                      <th width="5%">Qty</th>




                      <th width="6%">Rate</th>




                      <th width="9%">Amount</th>




                       <th width="2%"></th>




                      









                      




                     




                    </tr>




                     <?php




                    $statement = $connect->prepare("select b.ln_no,b.item_no,b.item_name, qty, rcvd,rate, balance 




                        from ( select a.ln_no,a.item_no,a.item_name,sum(qty) qty, sum(rcvd) rcvd, rate,sum(qty) - sum(rcvd) as balance 




                          from ( select d.ln_no,d.item_no,i.item_name,sum(IFNULL(d.qty,0)) as qty, 0 as rcvd,rate




                           from po_detail d, po m, items i where m.po_no=d.po_no  and i.item_no = d.item_no and m.po_no = :po_no group by item_no,item_name                           




                           union all




                           select 0 as ln_no,d.item_no,i.item_name, 0 as qty, sum(IFNULL(d.qty,0)) as rcvd ,IFNULL(rate,0) rate




                           from purchase_detail d, purchase m,items i where m.p_id=d.p_id and i.item_no=d.item_no and m.po_no = :po_no group by item_no,item_name




                          ) a group by  a.item_no,a.item_name) b order by ln_no;");




                    $statement->execute(




                      array(




                        ':po_no'       =>  $po_no




                      )




                    );




                    $item_result = $statement->fetchAll();




                    $m = 0;




                    foreach($item_result as $sub_row)




                    {




                      $m = $m + 1;




                    ?>




                     <tr id="row_id_<?php echo $m; ?>">




                      <td><span id="sr_no"><?php echo $m; ?></span></td>




                      <td><select name="item_no[]" id="item_no<?php echo $m; ?>" class="form-control input-sm item_no selectpicker" data-show-subtext="true" data-live-search="true" required />




                      <option value="<?php echo $sub_row["item_no"]; ?>"><?php echo $sub_row["item_name"]; ?></option>




                          <?php echo fill_item($connect);?>









                        </select></td>




                        <td><select name="store_id[]" id="store_id<?php echo $m; ?>" class="form-control input-sm store_id" required />




                        <option value="<?php echo $default_store; ?>"><?php echo $store_name; ?></option>




                          <?php echo fill_store($connect);?>









                        </select></td>




                      <td><input type="text" name="qty[]" id="qty<?php echo $m; ?>" class="form-control input-sm number_only qty" value="<?php echo $sub_row["balance"]; ?>" /></td>




                      <td><input type="text" name="rate[]" id="rate<?php echo $m; ?>" class="form-control input-sm number_only rate" value="<?php echo $sub_row["rate"]; ?>"/></td>




                      <td><input type="text" name="amount[]" id="amount<?php echo $m; ?>" class="form-control input-sm amount" readonly /></td>




                      <td><button type="button" name="remove_row[]" id="<?php echo $m; ?>" class="btn btn-danger btn-xs remove_row">X</button> </td>




                      




                    




                    </tr>




                    <?php




                    }




                    ?>




                  </table>




                  <div align="left">









                  <br />




                  




                  </div>









                  <div align="right">




                    <button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>




                  </div>




                </td>




              </tr>




             <tr>









                </tr>



















                <tr>




                <td width="80%"align="right"><b>Total :</b></td><td width="20%" align="right"> <b><span id="total_amount"></span></b></td>









              </tr>









              <tr>




                <td colspan="2">









                </td>




              </tr>




              <tr>




                <td colspan="2" align="center">




                  <input type="hidden" name="total_item" id="total_item" value="<?php echo $m; ?>" />




                  <input type="hidden" name="btn_action" id="btn_action" />




                  <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />




                </td>




              </tr>




          </table>




        </div>




      </form>




      <script>




      $(document).ready(function(){









        var total_debit = $('#total_debit').text();




        var count = "<?php echo $m; ?>";




        




        $(document).on('click', '#add_row', function(){




          count++;




          $('#total_item').val(count);




          var html_code = '';




          html_code += '<tr id="row_id_'+count+'">';




          html_code += '<td><span id="sr_no">'+count+'</span></td>';









          html_code += '<td><select name="item_no[]" id="item_no'+count+'" data-srno="'+count+'" class="form-control item_no selectpicker" data-show-subtext="true" data-live-search="true"><?php echo fill_item($connect); ?></select></td>';




          html_code += '<td><select name="store_id[]" id="store_id'+count+'" data-srno="'+count+'" class="form-control store_id"><?php echo fill_store($connect); ?></select></td>';




          html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" /></td>';




          html_code += '<td><input type="text" name="rate[]" id="rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only rate" /></td>';




          html_code += '<td><input type="text" name="amount[]" id="amount'+count+'" data-srno="'+count+'" class="form-control input-sm amount" readonly /></td>';          




          




          




                      




          html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button> </td>';









          




          html_code += '</tr>';




          $('#invoice-item-table').append(html_code);




           $('.selectpicker').selectpicker();




          




        });




        




       $(document).on('click', '.remove_row', function(){









          var row_id = $(this).attr("id");




          var total_item_amount = $('#amount'+row_id).val();




          var final_amount = $('#total_amount').text();




          var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);




          $('#total_amount').text(result_amount);




          $('#row_id_'+row_id).remove();




          count--;




          $('#total_item').val(count);




        });









       $(document).on('blur', '.rate', function(){




              cal_final_total(count);









        });









              









        function cal_final_total(count)




        {




         var final_item_amount = 0;














          for(j=1; j<=count; j++)




          {




            var qty = 0;




            var rate = 0;




            var amount = 0;




            var cur_rate = 0;




            var cur_rated = 0;




            




            var total_amount = 0;









            var item_amount = 0;




            qty = $('#qty'+j).val();




            if(qty > 0)




            {









              rate = $('#rate'+j).val();




              cur_rate = $('#cur_rate').val();




              









              if(rate > 0)




              {









                




                amount = parseFloat(qty) * parseFloat(rate);




                









                $('#amount'+j).val(amount);




               




                









                




                final_item_amount = parseFloat(final_item_amount) + parseFloat(amount);




               



















              }




            }




          }









          $('#total_amount').text(final_item_amount);




        }









        $(document).on('blur', '.item_no', function(){




          var item_no = $('#item_no'+count).val();




          $.ajax({




                url:"item_data.php",




                method:"POST",




                data:{item_no:item_no},




                dataType:"json",




                success:function(data){




                   // $('#pre_cost'+count).val(data.item_cost);




                   




                     




                     // $('#stock'+count).val(data.total_stock);









                   




                     




                }




           });









        });
























        $(document).on('blur', '.cur_name', function(){




          var cur_name = $('#cur_name').val();




          




          




          $.ajax({




                url:"cur_data.php",




                method:"POST",




                data:{cur_name:cur_name},




                dataType:"json",




                success:function(data){




                     $('#cur_rate').val(data.cur_rate);




                     




                }




           });









        });



















       














       









        $(document).on('blur', '.discount', function(){









           var discount = $('#discount').val();




           if(discount ==''){




            return true;




           }




          var discount_percent = 0;




          var total_amount = $('#inv_amt').val();



















          discount_percent = parseFloat(discount) / parseFloat(total_amount) * 100;




          $('#discount_percent').val(discount_percent);




          discount_percent = $('#discount_percent').val();




          discount_percent.value = parseFloat(discount_percent.value.replace(/,/g, ""))




                    .toFixed(2)




                    .toString()




                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");




                    $('#discount_percent').val(discount_percent);



























































          discount.value = parseFloat(discount.value.replace(/,/g, ""))




                    .toFixed(2)




                    .toString()




                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");




                    $('#discount').val(discount);
























        });
























        $(document).on('blur', '.discount_percent', function(){




         var discount = 0




          var discount_percent = $('#discount_percent').val();




          var total_amount = $('#inv_amt').val();














          discount = parseFloat(total_amount) * parseFloat(discount_percent) / 100;




          $('#discount').val(discount);









                    total_amount = parseFloat(total_amount) - parseFloat(discount);




                    $('#inv_amt').text(total_amount);




          discount.value = parseFloat(discount.value.replace(/,/g, ""))




                    .toFixed(2)




                    .toString()




                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");




                    $('#discount').val(discount);





























       });














        














        









       




        $(document).on('blur', '.freight', function(){









          var freight = $('#freight').val();




          if(freight == ''){




            freight =0;




          }




          $('#freight').val(freight);




          









       });




         $(document).on('blur', '.others', function(){









         var others = $('#others').val();




         if(others ==''){




          others = 0;




         }




          $('#others').val(others);




          




       });









          $(document).on('blur', '.inv_amt', function(){




          




       });



















      
























        $('#save').click(function(){









          if($.trim($('#inv_amt').val()).length == 0)




          {




            alert("Please Enter Purchase invoice Amount");




            $('#inv_amt').focus();




            return false;




          }














           if($.trim($('#v_id').val()).length == 0)




          {




            alert("Please Select Vendor");




            $('#v_id').focus();




            return false;




          }









           if($.trim($('#inv_type').val()).length == 0)




          {




            alert("Please select invoice Type");




            $('#inv_type').focus();




            return false;




          }









           if($.trim($('#cur_name').val()).length == 0)




          {




            alert("Please Select Currency");




            $('#cur_name').focus();




            return false;




          }









          if($.trim($('#dated').val()).length == 0)




          {




            alert("Please Select Date");




            $('#dated').focus();




            return false;




          }









          














          $('#purchase_form').submit();














        });



















          



















      });




      </script>









       <?php




     }




   }




?>