<?php include ("../core/kfunctions.php");
//role("dos,hmp");
?>
<html>
<head>
<?php 

echo "

<!-- REQUIRED SCRIPTS -->
<!-- jQuery -->
<script src='../../plugins/jquery/jquery.min.js'></script>
<!-- Bootstrap -->
<script src='../../plugins/bootstrap/js/bootstrap.bundle.min.js'></script>
<!-- overlayScrollbars -->
<script src='../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js'></script>
<!-- AdminLTE App -->
<script src='../../dist/js/adminlte.js'></script>

<!-- OPTIONAL SCRIPTS -->
<script src='../../dist/js/demo.js'></script>

<!-- PAGE PLUGINS -->
<!-- jQuery Mapael -->
<script src='../../plugins/jquery-mousewheel/jquery.mousewheel.js'></script>
<script src='../../plugins/raphael/raphael.min.js'></script>
<script src='../../plugins/jquery-mapael/jquery.mapael.min.js'></script>
<script src='../../jquery-mapael/maps/world_countries.min.js'></script>
<!-- ChartJS -->
<script src='../../plugins/chart.js/Chart.min.js'></script>

<!-- PAGE SCRIPTS -->
<script src='../../dist/js/pages/dashboard2.js'></script>
<script src='../../plugins/jquery/jquery.min.js'></script>
<script src='../../plugins/moment/moment.min.js'></script>
<script src='../../plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js'></script>
<script type='text/javascript' src='../../js/bootstrap-datetimepicker.js' charset='UTF-8'></script>
<script type='text/javascript'>
    $('.form_datetime').datetimepicker({
        //language:  'fr',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        hours12: true
    });
    $('.form_date').datetimepicker({
        language:  'en',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0
    });
    $('.form_time').datetimepicker({
        language:  'en',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        maxView: 1,
        hours12: true,
        forceParse: 0,
    });

</script>
";

$stage='56';
$ip_ad2=$_SERVER['REMOTE_ADDR'];
$kbrowser2=$_SERVER['HTTP_USER_AGENT'];
$currentpage2=$_SERVER['SCRIPT_NAME'];
$userid2 = $_SESSION["rolenumber"];

?>
<script src='../../js/jquery.js'></script>
<script src='../../js/thousandseparator.js'></script>

