<?php
require("../../includes/config.php");

header('Content-Type: application/json');
ini_set('display_errors', 0);

try {
    $month = $_GET['month'] ?? date('Y-m');

    // 1. Get Overall Totals
    $total_sql = "SELECT 
                SUM(amount) as total_expected,
                SUM(CASE WHEN payment_status = 'paid' THEN amount ELSE 0 END) as total_collected,
                SUM(CASE WHEN payment_status = 'unpaid' THEN amount ELSE 0 END) as total_pending
            FROM fee_assign 
            WHERE due_month = :month";

    $total_stmt = $pdo->prepare($total_sql);
    $total_stmt->execute([':month' => $month]);
    $summary = $total_stmt->fetch(PDO::FETCH_ASSOC);

    // 2. Get Breakdown by Fee Type (New Section)
    $breakdown_sql = "SELECT 
                        ft.fee_title,
                        SUM(fa.amount) as type_total,
                        SUM(CASE WHEN fa.payment_status = 'paid' THEN fa.amount ELSE 0 END) as type_paid,
                        SUM(CASE WHEN fa.payment_status = 'unpaid' THEN fa.amount ELSE 0 END) as type_pending
                      FROM fee_assign fa
                      JOIN fee_types ft ON fa.fee_type_id = ft.id
                      WHERE fa.due_month = :month
                      GROUP BY ft.fee_title";

    $breakdown_stmt = $pdo->prepare($breakdown_sql);
    $breakdown_stmt->execute([':month' => $month]);
    $breakdown = $breakdown_stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'month' => $month,
        'totals' => [
            'expected' => (float) ($summary['total_expected'] ?? 0),
            'collected' => (float) ($summary['total_collected'] ?? 0),
            'pending' => (float) ($summary['total_pending'] ?? 0)
        ],
        'breakdown' => $breakdown
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>