<?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>
<html>
<?php include '../includes/connection.php'; ?>
    
    <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_debtors_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">
        <!--[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="pull-center">
                   
                                       <a href="../main/dashboard.php"> <button class="btn btn-primary"><i class="icon-shopping-cart icon-white"></i> Dashboard</button></a> &nbsp;&nbsp;&nbsp;  <a href="../sales/new_order.php"> <button class="btn btn-primary"><i class="icon-shopping-cart icon-white"></i> New Order</button></a>

                          </div>
                <div class="span12" id="content" style="font-size: 20px;">

                     <div class="row-fluid">
                        <!-- block -->
                        <div class="block">
                            <div class="navbar navbar-inner block-header">
                                <div class="muted pull-left">Current Pending Payments</div>
                            </div>
                            <div class="block-content collapse in">
                                <div class="span12">
                                   
                                    
                                    <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example2">
                                        <thead>
                                            <tr>
                                                <th>sno</th>
                                                <th>Date</th>
                                                <!--<th>Receipt No</th>-->
                                                <th>Customer</th>
                                                <!--<th>Contact</th>-->
                                                <th>Items</th>
                                                <th>Total Amount</th>
                                                <th>Amount Paid</th>
                                                <th>Balance</th>
                                                <th>Staff</th>
                                                <th>Pay</th>
                                                

                                            </tr>
                                        </thead>
                                        <tbody>
<?php
/*$sql = "SELECT distinct order_id as oid, (select receipt_no from sales where id=oid)as receiptnoo,(select total_price from sales where id=oid)as total_pricex,(select paid from sales where id=oid)as amt_paid,(select (select full_name from staff where staff_code=sales.staff) from sales where id=oid)as staffname, GROUP_CONCAT((select concat(product_name,' (',(select quantity from sales_details where product_id=products.id AND order_id=oid group by order_id),') ') from products where id=sales_details.product_id))as pname from sales_details where (select total_price from sales where id=sales_details.order_id)>(select paid from sales where id=sales_details.order_id) group by order_id";*/
//if( $_SESSION['role']=="Super Admin"){
if($permissions['business_id'] != 0 && $permissions['branch_id']==0){
  $sql="SELECT distinct order_id as oid,date_format(date_time,'%y-%m-%d') as date, (select receipt_no from sales where id=sales_details.order_id)as receiptnoo,(select total_price from sales where id=sales_details.order_id)as total_pricex,(select paid from sales where id=sales_details.order_id)as amt_paid,(select (select full_name from staff where staff_code=sales.staff) from sales where id=oid)as staffname, GROUP_CONCAT((select concat(product_name,' (',(select quantity from sales_details where product_id=products.id AND order_id=sales_details.order_id group by order_id limit 1),') ') from products where id=sales_details.product_id))as pname, (select customer_name from sales where id=sales_details.order_id)as customer_name, (select contact from sales where id=sales_details.order_id)as customer_contact from sales_details where (select total_price from sales where business_id='$business' && id=sales_details.order_id)>(select paid from sales where id=sales_details.order_id) group by order_id";
}else{
$sql="SELECT distinct order_id as oid,date_format(date_time,'%y-%m-%d') as date, (select receipt_no from sales where id=sales_details.order_id)as receiptnoo,(select total_price from sales where id=sales_details.order_id)as total_pricex,(select paid from sales where id=sales_details.order_id)as amt_paid,(select (select full_name from staff where staff_code=sales.staff) from sales where id=oid)as staffname, GROUP_CONCAT((select concat(product_name,' (',(select quantity from sales_details where product_id=products.id AND order_id=sales_details.order_id group by order_id limit 1),') ') from products where id=sales_details.product_id))as pname, (select customer_name from sales where id=sales_details.order_id)as customer_name, (select contact from sales where id=sales_details.order_id)as customer_contact from sales_details where (select total_price from sales where branch_id='$branch' && id=sales_details.order_id)>(select paid from sales where id=sales_details.order_id) group by order_id";
}

//SELECT distinct order_id as oid, (select receipt_no from sales where id=oid)as receiptnoo,(select total_price from sales where id=oid)as total_price,(select paid from sales where id=oid)as amt_paid, GROUP_CONCAT((select concat(product_name,' ',(select quantity from sales_details where product_id=products.id AND order_id=oid group by order_id)) from products where id=sales_details.product_id))as pname from sales_details group by order_id

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
  $num=1;
    while($row = mysqli_fetch_assoc($result)) {
        ?>
<tr class="odd gradeX">
    <td><?php echo $num; ?></td>
    <td><?php echo $row['date']; ?></td>
    <!--<td><?php echo $row['receiptnoo']; ?></td>-->
    <td><?php echo $row['customer_name']; ?>   <?php echo $row['customer_contact']; ?></td>
    <!--<td><?php echo $row['customer_contact']; ?></td>-->
    <td><?php echo $row['pname']; ?></td>
    <td><?php echo $row['total_pricex']; ?></td>
    <td><?php echo $row['amt_paid']; ?></td>
    <td><?php echo $row['total_pricex']-$row['amt_paid']; ?></td>
     <td><?php echo $row['staffname']; ?></td> 
     <td>
       <a href="#myModal<?php echo$row['oid'];?>" data-toggle="modal" class="btn btn-primary"><i class="icon-check icon-white"></i>&nbsp;</a>
     </td>
    
</tr>
         <div id="myModal<?php echo$row['oid'];?>" class="modal hide">
                      <div class="modal-header" style="background: #08c; color: white; text-align: center;">
                        <button data-dismiss="modal" class="close" type="button">&times;</button>
                        <h3>Add Payment</h3>
                      </div>
                      <div class="modal-body" style="max-height: 550px;">
                        <form class="form-horizontal" method="POST" action="">
                            <fieldset>
                              
                              <div class="control-group">
                                <label class="control-label" for="focusedInput" style="font-size: 18px;">Receipt Number:  <?php echo $row['receiptnoo']; ?></label>
                                <div class="controls">
                                <input type="hidden" class="form-control" name="receiptno" value="<?php echo $row['receiptnoo'];?>" style="width: 90%; font-size: 18px; height: 35px;" onchange="getdetails(this.value)"  required >
                                 
                                                                    </div>
                                                                  </div>

                                                          
                                            <div class="control-group">
                                                <div class="pull-center">
                                                    <h3 style="color:blue;">
                                                       <font color=blue>Total:  <?php echo $row['total_pricex']?></font>&nbsp;&nbsp;
                                                       <font color=darkgreen> Paid: <?php echo $row['amt_paid']?>
                                                         
                                                       </font>&nbsp;&nbsp;
                                                       <font color=darkorange>Balance: <?php echo $row['total_pricex']-$row['amt_paid']?></font> 
                                                    </h3>
                                                </div>
                                             
                                            </div>
                                            <p>
                                            <div style="display: block;" id="restforms">
                                            <div class="control-group">
                                              <label class="control-label" for="focusedInput" style="font-size: 18px;">Amount Paid</label>
                                              <div class="controls">
                                                <input class="input-xlarge focused" max="<?php echo $row['total_pricex']-$row['amt_paid']?>" value="<?php echo $row['total_pricex']-$row['amt_paid']?>"  id="ampaid" name="ampaid" type="number" style="width: 90%; font-size: 18px; height: 35px;" required="" onkeyup="calculateBalance<?php echo $row['oid'];?>(this.value);">
                                                <input type="hidden" id="hiddenpaid<?php echo $row['oid'];?>" value="<?php echo $row['total_pricex']-$row['amt_paid'];?>">
                                              </div>
                                            </div>
                                                              <script type="text/javascript">
                                                                  function calculateBalance<?php echo $row['oid'];?>(varx){
                                                                      var entered=varx;
                                                                      var paid=document.getElementById("hiddenpaid<?php echo $row['oid'];?>").value;

                                                                      document.getElementById("newbal<?php echo $row['oid'];?>").value=paid-entered

                                                                  }
                                                              </script>
                                                <div class="control-group">
                                                  <label class="control-label" for="focusedInput" style="font-size: 18px;">New Balance</label>
                                                  <div class="controls">
                                                    <input class="input-xlarge focused" name="newbal" id="newbal<?php echo $row['oid'];?>" type="text" value="0" style="width: 90%; font-size: 18px; height: 35px;" readonly="">
                                                  </div>
                                                </div>

                                             <div class="control-group">
                                                  <label class="control-label"  for="focusedInput" style="font-size: 18px;">Staff Number</label>
                                                  <div class="controls">
                                                    <input class="form-control" name="staffno" id="scode<?php echo $row['oid'];?>" type="list" list="staffx<?php echo $row['oid'];?>" style="width: 90%; font-size: 18px; height: 35px;" onchange="chechStaff<?php echo $row['oid'];?>(this.value);">




                                          <datalist id="staffx<?php echo $row['oid'];?>">
                                          <?php

                                            $sqlm= "SELECT * FROM staff where status=1 AND suspend=1 AND branch_id='$branch'";
                                            $resultm = mysqli_query($conn, $sqlm);

                                            if (mysqli_num_rows($resultm) > 0) {
                                                // output data of each row
                                                while($rowm = mysqli_fetch_assoc($resultm)) {
                                                    $val=$rowm['staff_code'];
                                                    $nem=$rowm['full_name'];

                                                    ?>
                                                    <option value="<?php echo $val; ?>"  style="font-size: 18px;"><?php echo $nem; ?></option>
                                                    <?php
                                                }
                                            } else {
                                                echo "<option value='0".mysqli_error($conn)."'>";
                                            }
                                            ?>


                                   </datalist>
                                                                    </div>
                                                                  </div>
                                                      <script type="text/javascript">

                                                      function chechStaff<?php echo $row['oid'];?>(id) {
                                                        var xhttp = new XMLHttpRequest();
                                                        xhttp.onreadystatechange = function() {
                                                          if (this.readyState == 4 && this.status == 200) {
                                                            
                                                            if(this.responseText=="invalid"){
                                                              document.getElementById("showError").innerHTML ="<h3><font color=red>Oops! Staff Number Doesnot Exist</font></h3>";
                                                              document.getElementById("savebtn<?php echo $row['oid'];?>").disabled=true;

                                                            }
                                                            else{
                                                              document.getElementById("showError").innerHTML =
                                                            this.responseText;
                                                            document.getElementById("savebtn<?php echo $row['oid'];?>").disabled=false;
                                                            }
                                                          }
                                                        };
                                                        xhttp.open("GET", "checkstaff.php?id="+id, true);
                                                        xhttp.send();
                                                      }

                                                      </script>
                                          <div id="showError" class="text-center"></div>
                                              <div class="form-actions">
                                              
                                                <button type="submit" name="savepayment" class="btn btn-primary" id="savebtn<?php echo $row['oid'];?>" disabled="">Save changes</button>
                                                <button data-dismiss='modal' class="btn">Cancel</button>
                                              </div>
                              </div>
                            </fieldset>
                        </form>
                      </div>
                    </div>

        <?php
        $num++;
    }
} else {
    echo "0 results";
}
?>
                                            
                                            
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <!-- /block -->
                    </div>
                </div>
              
                         
