<?php
header('Content-Type: application/json');
require("../../includes/config.php");

$date = $_GET['date'] ?? date('Y-m-d');
$type = $_GET['type'] ?? 'daily'; // 'daily' or 'uptodate'
$year_id = defined('APP_YEAR_ID') ? APP_YEAR_ID : 0;

try {
    // If "uptodate", we find the start date of the current academic year
    $whereClause = "WHERE DATE(fp.payment_date) = :pay_date";
    $params = ['pay_date' => $date];

    if ($type === 'uptodate') {
        // Fetch the start date of the academic year from your years table
        $yearQuery = $pdo->prepare("SELECT start_date FROM academic_years WHERE id = ?");
        $yearQuery->execute([$year_id]);
        $yearData = $yearQuery->fetch();
        $startDate = $yearData['start_date'] ?? date('Y-01-01');

        $whereClause = "WHERE DATE(fp.payment_date) BETWEEN :start_date AND :pay_date";
        $params = [
            'start_date' => $startDate,
            'pay_date' => date('Y-m-d') // Today
        ];
    }

    // 1. Breakdown Query
    $breakdownSql = "SELECT payment_mode, COUNT(*) as transactions, 
                     SUM(amount_paid) as net_cash, SUM(discount_amount) as total_discount 
                     FROM fee_payments fp $whereClause GROUP BY payment_mode";
    $stmt = $pdo->prepare($breakdownSql);
    $stmt->execute($params);
    $breakdown = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. Class Summary Query
    $classSql = "SELECT c.class_name, COUNT(fp.id) as transactions, SUM(fp.amount_paid) as class_total
                 FROM fee_payments fp
                 LEFT JOIN enrollments e ON fp.student_id = e.student_id AND e.academic_year_id = :year_id
                 LEFT JOIN classes c ON e.class_id = c.id
                 $whereClause
                 GROUP BY c.id ORDER BY c.id ASC";
    $stmtClass = $pdo->prepare($classSql);
    // Add year_id to params for the class join
    $classParams = array_merge($params, ['year_id' => $year_id]);
    $stmtClass->execute($classParams);
    $classBreakdown = $stmtClass->fetchAll(PDO::FETCH_ASSOC);

    // 3. Transactions Query (Stream Join Removed)
    $listSql = "SELECT fp.*, s.student_name, c.class_name,
                TIME_FORMAT(fp.payment_date, '%h:%i %p') as pay_time,
                DATE_FORMAT(fp.payment_date, '%d-%b') as pay_day
                FROM fee_payments fp
                LEFT JOIN students s ON fp.student_id = s.id
                LEFT JOIN enrollments e ON fp.student_id = e.student_id AND e.academic_year_id = :year_id
                LEFT JOIN classes c ON e.class_id = c.id
                $whereClause ORDER BY fp.payment_date DESC LIMIT 500";
    $stmtList = $pdo->prepare($listSql);
    $stmtList->execute($classParams);
    $transactions = $stmtList->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'type' => $type,
        'breakdown' => $breakdown,
        'class_summary' => $classBreakdown,
        'transactions' => $transactions
    ]);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>