<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
    exit();
}

// Get filter params
$session = mysqli_real_escape_string($con, $_GET['session']);
$term = mysqli_real_escape_string($con, $_GET['term']);

// Build query
$where = "1"; // Default to no filter
if (!empty($session)) {
    $where .= " AND session = '$session'";
}
if (!empty($term)) {
    $where .= " AND Term = '$term'";
}

// Fetching data with Term and session
$query = "
    SELECT session, Term, 
        SUM(amount) AS total_collected, 
        SUM(discount_amount) AS total_discount
    FROM payment
    WHERE $where
    GROUP BY session, Term
    ORDER BY session DESC, 
             FIELD(Term, 'First Term', 'Second Term', 'Third Term', 'Fourth Term')
";



$result = mysqli_query($con, $query);

// Prepare data for chart and table
$data = [];
$labels = [];
$amounts = [];
$discounts = [];
$totalSum = 0;
$totalDiscount = 0;


if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $row['total_discount'] = $row['total_discount'] ?? 0;

        $data[] = $row;
        $labels[] = $row['session'] . " " . ($row['Term'] ? $row['Term'] : 'No Term Info');
        $amounts[] = $row['total_collected'];
        $discounts[] = $row['total_discount'];
        $totalSum += $row['total_collected'];
        $totalDiscount += $row['total_discount'];
    }
}

$response = [
    'labels' => $labels,
    'amounts' => $amounts,
    'discounts' => $discounts,
    'rows' => $data,
    'totalSum' => $totalSum,
    'totalDiscount' => $totalDiscount,
];


echo json_encode($response);
