<?php
session_start();
error_reporting(0);
@ini_set('display_errors', 0);
$id_user=$_SESSION['id'];
$branch=$_SESSION['branch_id'];
$business=$_SESSION['business_id'];
?>

<!DOCTYPE html>
 <?php include '../includes/connection.php'; 
   include("../includes/header-links.php");
 ?>
<html>
<script type="text/javascript">
    function FormatCurrency(ctrl) {
                  //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                  if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                      return;
                  }

                  var val = ctrl.value;

                  val = val.replace(/,/g, "")
                  ctrl.value = "";
                  val += '';
                  x = val.split('.');
                  x1 = x[0];
                  x2 = x.length > 1 ? '.' + x[1] : '';

                  var rgx = /(\d+)(\d{3})/;

                  while (rgx.test(x1)) {
                      x1 = x1.replace(rgx, '$1' + ',' + '$2');
                  }

                  ctrl.value = x1 + x2;
              }

              function CheckNumeric() {
                  return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
              }
</script>
    
    <head>
      <?php include("../includes/header-links.php");
$permissions = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM  
  permissions,users WHERE  permissions.role_id = users.role 
  AND users.id='$id_user' AND users.business_id ='$business' AND users.branch_id ='$branch'"));

if($permissions['view_creditors_report'] != 1){
?>
<script>window.location="../main/dashboard.php"</script>
<?php
}
?>
       
        <!-- Bootstrap -->
        <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="../bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
        <link href="../assets/styles.css" rel="stylesheet" media="screen">
        <link href="../assets/DT_bootstrap.css" rel="stylesheet" media="screen">
        <link rel="stylesheet" href="../data-table-css/bootstrap-table.css">
    <link rel="stylesheet" href="../data-table-css/bootstrap-editable.css">
        <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="vendors/flot/excanvas.min.js"></script><![endif]-->
        <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
        <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script src="../vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    
    <body>
        <?php include '../includes/header.php'; ?>
        <div class="container-fluid">
            <div class="row-fluid">
                <?php include '../includes/sidebar.php'; ?>
                <!--/span-->
                <div class="span10" id="content">


                     <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
                            <div class="navbar navbar-inner block-header">
                                <div class="muted pull-left">Credit</div>
                                <div class="muted pull-right">Filter By Date</div>
                            </div>
                            <div class="block-content collapse in">
                                <div class="span12">

                                   <?php 
                        // if($_SESSION['role']=="Admin"){

                        if( $permissions['export_creditors_report'] == 1){

                        
                            ?>
                                    <div id="toolbar">
                                        <select class="form-control">
                                                <option value="">Export Basic</option>
                                                <option value="all">Export All</option>
                                                <option value="selected">Export Selected</option>
                                            </select>
                                    </div>

                         <?php
                         }
                     //     
                             ?>
                                    <table  id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="false" data-cookie="true"
                                        data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar" data-export-options='{"fileName": "Testing_filename"}'>                                    <?php
include '../includes/connection.php';
                                   // Create connection

// if( $_SESSION['role']=="Super Admin"){
if($permissions['business_id'] != 0 && $permissions['branch_id']==0){
$sql= mysqli_query($con,"SELECT id, total_price, (select count(id) from sales_details where order_id=purchase_totals.id)as count_orders, AddedOn,(select  distinct supplier from purchases where purchase_id=purchase_totals.id) as supplier,paid from purchase_totals where total_price > paid && business_id='$business' order by id desc");
}else{
  $sql= mysqli_query($con,"SELECT id, total_price, (select count(id) from sales_details where order_id=purchase_totals.id)as count_orders, AddedOn,(select  distinct supplier from purchases where purchase_id=purchase_totals.id) as supplier,paid from purchase_totals where total_price > paid && branch_id='$branch' order by id desc");
}

//$result = mysqli_query($con, $sql);

