<?php

session_start();

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

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

}

require_once "config.php";


// =============================
// CATEGORY ID
// =============================

$category_id=$_GET['id'] ?? 0;



// =============================
// CATEGORY DETAILS
// =============================

$stmt=$pdo->prepare("
SELECT *
FROM expense_categories
WHERE id=?
");

$stmt->execute([$category_id]);

$category=$stmt->fetch();


if(!$category){

    die("Category not found");

}



// =============================
// FILTERS
// =============================

$search=$_GET['search'] ?? '';

$start=$_GET['start'] ?? '';

$end=$_GET['end'] ?? '';




// =============================
// EXPENSE LIST
// =============================

$sql="
SELECT

e.*,

v.vendor_name,

c.category_name

FROM expenses e

LEFT JOIN vendors v
ON e.vendor_id=v.id

LEFT JOIN expense_categories c
ON e.category_id=c.id


WHERE e.category_id=?

";


$params=[
$category_id
];



if($search!=""){


$sql.="

AND (

e.description LIKE ?

OR v.vendor_name LIKE ?

)

";


$params[]="%".$search."%";

$params[]="%".$search."%";


}



if($start!=""){

$sql.=" AND e.expense_date >= ?";

$params[]=$start;

}



if($end!=""){

$sql.=" AND e.expense_date <= ?";

$params[]=$end;

}



$sql.=" ORDER BY e.expense_date DESC";



$stmt=$pdo->prepare($sql);

$stmt->execute($params);

$expenses=$stmt->fetchAll();





// =============================
// SUMMARY
// =============================


$stmt=$pdo->prepare("

SELECT COALESCE(SUM(total),0)

FROM expenses

WHERE category_id=?

");


$stmt->execute([$category_id]);

$totalSpent=$stmt->fetchColumn();



$budget=$category['budget_limit'];

$balance=$budget-$totalSpent;



$percentage=0;


if($budget>0){

$percentage=round(
($totalSpent/$budget)*100
);

}



$status="safe";


if($percentage>=100){

$status="danger";

}
elseif($percentage>=70){

$status="warning";

}





// =============================
// STATISTICS
// =============================


$stmt=$pdo->prepare("

SELECT

COUNT(*) total_count,

COALESCE(AVG(total),0) average_expense,

COALESCE(MAX(total),0) highest_expense


FROM expenses

WHERE category_id=?

");


$stmt->execute([$category_id]);

$stats=$stmt->fetch();




$stmt=$pdo->prepare("

SELECT COUNT(DISTINCT vendor_id)

FROM expenses

WHERE category_id=?

");


$stmt->execute([$category_id]);

$vendorCount=$stmt->fetchColumn();


?>

<!DOCTYPE html>

<html>

<head>


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



<title>

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

</title>


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


<link rel="stylesheet"

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


<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;

}




.topbar{

display:flex;

justify-content:space-between;

align-items:center;

}



.mobile-btn{

display:none;

font-size:25px;

color:#059669;

cursor:pointer;

}



.toggle{

font-size:25px;

color:#059669;

cursor:pointer;

}




.cards{

display:grid;

grid-template-columns:

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

gap:15px;

margin-top:20px;

}




.card{

background:white;

padding:15px;

border-radius:15px;

display:flex;

align-items:center;

gap:12px;

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

transition:.3s;

}



.card:hover{

transform:translateY(-3px);

}



body.dark .card,

body.dark .filter,

body.dark .transaction-card{

background:#1f2937;

color:white;

}




.icon-box{

width:45px;

height:45px;

border-radius:12px;

background:#ecfdf5;

display:flex;

align-items:center;

justify-content:center;

color:#059669;

font-size:20px;

}




.card-info p{

font-size:12px;

color:#777;

}


body.dark .card-info p{

color:#ccc;

}




.number{

font-size:18px;

font-weight:700;

color:#065f46;

}


body.dark .number{

color:#10b981;

}



.warning-text{

color:#f59e0b!important;

}


.danger-text{

color:#dc2626!important;

}





.filter{

background:white;

padding:20px;

border-radius:15px;

margin-top:25px;

}



input{

padding:12px;

border-radius:10px;

border:1px solid #ddd;

margin:5px;

}



button{

background:#059669;

color:white;

border:0;

padding:12px 20px;

border-radius:10px;

}




.transaction-card{

background:white;

padding:18px;

border-radius:15px;

margin-top:15px;

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

}




.amount{

font-weight:700;

color:#059669;

font-size:18px;

}



.vendor{

font-size:13px;

color:#64748b;

}



@media(max-width:768px){



.sidebar{

left:-280px;

}


.sidebar.active{

left:0;

}



.content{

margin-left:0;

padding:15px;

}



.mobile-btn{

display:block;

}



.cards{

grid-template-columns:

repeat(2,1fr);

gap:10px;

}



.card{

padding:12px;

}



.icon-box{

width:38px;

height:38px;

font-size:16px;

}



.number{

font-size:15px;

}



.filter form{

display:flex;

flex-direction:column;

}



input,button{

width:100%;

}



}



</style>


</head>
<body>


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


<div id="overlay"
class="overlay"
onclick="closeMenu()">
</div>



<div class="content">


<div class="topbar">


<div style="display:flex;align-items:center;gap:15px;">


<i class="fa fa-bars mobile-btn"
onclick="openMenu()">
</i>



<a href="javascript:history.back()"
style="
background:#059669;
color:white;
padding:8px 14px;
border-radius:10px;
text-decoration:none;
font-size:14px;
">

<i class="fa fa-arrow-left"></i>

Back

</a>




<h2>

<i class="fa fa-folder-open"></i>

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

</h2>


</div>



<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-wallet"></i>

</div>


<div class="card-info">

<p>Budget</p>

<div class="number">

 <?=number_format($budget)?>

</div>


</div>

</div>






<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Spent</p>

<div class="number">

 <?=number_format($totalSpent)?>

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Balance</p>


<div class="number 
<?=($balance<0)?'danger-text':''?>">

 <?=number_format($balance)?>

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Usage</p>


<div class="number 
<?=($status=="danger")?'danger-text':''?>">

<?=$percentage?>%

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Transactions</p>


<div class="number">

<?=$stats['total_count']?>

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Vendors</p>


<div class="number">

<?=$vendorCount?>

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

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

</div>


<div class="card-info">

<p>Average</p>


<div class="number">

<?=number_format($stats['average_expense'])?>

</div>


</div>

</div>







<div class="card">

<div class="icon-box">

<i class="fa fa-arrow-up"></i>

</div>


<div class="card-info">

<p>Highest</p>


<div class="number">

<?=number_format($stats['highest_expense'])?>

</div>


</div>

</div>



</div>







<!-- BUDGET STATUS -->


<div class="filter">


<h3>

Budget Status

</h3>


<br>


<div>


<span>

<?php

if($status=="danger"){

echo "Over Budget";

}

elseif($status=="warning"){

echo "Near Limit";

}

else{

echo "Within Budget";

}

?>

</span>


</div>



<br>


<div style="
height:15px;
background:#e5e7eb;
border-radius:20px;
overflow:hidden;
">


<div style="
height:100%;
width:<?=min($percentage,100)?>%;
background:

<?php

echo $status=="danger"
?
'#ef4444'
:
($status=="warning"
?
'#f59e0b'
:
'#10b981');

?>

">

</div>


</div>



</div>








<!-- SEARCH FILTER -->


<div class="filter">


<form method="get">


<input type="hidden"
name="id"
value="<?=$category_id?>">



<input

name="search"

placeholder="Search expense or vendor"

value="<?=htmlspecialchars($search)?>">



<input

type="date"

name="start"

value="<?=$start?>">



<input

type="date"

name="end"

value="<?=$end?>">



<button>

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

Search

</button>



</form>


</div>







<h2 style="margin-top:25px">

Expense Transactions

</h2>





<?php if(count($expenses)>0){ ?>


<?php foreach($expenses as $e){ ?>



<div class="transaction-card">



<div style="
display:flex;
justify-content:space-between;
flex-wrap:wrap;
">


<strong>

<?=$e['expense_date']?>

</strong>


<div class="amount">

 <?=number_format($e['total'])?>

</div>



</div>





<p style="margin-top:10px">


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


<?=htmlspecialchars($e['description'])?>


</p>





<div class="vendor">


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


<?=htmlspecialchars($e['vendor_name'] ?? 'No Vendor')?>


&nbsp; | &nbsp;


<i class="fa fa-credit-card"></i>


<?=htmlspecialchars($e['payment_method'] ?? 'N/A')?>


</div>




</div>



<?php } ?>


<?php }else{ ?>


<div class="transaction-card">


<center>

<i class="fa fa-folder-open fa-3x"></i>


<h3>

No Expenses Found

</h3>


<p>

No transactions available in this category.

</p>


</center>


</div>


<?php } ?>



</div>
<script>


// ============================
// MOBILE MENU
// ============================


function openMenu(){


document
.getElementById("sidebar")
.classList.add("active");



document
.getElementById("overlay")
.classList.add("show");


}





function closeMenu(){


document
.getElementById("sidebar")
.classList.remove("active");



document
.getElementById("overlay")
.classList.remove("show");


}





// CLOSE MENU AFTER CLICK

document
.querySelectorAll(".sidebar a")
.forEach(link=>{


link.addEventListener(
"click",
closeMenu
);


});




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


function theme(){


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


localStorage.setItem(

"dark",

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

);


}




// LOAD SAVED THEME

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


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


}






// ============================
// PRINT MODE
// ============================


window.onbeforeprint=function(){


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


}




</script>



</body>

</html>