<?php

session_start();


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

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

}


require_once "config.php";



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



if(!$id){

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

}




// CHECK CATEGORY EXISTS

$stmt=$pdo->prepare("

SELECT *

FROM expense_categories

WHERE id=?

");


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


$category=$stmt->fetch();



if(!$category){


    $_SESSION['error']="Category not found";

    header("Location:categories.php");

    exit;

}






// CHECK IF CATEGORY IS USED


$stmt=$pdo->prepare("

SELECT COUNT(*)

FROM expenses

WHERE category_id=?

");


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


$count=$stmt->fetchColumn();






if($count>0){


    $_SESSION['error']="Cannot delete this category because it has expenses assigned to it.";


    header("Location:categories.php");

    exit;


}






// DELETE CATEGORY


$stmt=$pdo->prepare("

DELETE FROM expense_categories

WHERE id=?

");



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





$_SESSION['success']="Category deleted successfully";



header("Location:categories.php");

exit;



?>