<?php

session_start();


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

    header("Location: login.php");
    exit;

}


require_once "config.php";




// ============================
// BASIC ANALYTICS
// ============================


// Total Expenses

$stmt=$pdo->query("

SELECT COALESCE(SUM(total),0)

FROM expenses

");


$totalExpenses=$stmt->fetchColumn();




// This Month

$stmt=$pdo->query("

SELECT COALESCE(SUM(total),0)

FROM expenses


WHERE MONTH(expense_date)=MONTH(CURRENT_DATE())


AND YEAR(expense_date)=YEAR(CURRENT_DATE())


");


$monthExpenses=$stmt->fetchColumn();




// Today

$stmt=$pdo->query("

SELECT COALESCE(SUM(total),0)

FROM expenses


WHERE expense_date=CURDATE()


");


$todayExpenses=$stmt->fetchColumn();





// Transactions

$stmt=$pdo->query("

SELECT COUNT(*)

FROM expenses


");


$totalTransactions=$stmt->fetchColumn();





// Vendors

$stmt=$pdo->query("

SELECT COUNT(*)

FROM vendors

WHERE status=1


");


$totalVendors=$stmt->fetchColumn();






// Average Expense


$stmt=$pdo->query("

SELECT COALESCE(AVG(total),0)

FROM expenses


");


$averageExpense=$stmt->fetchColumn();






// ============================
// CATEGORY CHART
// ============================



$stmt=$pdo->query("


SELECT


COALESCE(
c.category_name,
'Unknown'
) AS category,


SUM(e.total) amount



FROM expenses e



LEFT JOIN expense_categories c


ON e.category_id=c.id



GROUP BY e.category_id



ORDER BY amount DESC



");



$categoryData=$stmt->fetchAll();




$categoryLabels=[];

$categoryAmounts=[];




foreach($categoryData as $row){


$categoryLabels[]=$row['category'];


$categoryAmounts[]=$row['amount'];


}








// ============================
// CATEGORY PROGRESS AGAINST TOTAL
// ============================



$stmt=$pdo->query("


SELECT


c.category_name,


COALESCE(
SUM(e.total),
0
) AS amount



FROM expense_categories c



LEFT JOIN expenses e


ON c.id=e.category_id



GROUP BY c.id



ORDER BY amount DESC



");



$categoryProgress=$stmt->fetchAll();





foreach($categoryProgress as &$cat){


if($totalExpenses>0){


    $cat['percentage']=round(

        ($cat['amount']/$totalExpenses)*100,

        2

    );


}else{


    $cat['percentage']=0;


}



}








// ============================
// MONTHLY TREND
// ============================



$stmt=$pdo->query("


SELECT


MONTHNAME(expense_date) month,


SUM(total) amount



FROM expenses



WHERE YEAR(expense_date)=YEAR(CURRENT_DATE())



GROUP BY 

MONTH(expense_date),
MONTHNAME(expense_date)



ORDER BY MONTH(expense_date)



");



$monthlyData=$stmt->fetchAll();



$months=[];

$monthlyAmounts=[];




foreach($monthlyData as $row){



$months[]=$row['month'];


$monthlyAmounts[]=$row['amount'];



}



?>
<!DOCTYPE html>

<html>

<head>


<meta name="viewport"
content="width=device-width,initial-scale=1">


<title>
Expense Analytics
</title>



<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">


<link rel="stylesheet"

href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


<link rel="stylesheet" href="assets/css/sidebar.css">



<style>


*{

margin:0;

padding:0;

box-sizing:border-box;

font-family:Poppins;

}




body{

background:#f4f7f9;

transition:.3s;

}



body.dark{

background:#111827;

color:white;

}




.content{

margin-left:260px;

padding:25px;

}


.chart{

background:white;

padding:25px;

border-radius:20px;

box-shadow:
0 10px 30px rgba(0,0,0,.08);

transition:.3s;

}



.chart:hover{

transform:translateY(-5px);

box-shadow:
0 15px 40px rgba(0,0,0,.12);

}



.chart canvas{

height:380px!important;

}


.topbar{

display:flex;

justify-content:space-between;

align-items:center;

margin-bottom:20px;

}





.mobile-btn{

display:none;

font-size:25px;

cursor:pointer;

color:#059669;

}




.toggle{

font-size:24px;

cursor:pointer;

color:#059669;

}




.cards{


display:grid;

grid-template-columns:

repeat(auto-fit,minmax(170px,1fr));


gap:15px;


}



.card{


background:white;

padding:15px;

border-radius:15px;


display:flex;

align-items:center;

gap:15px;


box-shadow:0 5px 20px #0001;


}




body.dark .card{

background:#1f2937;

}





.icon-box{


width:45px;

height:45px;


border-radius:12px;


display:flex;

align-items:center;

justify-content:center;


background:#ecfdf5;


color:#059669;


font-size:20px;


}





.card p{

font-size:12px;

color:#777;

}



body.dark .card p{

color:#ddd;

}





.number{


font-size:20px;

font-weight:bold;


color:#065f46;


}



body.dark .number{

color:#10b981;

}





.charts{


display:grid;


grid-template-columns:

repeat(auto-fit,minmax(350px,1fr));


gap:20px;


margin-top:25px;


}






.chart,


.progress-box{


background:white;


padding:20px;


border-radius:15px;


box-shadow:0 5px 20px #0001;


}





body.dark .chart,

body.dark .progress-box{


background:#1f2937;


}








/* CATEGORY PROGRESS */


.progress-item{


margin-bottom:20px;


}



.progress-title{


display:flex;

justify-content:space-between;


font-size:14px;


margin-bottom:8px;


}





.progress{


height:18px;


background:#e5e7eb;


border-radius:20px;


overflow:hidden;


}





.progress-bar{


height:100%;


background:linear-gradient(

90deg,

#059669,

#10b981

);


border-radius:20px;


display:flex;


justify-content:flex-end;


align-items:center;


padding-right:8px;


color:white;


font-size:11px;


font-weight:bold;


}





.amount{


font-size:12px;


color:#64748b;


margin-top:5px;


}




body.dark .amount{


color:#d1d5db;


}









@media(max-width:768px){



.sidebar{

left:-260px;

}



.sidebar.active{

left:0;

}





.content{


margin-left:0;

padding:15px;


}




.mobile-btn{

display:block;

}




.charts{


grid-template-columns:1fr;


}




}





</style>



</head>



<body>




<?php include "sidebar.php"; ?>





<div class="content">





<div class="topbar">


<i class="fa fa-bars mobile-btn"

onclick="openMenu()">

</i>




<h2>

<i class="fa fa-chart-pie"></i>

Analytics

</h2>





<i class="fa fa-moon toggle"

onclick="theme()">

</i>



</div>









<!-- SUMMARY CARDS -->


<div class="cards">





<div class="card">


<div class="icon-box">

<i class="fa fa-money-bill"></i>

</div>


<div>

<p>Total Expenses</p>


<div class="number">

 <?=number_format($totalExpenses)?>

</div>


</div>


</div>







<div class="card">


<div class="icon-box">

<i class="fa fa-calendar"></i>

</div>


<div>


<p>This Month</p>


<div class="number">

 <?=number_format($monthExpenses)?>

</div>


</div>


</div>







<div class="card">


<div class="icon-box">

<i class="fa fa-wallet"></i>

</div>


<div>


<p>Today</p>


<div class="number">

 <?=number_format($todayExpenses)?>

</div>


</div>


</div>







<div class="card">


<div class="icon-box">

<i class="fa fa-file-invoice"></i>

</div>


<div>


<p>Transactions</p>


<div class="number">

<?=$totalTransactions?>

</div>


</div>


</div>







<div class="card">


<div class="icon-box">

<i class="fa fa-building"></i>

</div>


<div>


<p>Vendors</p>


<div class="number">

<?=$totalVendors?>

</div>


</div>


</div>





<div class="card">


<div class="icon-box">

<i class="fa fa-chart-line"></i>

</div>


<div>


<p>Average Expense</p>


<div class="number">

 <?=number_format($averageExpense)?>

</div>


</div>


</div>






</div>






<!-- CHARTS -->


<div class="charts">



<div class="chart">


<h3>

<i class="fa fa-chart-pie"></i>

Expense By Category

</h3>



<br>


<canvas id="categoryChart"></canvas>



</div>







<div class="chart">


<h3>

<i class="fa fa-chart-line"></i>

Monthly Expense Trend

</h3>


<br>


<canvas id="monthlyChart"></canvas>



</div>



</div>






<!-- CATEGORY PROGRESS -->



<div class="progress-box">


<h3>

<i class="fa fa-chart-bar"></i>

Expense Category Distribution

</h3>


<br>




<?php foreach($categoryProgress as $cat){ ?>



<div class="progress-item">



<div class="progress-title">


<strong>

<?php if(isset($cat['id'])){ ?>

<a class="category-link"
href="category_details.php?id=<?=$cat['id']?>">

<?=htmlspecialchars($cat['category_name'])?>

</a>

<?php } else { ?>

<?=htmlspecialchars($cat['category_name'])?>

<?php } ?>
</strong>



<span>

<?=$cat['percentage']?>%

</span>


</div>




<div class="progress">


<div class="progress-bar"

style="width:<?=$cat['percentage']?>%">


<?=$cat['percentage']?>%


</div>


</div>




<div class="amount">


 <?=number_format($cat['amount'])?>

/

 <?=number_format($totalExpenses)?>


</div>



</div>



<?php } ?>


<div class="chart">


<div style="
display:flex;
justify-content:space-between;
align-items:center;
">

<h3>
<i class="fa fa-chart-column"></i>
Financial Category Analysis
</h3>


<span style="
background:#ecfdf5;
color:#059669;
padding:8px 15px;
border-radius:20px;
font-size:12px;
font-weight:600;
">

LIVE ANALYTICS

</span>


</div>


<br>


<canvas id="budgetChart"></canvas>


</div>

</div>



</div>
<script>


// ===========================
// MOBILE SIDEBAR
// ===========================


function openMenu(){

document.getElementById("sidebar")

.classList.add("active");


}




function closeMenu(){

document.getElementById("sidebar")

.classList.remove("active");


}





// ===========================
// DARK MODE
// ===========================


function theme(){


document.body.classList.toggle("dark");


localStorage.setItem(

"dark",

document.body.classList.contains("dark")

);


}



if(localStorage.getItem("dark")=="true"){


document.body.classList.add("dark");


}






// ===========================
// CATEGORY PIE CHART
// ===========================



new Chart(

document.getElementById('categoryChart'),

{


type:'doughnut',


data:{


labels:

<?=json_encode($categoryLabels)?>,



datasets:[{


label:'Expenses',


data:

<?=json_encode($categoryAmounts)?>


}]


},



options:{


responsive:true,


plugins:{


legend:{


position:'bottom'


}


}


}



}

);








// ===========================
// MONTHLY EXPENSE TREND
// ===========================



new Chart(

document.getElementById('monthlyChart'),

{


type:'line',


data:{



labels:

<?=json_encode($months)?>,



datasets:[{


label:'Monthly Expenses',



data:

<?=json_encode($monthlyAmounts)?>,


fill:true,


tension:.4



}]


},



options:{


responsive:true,


plugins:{


legend:{


display:true


}


}


}



}

);





</script>


<?php

// ============================
// CATEGORY BUDGET VS EXPENSE VS BALANCE
// ============================


$stmt=$pdo->query("

SELECT

c.category_name,
c.id,

c.budget_limit,

COALESCE(SUM(e.total),0) expenses,


(c.budget_limit - COALESCE(SUM(e.total),0)) balance


FROM expense_categories c


LEFT JOIN expenses e

ON c.id=e.category_id


GROUP BY c.id


ORDER BY c.category_name


");


$budgetData=$stmt->fetchAll();



$budgetLabels=[];

$budgetAmounts=[];

$expenseAmounts=[];

$balanceAmounts=[];



foreach($budgetData as $row){


$budgetLabels[]=$row['category_name'];


$budgetAmounts[]=$row['budget_limit'];


$expenseAmounts[]=$row['expenses'];


$balanceAmounts[]=$row['balance'];


}





?>


<script>
// ===========================
// CATEGORY BUDGET CHART
// ===========================


const budgetCanvas = document.getElementById('budgetChart');


if(budgetCanvas){


new Chart(budgetCanvas, {


type:'bar',


data:{


labels: <?=json_encode($budgetLabels ?? [])?>,


datasets:[


{
label:'Budget',

data: <?=json_encode($budgetAmounts ?? [])?>,

backgroundColor:'#3b82f6',

borderRadius:10

},


{
label:'Expenses',

data: <?=json_encode($expenseAmounts ?? [])?>,

backgroundColor:'#ef4444',

borderRadius:10

},


{
label:'Balance',

data: <?=json_encode($balanceAmounts ?? [])?>,

backgroundColor:'#10b981',

borderRadius:10

}


]


},



options:{


responsive:true,


maintainAspectRatio:false,


plugins:{


legend:{


position:'bottom'


},



tooltip:{


callbacks:{


label:function(context){


return context.dataset.label+
":  "+
Number(context.raw).toLocaleString();


}


}



}


},



scales:{


y:{


beginAtZero:true,


ticks:{


callback:function(value){


return " "+value.toLocaleString();


}


}


}


}



}



});


}f

</script>
</body>

</html>