 <?php
session_start();
require("php_con.php");
require("check_user.php");
require("function.php");

if(setting_view("auto_backup_status")==1){
	
	function custom_copy($src, $dst) { 
  
    // open the source directory
    $dir = opendir($src); 
  
    // Make the destination directory if not exist
    @mkdir($dst); 
  
    // Loop through the files in source directory
    while( $file = readdir($dir) ) { 
  
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) 
            { 
  
                // Recursively calling custom copy function
                // for sub directory 
                custom_copy($src . '/' . $file, $dst . '/' . $file); 
  
            } 
            else { 
                if(@copy($src . '/' . $file, $dst . '/' . $file)){	
				}
				else{
					echo "<script>window.location='dashboard?backup_fail';</script>";
				}
            } 
        } 
    } 
  
    closedir($dir);
}
	
if(setting_view("auto_backup_next_date")<=date("Y-m-d")){
  
$src = setting_view("auto_backup_from");
  
$dst = setting_view("auto_backup_to")."/system_backup_file";
  
custom_copy($src, $dst);
	
setting_update("auto_backup_next_date",date("Y-m-d",strtotime("+1 day")));
	
}
	
}

if(isset($_POST['popup_open'])){
	unset($_SESSION['low_stock_popup']);
}

if(isset($_GET['expenses_details_id'])){
	$expenses_details_id=mysqli_real_escape_string($connation,$_GET['expenses_details_id']);
	if(mysqli_query($connation,"DELETE FROM expenses_details WHERE expenses_details_id='$expenses_details_id'")){
	echo "<script>window.location='expenses';</script>";
	}
}

if(isset($_POST['add_cat'])){
	$expenses_details_category=mysqli_real_escape_string($connation,$_POST['expenses_details_category']);
	$expenses_details_amount=mysqli_real_escape_string($connation,$_POST['expenses_details_amount']);
	$expenses_details_date=mysqli_real_escape_string($connation,$_POST['expenses_details_date']);
	mysqli_query($connation,"INSERT INTO expenses_details(expenses_details_category, expenses_details_amount, expenses_details_user, expenses_details_date) VALUES ('$expenses_details_category','$expenses_details_amount','$_COOKIE[user_id]','$expenses_details_date')");
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title><?php echo $system_name; ?></title>
<link rel="stylesheet" href="main_css.css">
	
<script src="data_table/js/jquery-3.5.1.js"></script>
<script src="data_table/js/jquery.dataTables.min.js"></script>
<script src="data_table/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="data_table/css/bootstrap.css">
<link rel="stylesheet" href="data_table/css/dataTables.bootstrap4.min.css">
	
<link rel="stylesheet" href="icon/css/font-awesome.css">
<link rel="stylesheet" href="icon/css/font-awesome.min.css">
	
<link rel="stylesheet" href="alert/sweetalert2.min.css">
<link href="cus_css.css" rel="stylesheet" type="text/css">
<script src="alert/sweetalert2.min.js"></script>
	
<script src="RGraph/libraries/RGraph.common.core.js"></script>
<script src="RGraph/libraries/RGraph.common.dynamic.js"></script>
<script src="RGraph/libraries/RGraph.common.tooltips.js"></script>
<script src="RGraph/libraries/RGraph.line.js"></script>
<script src="RGraph/libraries/RGraph.bar.js"></script>

</head>

<body>
<script>
window.addEventListener("load",function(){
	var load_screen=document.getElementById('load_screen');
	document.body.removeChild(load_screen);
});
</script>
	
<div id="load_screen"><div id="loading"><img src="image/loading.gif" width="80px;"></div></div>
	
<?php if(isset($_GET['backup_fail'])){ ?><div class="alert alert-warning text-center"><strong>System auto backup error!</strong> Please check your backup setting.</div><?php } ?>

<?php 
if(setting_view("backup_notification")==1){
if(setting_view("next_backup_date")<=date("Y-m-d")){
?>
<div style="background-color: red; text-align: center; padding: 10px; color: white;"><strong><i class="fa fa-download"></i> Please backup your database!</strong><br><a href="setting" style="color: white;">Click here to go to the setting page.</a></div>
<?php
}
}
?>

	
<?php require("header.php"); ?>
	
<div class="container mb-4">
<div class="row">

	
<div class="col-lg-7 col-sm-12 align-items-center justify-content-between">
	
<div class="card">
<div class="card-header bg-dark text-white text-center">Last Update</div>
<div class="card-body text-center">
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="btn btn-light" onClick="window.location='sales';">
<img src="image/exp_btn.png" style="width:60px;" class="mb-2"><br>
<?php 
$total_amount=0;
$date=date("Y-m-d");
$qury=mysqli_query($connation,"SELECT sd.sale_details_billid
FROM sale_details sd
WHERE sd.sale_details_date BETWEEN '$date' AND '$date'
ORDER BY sd.sale_details_id DESC");
while($resalt=mysqli_fetch_assoc($qury)){
$total_amount+=bill_amount($resalt['sale_details_billid']);
}	
?>
<strong class="badge badge-primary"><?php echo number_format($total_amount,2); ?></strong><br>
Today Sale
</div>
<?php } } ?>
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="btn btn-light" onClick="window.location='sales';">
<img src="image/sale_btn.png" style="width:60px;" class="mb-2"><br>
<strong class="badge badge-primary"><?php echo number_format(today_sale()); ?></strong><br>
Today Invoice
</div>
<?php } } ?>
	