<style type="text/css">
table{ width: 100%;border-collapse: collapse;background:  }
tr:nth-of-type(odd){background: #eee;}
th{background: #333;color: #ffffff;font-weight: bold;}
td, th{padding: 6px;text-align: left;}  
@media
only screen and (max-width: 760px),
(min-device-width:768px) and (max-device-width:1024px ){
 
table,thead,tbody,th,td,tr{display: block;}
thead tr{position: absolute;top: -9999px;left: -9999px;}
tr{border: 1px solid #ccc; }
.td{border: none;border-bottom: 1px solid #eee;position: relative;padding-left: 50%;}
.td:before{position: absolute;top:6px;left: 6px;width: 45%;padding-right: 10px;white-space: nowrap;}
.td:nth-of-type(1):before{content: "No";}
.td:nth-of-type(2):before{content: "Given to";}
.td:nth-of-type(3):before{content: "Location";}
.td:nth-of-type(4):before{content: "Date";}
.td:nth-of-type(5):before{content: "Amount";}
.td:nth-of-type(6):before{content: "Category";}
.td:nth-of-type(7):before{content: "Details";}

} 

</style>

<?php kheader(); ?>

<script src="../js/print.js"></script>


<?php 
require_once("../core/connect.php");

?>
<link href="../css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<script src="../js/sorttable.js"></script>

<script>
function show_dis(ai){$("#dis_edit"+ai).toggle(500);}
function display_row(ai){$("#rows"+ai).toggle();}
function show_2(ai){$("#attachment"+ai).toggle(500);}  
function show_dis2(ai){$("#dis_edit2"+ai).toggle(500);}
function display_row2(ai){$("#row2"+ai).toggle();}
function get_no(ai){document.getElementById("no").value=ai;}
</script>

</head>
<body>


    <div id="wrapper">

        <!-- Navigation -->
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <!-- Brand and toggle get grouped for better mobile display -->
            <?php ktopbar(); ?>
            <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
            <?php kleftbar(); ?>
            <!-- /.navbar-collapse -->
        </nav>

        <div id="page-wrapper">

            <div class="container-fluid">

 <!-- Page Heading -->
                <div>&nbsp;</div>



<div id='myDiv'>

<form method='post'>
<div class='row' style='color:maroon;'>
<h5 class="col-md-1" style='margin-right:-20px;'><b>Filters : </b></h5>
<div class="col-md-1" style='margin-right:-35px;'><b>From :</b></div>
<div class="col-md-2"><input type='date' name='datefrom' class='form-control'></div>
<div class="col-md-1" style='margin-right:-60px;'><b>To :</b></div>
<div class="col-md-2"><input type='date' name='dateto' class='form-control'></div>
<div class='col-lg-2'>
<select class='form-control' name='category'>
                      <option value=''>Category</option>

<?php
$result_scrap=$dbh->query("select * from scrap where type='expense'");
$row_scrap=$result_scrap->fetchObject();
$count_scrap=$result_scrap->rowCount();

if($count_scrap>0){ do{
echo "<option value='".$row_scrap->item."'>".$row_scrap->item2."</option>";
}while($row_scrap=$result_scrap->fetchObject());
}else{echo "<option value=''>There is no data as yet. </option>";}

?>
</select>
</div>
 <div class='col-lg-1'>
<input type='submit' style='float:right;' class='btn btn-sm btn-success' name='filter' value='Filter'></div>
</div>
</form>

<?php
if(isset($_POST["filter"])){
$datefrom=$_POST["datefrom"];
$dateto=$_POST["dateto"];
if(!empty($_POST["category"])){$catid=$_POST["category"]; $dacat="and category='$catid'";
$result_scrap=$dbh->query("select * from scrap where type='expense' and item='$catid'");
$row_scrap=$result_scrap->fetchObject();
$wd="<span style='color:maroon;'><i> Category : </i></span>".$row_scrap->item2."; ";}else{$dacat='';}

if(!empty($datefrom)&&!empty($dateto)){$dadate="and (datez>='$datefrom' && datez<='$dateto')"; 
$wd="<span style='color:maroon;'><i> From Between : </i></span>".$datefrom."<span style='color:maroon;'><i> To : </i></span>".$dateto."; ";}

elseif(!empty($datefrom)&&empty($dateto)){$dadate="and datez='$datefrom'";
$wd="<span style='color:maroon;'><i> On : </i></span>".$datefrom."; ";}

elseif(empty($datefrom)&&!empty($dateto)){$dadate="and datez='$dateto'";
$wd="<span style='color:maroon;'><i> On : </i></span>".$dateto."; ";}

elseif(empty($datefrom)&&empty($dateto)){$dadate='';}
}else{$dadate='and autoid!=0'; $wd=''; $dacat='';}

$result_expense=$dbh->query("select sum(cost) from expenses where status=2 $dadate $dacat");
$row_expense=$result_expense->fetch();


$result_expenses=$dbh->query("select * from expenses where status=2 $dadate $dacat");
$count_expenses=$result_expenses->rowcount();

echo "<div class='alert alert-warning' style='text-align:center;font-weight:bold;font-style:italic;'>UGx ".number_format($row_expense[0])." in ".$count_expenses." transactions ".$wd."</div>";
?>





<div class='panel panel-yellow'><!--Initiative-->
          <div class='panel-heading'>    
              <div class="card-header d-flex p-0">
                <ul class="nav nav-pills ml-auto p-2"> 
                  <li class="nav-item"><a class="nav-link active" href="entry_expense.php" >Expenses</a></li>
                  <li class="nav-item"><a class="nav-link active" href="expense_categories.php">Categories</a></li>  
                  <li class="nav-item"><a class="nav-link active" href="view_expenses.php">View expenses</a></li>               
                </ul>
              </div><!-- /.card-header -->
          </div>

<div class='col-lg-12'><br></div>

 <div class="col-lg-12">
            <!-- Custom Tabs -->
            <div class="card">

              <div class="card-body">

                <?php
if(isset($_POST["submit_attachment"])){
$expid=$_POST['expid'];
$attachment=$_POST['attachment'];
if(!empty($_FILES['myfile']['tmp_name'])){
$filename = str_replace(' ','_', date('i')."".date('s').$_FILES['myfile']['name']);
// destination of the file on the server
$destination = 'uploadspic/' . $filename;
// get the file extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// the physical file on a temporary uploads directory on the server
$file = $_FILES['myfile']['tmp_name'];
$size = $_FILES['myfile']['size'];

$result_expensess=$dbh->query("select * from expenses where expid = '$expid'");
$row_expensess=$result_expensess->fetchObject();
$count_expensess=$result_expensess->rowCount();

$activity2="@".$rolenumber." uploaded an attachment ".$filename." to expense No. ".$row_expensess->autoid;

if (!in_array($extension, ['pdf', 'docx', 'xls','png','jpg','jpeg','gif','xlsx','doc','odt','txt','ods'])) {
echo "You file extension must be .pdf, .xls, .png, .jpg, .jpeg, .gif, .xlsx, .doc, .odt, .txt, .ods or .docx";
} elseif ($_FILES['myfile']['size'] > 1000000000) { // file shouldn't be larger than 1Megabyte
echo "File too large!";
}else {
// move the uploaded (temporary) file to the specified destination
if(move_uploaded_file($file, $destination)){
$add_attachment=$dbh->query("UPDATE expenses SET attachment='$filename', attachment_dets='$attachment', fsize='$size' WHERE expid='$expid'");

$insertactivity = $dbh->exec("INSERT into useractivity (activity,userid,deviceid,browser,currentpage,stage) 
    values('$activity2','$userid2','$ip_ad2','$kbrowser2','$currentpage2','$stage')");

echo "<div class='alert alert-success'>Attachment Uploaded</div>";}
}}}
?>  

<?php
if(isset($_POST["update_expenses"])){
$expid=$_POST["expid"];
$user=$_POST["user"];
$date=$_POST["date"];

$result_expensess=$dbh->query("select * from expenses where expid = '$expid'");
$row_expensess=$result_expensess->fetchObject();
$count_expensess=$result_expensess->rowCount();

$amount=str_replace(',','',$_POST["amount"]);
$category=$_POST["category"];
$detail=$_POST["detail"];

$activity2="@".$rolenumber." edited expense No. ".$row_expensess->autoid." from (".$row_expensess->datez.", ".$row_expensess->requestfrom.", ".$row_expensess->cost.", ".$row_expensess->category.", ".$row_expensess->comment.") to (".$date.", ".$user.", ".$amount.", ".$category.", ".$detail.")";

$insertactivity = $dbh->exec("insert into useractivity (activity,userid,deviceid,browser,currentpage,stage) 
    values('$activity2','$userid2','$ip_ad2','$kbrowser2','$currentpage2','$stage')");

$update_exp=$dbh->query("update expenses set  cost='$amount', requestfrom='$user', comment='$detail', datez='$date', category='$category' where expid='$expid'");
echo "<script>window.location='view_expenses.php'</script>";}

if(isset($_POST["del_exp"])){
$expid=$_POST["expid"];

$result_expensess=$dbh->query("select * from expenses where expid = '$expid'");
$row_expensess=$result_expensess->fetchObject();
$count_expensess=$result_expensess->rowCount();

$activity2="@".$rolenumber." updated status (Deleted) of expense No. ".$row_expensess->autoid." to 0 (Zero).";

$insertactivity = $dbh->exec("insert into useractivity (activity,userid,deviceid,browser,currentpage,stage) 
    values('$activity2','$userid2','$ip_ad2','$kbrowser2','$currentpage2','$stage')");

$update_expenses=$dbh->query("update expenses set status=0 where expid='$expid'");
if($update_expenses){echo "<div class='alert alert-success'>Success : Expense has been deleted successfully. </div>";
echo "<script>window.location='view_expenses.php'</script>";}
}

                    ?>
                <div class="tab-content">
                  
                  <div class='tab-pane active' id='tab_1'>

<table class='table table-bordered table-hover table-striped sortable' border='1'>
<thead>
                    <tr>
                      <th width="2%">No.</th>
                      <th>Date</th>
                      <th>Given to</th> 
                     
                      <th>Amount</th>
                      <th>Category</th>
                      <th>Details</th>
                      <th width="6%">Attachment</th>
                      <th colspan="3" width="8%">Action</th>
                    </tr>
                  </thead>
<?php
// Get the total number of records from our table "payments".
$pets = $dbh->query("select * from expenses where status=2 $dadate $dacat");
$total_pages=$pets->rowCount();
// Check if the page number is specified and check if it's a number, if not return the default page number which is 1.
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;

// Number of results to show on each page.
$num_results_on_page = 50;

$calc_page = ($page - 1) * $num_results_on_page;
if(isset($_POST["filter"])){$dalimit='';}else{$dalimit="limit $calc_page, $num_results_on_page";}
$result_expenses=$dbh->query("select * from expenses where status=2 $dadate $dacat order by autoid desc $dalimit");
$row_expenses=$result_expenses->fetchObject();
$count_expenses=$result_expenses->rowCount();

$x=1;

if($count_expenses>0){ do{
  $result_users=$dbh->query("select * from users where rolenumber='$row_expenses->requestfrom'");
$row_users=$result_users->fetchObject();
$count_users=$result_users->rowCount();

$result_scrap=$dbh->query("select * from scrap where item='$row_expenses->category' and type='expense'");
$row_scrap=$result_scrap->fetchObject();

$result_scrapl=$dbh->query("select * from scrap where item='$row_expenses->loc' and type='loc'");
$row_scrapl=$result_scrapl->fetchObject();
$count_scrapl=$result_scrapl->rowCount();
// $now=$row_expenses->;
// $new_time = date($now, strtotime('+7 hours'));
echo "<tr>
<td class='ttd'>".$x++."</td>
<td class='ttd'>".$row_expenses->datez."</td>
<td class='ttd'>".$row_expenses->requestfrom."</td>

<td class='ttd'>".number_format($row_expenses->cost)."</td>
<td class='ttd'>".$row_scrap->item2."</td>
<td class='ttd'>".$row_expenses->comment."</td>
<td class='ttd'>";if($row_expenses->attachment!=''){echo "<span style='color:maroon'>[".floor($row_expenses->fsize / 1000) . ' KB'."]</span>&nbsp<a href='media_download.php?asin=".$row_expenses->autoid."' class='btn btn-sm btn-success'><i class='fa fa-download' aria-hidden='true'></i></a><br>".$row_expenses->attachment_dets;}echo"</td>
<td class='ttd'>
<button style='width:100%;'  onClick='show_2(".$row_expenses->autoid.")' class='btn btn-sm btn-success'><i class='fa fa-upload' aria-hidden='true'></i></button></td>
<td class='ttd'><button style='width:100%;'  onClick='show_dis(".$row_expenses->autoid.")' class='btn btn-sm btn-primary'><i class='fa fa-edit' aria-hidden='true'></i></button></td>
<td class='ttd'>
 <form method='post' onsubmit='return fun_del()'>
<input type='hidden' name='expid' value='".$row_expenses->expid."'>
<button type='submit' name='del_exp' class='btn btn-sm btn-danger'><i class='fa fa-trash' aria-hidden='true'></i></button>
</form></td>
</tr>
<tr id='dis_edit".$row_expenses->autoid."' style='border-bottom: 2px solid red;border-top: 2px solid red;display:none;'><form method='post'>
<input type='hidden' name='expid' value='".$row_expenses->expid."'>

<td colspan='2'><label>Expense Date:</label><input type='date' class='form-control' name='date' value='".$row_expenses->datez."'></td>
<td colspan='2'><label>Given to:</label><input class='form-control' name='user' value='".$row_expenses->requestfrom."' required>

</input></td>

<td><label>Amount:</label><input type='text' data-type='number' data-type='number' class='form-control' name='amount' value='".$row_expenses->cost."'></td>
<td><label>Category:</label><select class='form-control' name='category' required>";
$result_scrap=$dbh->query("select * from scrap where item='$row_expenses->category' and type='expense'");
$row_scrap=$result_scrap->fetchObject();
$count_scrap=$result_scrap->rowCount();

                      echo "<option value='".$row_expenses->category."'>"; if($count_scrap>0){echo $row_scrap->item2; } echo "</option>";

$result_scrap=$dbh->query("select * from scrap where type='expense'");
$row_scrap=$result_scrap->fetchObject();
$count_scrap=$result_scrap->rowCount();

if($count_scrap>0){ do{
echo "<option value='".$row_scrap->item."'>".$row_scrap->item2."</option>";
}while($row_scrap=$result_scrap->fetchObject());
}else{echo "<option value=''>There is no data as yet. </option>";}

echo "
</select></td>
<td colspan='3'><label>Details:</label><textarea class='form-control' name='detail'>".$row_expenses->comment."</textarea></td>
<td><input type='submit' name='update_expenses' style='width:100%;' class='btn btn-sm btn-primary' value='Update'></td></form>
</tr>
<tr id='attachment".$row_expenses->autoid."' style='border-bottom: 2px solid red;border-top: 2px solid red;display:none;'>
<form method='post' enctype='multipart/form-data'>
<input type='hidden' name='expid' value='".$row_expenses->expid."'>
<td colspan='2'>
<input type='file' name='myfile' class='form-control'>
</td>
<td colspan='7'><input type='text' class='form-control' name='attachment' placeholder='Extra Details'></td>
<td><input type='submit' name='submit_attachment' class='btn btn-sm btn-success' value='Upload'></td></form>
</tr>";
}while($row_expenses=$result_expenses->fetchObject());}
else{echo "<tr><td colspan='12' align='center'>There is no data as yet. </td></tr>";}
 ?>
</table> 

                </div>

              </div>
            </div>
        </div>
    </div>

<!--pagination-->
<?php if (ceil($total_pages / $num_results_on_page) > 0): ?>
<ul class="pagination">
  <?php if ($page > 1): ?>
  <li class="prev"><a href="view_expenses.php?page=<?php echo $page-1 ?>">Prev</a></li>
  <?php endif; ?>

  <?php if ($page > 3): ?>
  <li class="start"><a href="view_expenses.php?page=1">1</a></li>
  <li class="dots">...</li>
  <?php endif; ?>

  <?php if ($page-2 > 0): ?><li class="page"><a href="view_expenses.php?page=<?php echo $page-2 ?>"><?php echo $page-2 ?></a></li><?php endif; ?>
  <?php if ($page-1 > 0): ?><li class="page"><a href="view_expenses.php?page=<?php echo $page-1 ?>"><?php echo $page-1 ?></a></li><?php endif; ?>

  <li class="currentpage"><a href="view_expenses.php?page=<?php echo $page ?>"><?php echo $page ?></a></li>

  <?php if ($page+1 < ceil($total_pages / $num_results_on_page)+1): ?><li class="page"><a href="view_expenses.php?page=<?php echo $page+1 ?>"><?php echo $page+1 ?></a></li><?php endif; ?>
  <?php if ($page+2 < ceil($total_pages / $num_results_on_page)+1): ?><li class="page"><a href="view_expenses.php?page=<?php echo $page+2 ?>"><?php echo $page+2 ?></a></li><?php endif; ?>

  <?php if ($page < ceil($total_pages / $num_results_on_page)-2): ?>
  <li class="dots">...</li>
  <li class="end"><a href="view_expenses.php?page=<?php echo ceil($total_pages / $num_results_on_page) ?>"><?php echo ceil($total_pages / $num_results_on_page) ?></a></li>
  <?php endif; ?>

  <?php if ($page < ceil($total_pages / $num_results_on_page)): ?>
  <li class="next"><a href="view_expenses.php?page=<?php echo $page+1 ?>">Next</a></li>
  <?php endif; ?>
</ul>
<?php endif; ?>
<!--end of pagination-->                  

    </div>

      </div><!--  close panel panel-yellow -->

            <!-- /.container-fluid -->
<?php useractivity("on page", "56"); ?>

        <!-- /#page-wrapper -->


    <!-- /#wrapper -->
    <script>
function checkall(){
<?php
include("connect.php");
$result_citadel=$dbh->query("select * from citadel_o where schoolyear='$schoolyear' and term='$schoolterm' and schoolclass='$schoolclass'");
$row_citadel=$result_citadel->fetchObject();
$count_citadel=$result_citadel->rowCount();

if($count_citadel>0){
    do{
?>
if(document.getElementById('checkallz').checked){
document.getElementById('cidcheck<?php echo $row_citadel->autoid; ?>').checked=true;
}else{
document.getElementById('cidcheck<?php echo $row_citadel->autoid; ?>').checked=false; 
}
<?php
}while($row_citadel=$result_citadel->fetchObject());
}
?>
}
</script>

    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
    <!-- Bootstrap Core JavaScript -->
    <script src="../js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../js/jquery-1.8.3.min.js" charset="UTF-8"></script>

</div><!--  close myDiv -->
</div><!--  close container fluid -->
</div><!--  close page wrapper -->
</div><!--  close wrapper -->

</body>

</html>
