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

try {
    // Basic Pagination & Search
    $search = isset($_GET['search']) ? "%" . $_GET['search'] . "%" : "%%";
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    
    // Filters
    $academic_year_id = !empty($_GET['year_id']) ? (int)$_GET['year_id'] : APP_YEAR_ID;
    $class_id = $_GET['class_id'] ?? '';
    $medium_id = $_GET['medium_id'] ?? ''; 
    // REMOVED: stream_id filter variable
    $roll_no = $_GET['roll_no'] ?? '';

    // 1. Build Dynamic WHERE Clause
    $conditions = [];
    $params = [
        ':search' => $search,
        ':yid'    => $academic_year_id
    ];

    // Standard search (Name or Fee Title)
    $conditions[] = "(s.student_name LIKE :search OR ft.fee_title LIKE :search)";
    $conditions[] = "e.academic_year_id = :yid";

    // Smart Class Filter
    if ($class_id !== '') {
        $conditions[] = "ft.class_id = :cid";
        $params[':cid'] = $class_id;
    }

    // Smart Medium Filter
    if ($medium_id !== '') {
        $conditions[] = "e.medium_id = :mid";
        $params[':mid'] = $medium_id;
    }

    // REMOVED: Smart Stream Filter logic block

    // Smart Roll Number Filter
    if ($roll_no !== '') {
        $conditions[] = "e.roll_no = :roll";
        $params[':roll'] = $roll_no;
    }

    $whereSql = implode(" AND ", $conditions);

    // 2. Get total records for pagination
    $countSql = "SELECT COUNT(*) 
                 FROM fee_assign fa 
                 JOIN students s ON fa.student_id = s.id 
                 JOIN fee_types ft ON fa.fee_type_id = ft.id
                 JOIN enrollments e ON fa.student_id = e.student_id AND e.academic_year_id = :yid
                 WHERE $whereSql";
    
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $totalRecords = $countStmt->fetchColumn();
    $totalPages = ceil($totalRecords / $limit);

    // 3. Fetch paginated data
    $sql = "SELECT 
                fa.id,
                fa.student_id,
                fa.total_amount,
                fa.remaining_amount,
                fa.due_date,
                fa.due_month,
                fa.payment_status,
                s.student_name, 
                ft.fee_title,
                c.class_name,
                m.medium_name,
                -- REMOVED: st.stream_name
                e.roll_no
            FROM fee_assign fa
            JOIN students s ON fa.student_id = s.id
            JOIN fee_types ft ON fa.fee_type_id = ft.id
            JOIN classes c ON ft.class_id = c.id
            JOIN enrollments e ON fa.student_id = e.student_id AND e.academic_year_id = :yid
            LEFT JOIN mediums m ON e.medium_id = m.id
            -- REMOVED: LEFT JOIN streams st
            WHERE $whereSql
            ORDER BY fa.id DESC
            LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($sql);
    
    // Bind all params
    foreach ($params as $key => $val) {
        $stmt->bindValue($key, $val);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'data' => $data,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_records' => $totalRecords
        ]
    ]);

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