<div class="btn btn-light" onClick="window.location='supplier-manage';">
<img src="image/supplier_dashbard.png" style="width:60px;" class="mb-2"><br>
<strong class="badge badge-info"><?php echo number_format((float)total_supplier()); ?></strong><br>
Supplier
</div>
	
<div class="btn btn-light" onClick="window.location='product';">
<img src="image/product_bt.png" style="width:60px;" class="mb-2"><br>
<strong class="badge badge-success"><?php echo number_format((float)total_product()); ?></strong><br>
Product
</div>
	
<div class="btn btn-light" onClick="window.location='customer';">
<img src="image/customer.png" style="width:60px;" class="mb-2"><br>
<strong class="badge badge-dark"><?php echo number_format((float)total_customer()); ?></strong><br>
Customer
</div>
	
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="btn btn-light">
<img src="image/pos_btn.png" style="width:60px;" class="mb-2"><br>
<strong><?php echo last_bill(); ?></strong><br>
Last Invoice
</div>
<?php } } ?>
	
<form method="post" class="mt-2">
<button type="submit" class="btn btn-sm btn-secondary" name="popup_open">View Low Stock</button>
</form>

</div>
	
</div>
	
<div class="card mt-4">

<p align="center" class="mt-2 font-weight-bold"><?php echo date("Y"); ?> Profit Summery</p>
	
<canvas id="cvs" width="650" height="250">
    [No canvas support]
</canvas>
</div>
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="card mt-4">
<div class="card-header bg-dark text-white text-center">Last 10 invoice</div>
<div class="card-body text-center">

<div class="table-responsive">
<table id="example" class="table list-table" style="width:100%; font-size: 14px; text-transform: capitalize;">
        <thead>
            <tr>
				<th>&nbsp;</th>
                <th>Bill ID</th>
                <th style="text-align: right;">Amount</th>
				<th>Sale Time</th>
            </tr>
        </thead>
        <tbody>
			<?php			
			$total_amount=0;

			$sale_qury=mysqli_query($connation,"SELECT *
			FROM sale_details INNER JOIN user_details ON sale_details.sale_details_user=user_details.user_id
			ORDER BY sale_details_id DESC
			LIMIT 10");
			
			while($sale_resalt=mysqli_fetch_array($sale_qury)){
			
			$amount=0;
				
			$amount_qury=mysqli_query($connation,"SELECT * FROM sale_list WHERE sale_billid='$sale_resalt[sale_details_billid]'");
			while($amount_resalt=mysqli_fetch_array($amount_qury)){
			$amount=$amount+($amount_resalt['sale_saleprice']*$amount_resalt['sale_qty']);
			}
			
			$total_amount=$total_amount+$amount;
				
			?>
            <tr>
				<td style="white-space: nowrap; text-align: center">
				<a href="view-sale?sale_billid=<?php echo $sale_resalt['sale_details_billid']; ?>" target="_blank" class="badge badge-primary" title="Edit Product"><i class="fa fa-eye"></i></a>
				</td>
                <td><?php echo $sale_resalt['sale_details_billid']; ?></td>
				<td align="right"><b class="text-success"><?php echo number_format($amount,2); ?></b></td>
				<td><?php echo date('Y-m-d h:i:s A',strtotime($sale_resalt['sale_details_date'].' '.$sale_resalt['sale_details_time'])); ?></td>
            </tr>
            <?php
			}
			?>
        </tbody>
    </table>
</div>

</div>
	
</div>
<?php } } ?>
	
</div>
	
<div class="col-lg-5 col-sm-12">
	