if (mysqli_num_rows($sql)> 0) {
    // output data of each row
    


                                   ?>
                                        <thead>
                                            <tr>
                                                <th  width="10%">S/NO</th>
                                                
                                                  <th width="50%">
                                                    <table background="white" >
                                                    <td width="40%">Product</td>
                                                    <td width="20%">Quantity</td>
                                                    <td width="20%">Unit Price</td>
                                                    <td width="20%">Total Price</td>
                                                    
                                                    
                                                </table>
                                              </th>
                                                <th  width="10%">Purchase Total</th>
                                                <th  width="10%">Credit Balance</th>
                                                <th width="20%">Date</th>
                                                <th width="20%">Supplier</th>
                                                <th width="10%">Action</th>
                                                
                                            </tr>
                                        </thead>
                                        <tbody>
                <?php
              $nid=0;
              while($row = mysqli_fetch_array($sql)) {
                $iddx=$row['id'];
                $nid++;
                        
                    ?>
                                            <tr>
                                                <td><?php echo $nid; ?></td>
                                                
                                                <td>
                                                    <?php include 'credit_details.php'; ?>
                                                </td>
                                                <td><?php echo $row['total_price']; ?></td>
                                                <td><?php echo $row['total_price'] -$row['paid']; ?></td>
                                                <td><?php echo $row['AddedOn']; ?></td>
                                                  <?php 
                                              $nn=  $row['supplier'];
                                                $supname1=mysqli_fetch_array(mysqli_query($con,"SELECT * from suppliers where supplier_id ='$nn'"));
                                                    $sname1=$supname1['name'];
                                                 ?>
                                                <td><?php echo $sname1; ?></td></td>

                                                <?php 
                        // if($_SESSION['role']=="Admin"){

                        if( $permissions['creditors_pay_button'] == 1){

                        
                            ?>

                                                <td><a href="#edit<?php echo $iddx; ?>" data-toggle="modal" ><button class="btn btn-success"><li class=" icon icon-check icon-white"></li>Pay</button>
                                                </a>
                                            </td>


                         <?php
                         }
                     //     
                             ?>


                         <div id="edit<?php echo $iddx; ?>" class="modal hide">
                      <div class="modal-header">
                        <button data-dismiss="modal" class="close" type="button">&times;</button>
                        <h3> Pay Credit</h3>
                      </div>
                      <div class="modal-body">
                        <?php
                        
                         
                        $sqledit=mysqli_fetch_array(mysqli_query($con," SELECT *from purchase_totals  where id='$iddx'"));
                          $editid=$sqledit['id'];
                         $tprice=$sqledit['total_price'];
                          $ppaid=$sqledit['paid'];
                         $cbal= $tprice-$ppaid;
                       $sqledit2=mysqli_fetch_array(mysqli_query($con,"SELECT distinct(supplier) as sup from purchases  where purchase_id='$editid'"));
                        $supp=$sqledit2['sup'];
                        
                                              
                                                $supname12=mysqli_fetch_array(mysqli_query($con,"SELECT * from suppliers where supplier_id ='$supp'"));
                                                    $sname12=$supname12['name'];
                                                 
                                               
                             
                        ?>
                        <form action="" method="POST" enctype="multipart/form-data">
                        <input type="hidden" value="<?php echo $editid; ?>" name="editid">
                        <input type="hidden" value="<?php echo $cbal; ?>" name="bal">
                        <label>Supplier </label>
                        <div class="controls">
                          <input type="text" value="<?php echo  $sname12; ?>" name="supplier" class="input-xlarge focused" readonly="readonly" style="width: 95%; height: 30px;">
                     </div>
                    
                        <label>Credit Amount</label>
                        <div class="controls">
                          <input type="number" value="<?php echo  $tprice-$ppaid;; ?>" name="bprice" class="input-xlarge focused" readonly="readonly" style="width: 95%; height: 30px;">
                                          </div>
                    
                         <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        
                        <label>Amount Paid </label>
                         <div class="controls">
                        <input type="text"  onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" value="<?php echo $cbal ?>" name="cpaid" class=" input-xlarge focused " max="<?php echo $cbal;  ?>" style="width: 95%; height: 30px;">
                      </div>
                  </div>
                        <div class="form-actions">
                                          <button type="submit" name="pay" class="btn btn-primary">Pay </button>
                                          
                                        </div>  
                        </form>
                      </div>
                    </div>
                                                
                                            </tr>
               <?php                             
    }
    // if( $_SESSION['role']=="Super Admin"){
    if($permissions['business_id'] != 0 && $permissions['branch_id']==0){
    $sqltt= mysqli_fetch_array(mysqli_query($con,"SELECT sum(total_price-paid) as credit from purchase_totals where total_price > paid  && business_id='$business'"));
  }else{
$sqltt= mysqli_fetch_array(mysqli_query($con,"SELECT sum(total_price-paid) as credit from purchase_totals where total_price > paid  && branch_id='$branch'"));
    }
    ?>
    <tr><td colspan="3"><h4>Total Credit Balance</h4></td><td colspan="4"><h4><?php echo number_format($sqltt['credit']); ?>/=</h4></td></tr>
    <?php
} else {
    echo "0 results";
}

