<?php
// Start session if not already started
session_start();
require 'db_connection.php';

// Fetch current session and term from settings table
$sql = "SELECT current_session, current_term FROM settings";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    $row = $result->fetch_assoc();
    $currentSession = $row['current_session'];
    $currentTerm = $row['current_term'];
} else {
    // Default values if no settings are found (optional)
    $currentSession = "Session Not Set";
    $currentTerm = "Term Not Set";
}


// Assuming you have stored the username in session after login
if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
} else {
    // Handle if username is not set in session (e.g., redirect to login)
    header("Location: login.php");
    exit();
}


$totalIncome = $conn->query("SELECT SUM(amount) AS total FROM financial_transactions WHERE type='income'")->fetch_assoc()['total'];
$totalExpenditure = $conn->query("SELECT SUM(amount) AS total FROM financial_transactions WHERE type='expenditure'")->fetch_assoc()['total'];

// Fetch notifications
$notifications = $conn->query("SELECT message, created_at FROM notifications ORDER BY created_at DESC LIMIT 5")->fetch_all(MYSQLI_ASSOC);

// Fetch recent activities (example: student registrations, fee payments, etc.)
$recentActivities = $conn->query("SELECT description, date FROM financial_transactions ORDER BY date DESC LIMIT 5")->fetch_all(MYSQLI_ASSOC);

echo json_encode([
    'studentCount' => $studentCount,
    'teacherCount' => $teacherCount,
    'totalIncome' => $totalIncome,
    'totalExpenditure' => $totalExpenditure,
    'notifications' => $notifications,
    'recentActivities' => $recentActivities
]);
?>
