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

$response = ['status' => 'error', 'message' => '', 'data' => [], 'total_pages' => 0];

try {
    // 1. Get Parameters
    $search = isset($_GET['search']) ? "%" . $_GET['search'] . "%" : "%";
    
    // Academic Year Filter
    $year_id = isset($_GET['year_id']) && !empty($_GET['year_id']) ? (int)$_GET['year_id'] : APP_YEAR_ID;
    
    // Class and Medium Filters
    $class_id = isset($_GET['class_id']) && !empty($_GET['class_id']) ? (int)$_GET['class_id'] : null;
    $medium_id = isset($_GET['medium_id']) && !empty($_GET['medium_id']) ? (int)$_GET['medium_id'] : null;

    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 10; 
    $offset = ($page - 1) * $limit;

    // Build conditional WHERE clause
    $whereConditions = "((ft.fee_title LIKE :search OR c.class_name LIKE :search)) AND ft.academic_year_id = :year_id";
    $params = [':search' => $search, ':year_id' => $year_id];

    if ($class_id) {
        $whereConditions .= " AND ft.class_id = :class_id";
        $params[':class_id'] = $class_id;
    }
    if ($medium_id) {
        $whereConditions .= " AND ft.medium_id = :medium_id";
        $params[':medium_id'] = $medium_id;
    }

    // 2. Count total records
    $countSql = "SELECT COUNT(*) FROM fee_types ft 
                 INNER JOIN classes c ON ft.class_id = c.id 
                 WHERE $whereConditions";
    
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total_rows = $countStmt->fetchColumn();
    $total_pages = ceil($total_rows / $limit);

    // 3. Fetch Data (Removed stream_id and streams JOIN)
    $sql = "SELECT ft.id, ft.fee_title, ft.description, ft.amount, ft.status, ft.km_range, ft.medium_id,
                   c.class_name, ay.year_name, m.medium_name 
            FROM fee_types ft
            INNER JOIN classes c ON ft.class_id = c.id
            INNER JOIN academic_years ay ON ft.academic_year_id = ay.id
            LEFT JOIN mediums m ON ft.medium_id = m.id
            WHERE $whereConditions
            ORDER BY ay.year_name DESC, c.class_name ASC, m.medium_name ASC, ft.fee_title ASC
            LIMIT :limit OFFSET :offset";
            
    $stmt = $pdo->prepare($sql);
    
    // Bind all params
    foreach ($params as $key => $val) {
        $stmt->bindValue($key, $val, is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    $fee_types = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response['status'] = 'success';
    $response['data'] = $fee_types;
    $response['total_pages'] = $total_pages;
    $response['current_page'] = $page;

} catch (PDOException $e) {
    $response['message'] = 'Database Error: ' . $e->getMessage();
}

echo json_encode($response);
?>