<div class="card">
<div class="card-header bg-dark text-white text-center"><?php echo date("F d, Y"); ?></div>
<div class="card-body">
<div id="time_dis"></div>
<div class="text-center text-secondary font-weight-bold">
<?php
$hour= date('H');
if ($hour >= 20) {
    $greetings = "Good Night";
} elseif ($hour > 14) {
   $greetings = "Good Evening";
} elseif ($hour > 11) {
    $greetings = "Good Afternoon";
} elseif ($hour < 12) {
   $greetings = "Good Morning";
}
echo $greetings." ".$current_user_resalt['user_fname']." !";	
?>	
</div>
</div>
</div>
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="card mt-4">
<div class="card-header bg-dark text-white text-center">Summary of <?php echo date("F, Y") ?> Sale's</div>
<div class="card-body">
	
<?php 
$start_date=date("Y-m-01");
$end_date=date("Y-m-t");
	
$monthly_sale_qury=mysqli_query($connation,"SELECT SUM(sl.sale_saleprice*sl.sale_qty) AS total_amount
FROM sale_details sd RIGHT JOIN sale_list sl ON sd.sale_details_billid=sl.sale_billid
WHERE sd.sale_details_billid IS NOT NULL AND sd.sale_details_date BETWEEN '$start_date' AND '$end_date'");
$monthly_sale_resalt=mysqli_fetch_assoc($monthly_sale_qury);
	
$monthly_discount_qury=mysqli_query($connation,"SELECT SUM(sd.sale_details_discount) AS total_amount
FROM sale_details sd RIGHT JOIN sale_list sl ON sd.sale_details_billid=sl.sale_billid
WHERE sd.sale_details_billid IS NOT NULL AND sd.sale_details_date BETWEEN '$start_date' AND '$end_date'");
$monthly_discount_resalt=mysqli_fetch_assoc($monthly_discount_qury);
	
$monthly_profit_qury=mysqli_query($connation,"SELECT SUM((sl.sale_saleprice*sl.sale_qty)-(sl.sale_buy_price*sl.sale_qty)) AS total_profit
FROM sale_details sd RIGHT JOIN sale_list sl ON sd.sale_details_billid=sl.sale_billid
WHERE sd.sale_details_billid IS NOT NULL AND sd.sale_details_date BETWEEN '$start_date' AND '$end_date'");
$monthly_profit_resalt=mysqli_fetch_assoc($monthly_profit_qury);
	
$monthly_exp_qury=mysqli_query($connation,"SELECT SUM(ed.expenses_details_amount) AS ex_amount
FROM expenses_details ed
WHERE ed.expenses_details_date BETWEEN '$start_date' AND '$end_date'");
$monthly_exp_resalt=mysqli_fetch_assoc($monthly_exp_qury);
	
$net_profit=($monthly_profit_resalt['total_profit']-$monthly_discount_resalt['total_amount'])-$monthly_exp_resalt['ex_amount'];
?>

<table class="table table-sm table-bordered mb-0">
  <tbody>
    <tr>
      <td align="right"><?php echo date("F"); ?> sale's</td>
      <td align="center" class="bg-success text-white w-50"><strong><?php echo number_format((float)$monthly_sale_resalt['total_amount']-$monthly_discount_resalt['total_amount'],2) ?></strong></td>
    </tr>
    <tr>
      <td align="right"><?php echo date("F"); ?> Discount</td>
      <td align="center" class="bg-success text-white w-50"><strong><?php echo number_format((float)$monthly_discount_resalt['total_amount'],2) ?></strong></td>
    </tr>
    <tr>
      <td align="right"><?php echo date("F"); ?> Profit</td>
      <td align="center" class="bg-success text-white"><strong><?php echo number_format((float)$monthly_profit_resalt['total_profit']-$monthly_discount_resalt['total_amount'],2) ?></strong></td>
    </tr>
    <tr>
      <td align="right"><?php echo date("F"); ?> Expenses</td>
      <td align="center" class="bg-danger text-white"><strong><?php echo number_format((float)$monthly_exp_resalt['ex_amount'],2) ?></strong></td>
    </tr>
    <tr>
      <td align="right"><?php echo date("F"); ?> Profit</td>
      <td align="center" class="bg-info text-white"><strong><?php echo number_format((float)$net_profit,2) ?></strong></td>
    </tr>
  </tbody>
</table>

	
</div>
</div>
<?php } } ?>
	
<div class="card mt-4">
<div class="card-header bg-dark text-white text-center">Top 5 sales product</div>
<div class="card-body">
	

<table class="table-sm table table-bordered mb-0 text-capitalize">
  <tbody>
    <tr>
      <th>Product</th>
      <th>Supplier</th>
      <th>QTY</th>
    </tr>
<?php 
$top_qury=mysqli_query($connation,"SELECT pd.product_name,spd.supplier_name,SUM(if(sd.stock_type=0,sd.stock_qty,0)) AS qty
FROM stock_details sd INNER JOIN product_details pd ON sd.stock_systemid=pd.product_systemid
INNER JOIN supplier_details spd ON pd.product_supplier=spd.supplier_id
GROUP BY pd.product_systemid
ORDER BY qty DESC
LIMIT 5");
while($top_resalt=mysqli_fetch_assoc($top_qury)){
?>
    <tr>
		<td style="white-space: pre-line;"><?php echo $top_resalt['product_name']; ?></td>
      <td style="white-space: pre-line;"><?php echo $top_resalt['supplier_name']; ?></td>      
      <td style="white-space: pre-line;" align="right"><?php echo number_format((float)$top_resalt['qty']); ?></td>
    </tr>
<?php } ?>
	  
  </tbody>
</table>

	
</div>
</div>
	
<?php if(isset($current_user_resalt)){ if($current_user_resalt['user_type']==0){}else{ ?>
<div class="card mt-4 bg-white">
<div class="card-body text-center text-secondary" style="font-size: 12px;">
<img src="image/logo.png" class="" style="height: 80px;"><br>
System Powered <br>
<a href="" target="_blank">Nova Script</a><br>
0769 146 421, 0777 404 233
</div>
</div>
<?php } } ?>
	
</div>
	
</div>
</div>

<?php
if(setting_view("low_stock_popup")==1){
if(isset($_SESSION['low_stock_popup'])){}
else{
?>
<div class="model" id="popup_mod" style="z-index: 999999; position: fixed;">
	<div class="model-contain" style="width: 70%;">
		<div class="model-body">
			<h5>Low Stock Alert (<?php echo $current_date; ?>)</h5>
		<iframe src="dashboard_low_stock.php" style="width: 100%; height: 450px; border: none;" scrolling="auto" id="low_load"></iframe>
		</div>
	</div>
</div>
<?php } } ?>


<script>
setInterval(function(){
  var d = new Date();
  var n = d.toLocaleTimeString();
  document.getElementById("time_dis").innerHTML = n;
},10);	
	
function popup_close(){
document.getElementById('popup_mod').classList.add("model-hide");
}
</script>

<script>
    labels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    bar = new RGraph.Bar({
        id: 'cvs',
        data: [<?php echo number_format((float)month_profit(date("Y-01-01"),date("Y-01-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-02-01"),date("Y-02-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-03-01"),date("Y-03-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-04-01"),date("Y-04-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-05-01"),date("Y-05-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-06-01"),date("Y-06-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-07-01"),date("Y-07-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-08-01"),date("Y-08-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-09-01"),date("Y-09-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-10-01"),date("Y-10-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-11-01"),date("Y-11-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-12-01"),date("Y-12-31")),2,".",""); ?>],
        options: {
            xaxis: false,
            yaxis: false,
            xaxisLabels: labels,
            colors: ['#ddf'],
            backgroundGridVlines: false,
            backgroundGridBorder: false,
            textSize: 10,
            colorsStroke: 'rgba(0,0,0,0)',
            marginBottom: 35
        }
    }).grow();



    line = new RGraph.Line({
        id: 'cvs',
                data: [<?php echo number_format((float)month_profit(date("Y-01-01"),date("Y-01-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-02-01"),date("Y-02-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-03-01"),date("Y-03-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-04-01"),date("Y-04-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-05-01"),date("Y-05-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-06-01"),date("Y-06-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-07-01"),date("Y-07-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-08-01"),date("Y-08-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-09-01"),date("Y-09-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-10-01"),date("Y-10-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-11-01"),date("Y-11-31")),2,".",""); ?>,
				<?php echo number_format((float)month_profit(date("Y-12-01"),date("Y-12-31")),2,".",""); ?>],
        options: {
            xaxis: false,
            yaxis: false,
            spline: true,
            shadow: true,
            tickmarksStyle: 'circle',
            tickmarksSize: 5,
            backgroundGridVlines: false,
            backgroundGridBorder: false,
            tooltips: '%{value}',
            tooltipsNames: labels,
            tooltipsCss: {
                backgroundColor: 'black',
                color: 'white',
                fontSize: '10pt'
            },
            marginBottom: 35,
            yaxisScale: false,
            xaxisTickmarksCount: 0,
            yaxisTickmarksCount: 0
        }
    });

    
    line.set('marginInner', (line.canvas.width - line.get('marginLeft') - line.get('marginRight')) / (bar.data.length * 2))
        .trace({frames: 30});
</script>
	
</body>
</html>
<?php @mysqli_close($connation); ?>