//mysqli_close($conn);
?>
<?php

if(isset($_POST['pay'])){
  include '../includes/connection.php';
$sup=mysqli_real_escape_string($con,$_POST['supplier']);
$upid=mysqli_real_escape_string($con,$_POST['editid']);
$cbal=mysqli_real_escape_string($con,$_POST['bal']);
$ampaid=str_replace(",","",  mysqli_real_escape_string($con,$_POST['cpaid']));
if ($ampaid>$cbal) {
    echo "<script> alert('Amount paid(shs $ampaid) cannot be greater than the credit balance (shs &cbal)'),history.go(-1)</script>";
}else{
  

$sqlstm = mysqli_query($con,"update purchase_totals set paid=paid+$ampaid where id='$upid' ");


if($sqlstm) {
echo $id_user=$_SESSION['id'];
$action="Paid   shs  $ampaid to  $sup";
 $log=mysqli_query($con,"INSERT INTO logs(user_id, activity,branch_id) VALUES 
('$id_user','$action','$branch')");
 
 
$paym=mysqli_fetch_array(mysqli_query($con,"SELECT * from purchase_totals where id='$upid'"));
$purchase_id=$paym['id'];


  

 $tyr = date("Y");
 $tmonth = date("m");
        $sql13 = mysqli_query($con,"select max(voucher) as recno from purchase_payments where year='$tyr' && month='$tmonth' && branch_id='$branch'");
        if(mysqli_num_rows($sql13)>0){
            $row13=mysqli_fetch_array($sql13);
            $rec = $row13['recno'];
        }
        else{
            $rec=0;
        }
        $new_rec = $rec +1;
        if(strlen($new_rec)==1){
            $reciept = "000".$new_rec;
        }
        else if(strlen($new_rec)==2){
            $reciept = "00".$new_rec;
        }
        else if(strlen($new_rec)==3){
            $reciept = "0".$new_rec;
        }
        else{
            $reciept = $new_rec;
        }
        $voucher_no = $tyr.$tmonth.$reciept;
$sql2 = mysqli_query($con,"INSERT INTO purchase_payments (purchase_id, amount_paid,voucher_no,year,month,voucher,branch_id,AddedBy)
VALUES ('$purchase_id', '$ampaid','$voucher_no','$tyr','$tmonth','$new_rec','$branch','$id_user')");


 echo "<script>
    
    window.location='credit_voucher.php?voucher=".$voucher_no."';
    </script>";
 
} else {
    echo "Error ".mysqli_error($con);
}

  
}


}

?>
                                            
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>
                </div>
            </div>
            <hr>
            <?php include '../includes/footer.php'; ?>
        </div>
        <!--/.fluid-container-->

        <script src="../vendors/jquery-1.9.1.js"></script>
        <script src="../bootstrap/js/bootstrap.min.js"></script>
        <script src="../vendors/datatables/js/jquery.dataTables.min.js"></script>

<script src="../data-table-js/bootstrap-table.js"></script>
    <script src="../data-table-js/tableExport.js"></script>
    <script src="../data-table-js/data-table-active.js"></script>
    <script src="../data-table-js/bootstrap-table-editable.js"></script>
    <script src="../data-table-js/bootstrap-editable.js"></script>
    <script src="../data-table-js/bootstrap-table-resizable.js"></script>
    <script src="../data-table-js/colResizable-1.5.source.js"></script>
    <script src="../data-table-js/bootstrap-table-export.js"></script>


        <script src="../assets/scripts.js"></script>
        <script src="../assets/DT_bootstrap.js"></script>
        <script>
        $(function() {
            
        });
        </script>
    </body>

</html>