<?php
if(isset($_POST['savepayment'])){
  $receiptnumber=$_POST['receiptno'];
  $amountpaid=$_POST['ampaid'];
  $newbalance=$_POST['newbal'];
  $staffno=$_POST['staffno'];
  //date format function
function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }

$date=udate('Y-m-d H:i:s.u');
// Create connection


 $sql = "UPDATE sales SET paid=paid+$amountpaid WHERE receipt_no='$receiptnumber'";
 $sql2="INSERT into payment_logs(order_id, amount_paid, balance, user_id,business_id,branch_id, date_time,category)
 VALUES ((select id from sales where receipt_no='$receiptnumber' && business_id='$business' && branch_id='$branch'),'$amountpaid','$newbalance','$id_user', '$business','$branch','$date','credit')";

if (mysqli_query($conn, $sql)) {
  $message="Payment Made";
   $activity="Added a payement of receipt number: ".$receiptnumber. "<br>
   <b>Amount: </b>".$amountpaid."<br>
   <b>New Balance: </b>".$newbalance;
 $log_sql=mysqli_query($conn,"INSERT INTO logs(user_id, activity,branch_id,business_id) VALUES 
('$id_user','$activity','$branch','$business')");

if ($log_sql) {

  if (mysqli_query($conn, $sql2)) {
    ?>
    <meta http-equiv="refresh" content="0;URL='print_receipt_two.php?recno=<?php echo $receiptnumber; ?>'" /><?php
  }
    else {
    echo "Error: Failed to add log <br>" . mysqli_error($conn);
}
    
} else {
    echo "Error: Failed to add log <br>" . mysqli_error($conn);
}
  
} else {
    echo "Error updating record: " . mysqli_error($conn);
}

}
?>
                         
            </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="../assets/scripts.js"></script>
        <script src="../assets/DT_bootstrap.js"></script>
        <script>
        $(function() {
            
        });
        </script>
    </body>

</html>