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

// 1. Force ID to be an integer and check validity
$id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_VALIDATE_INT) : null;

$response = [
    'status' => 'error', 
    'message' => 'Invalid fee type ID.', 
    'data' => null
];

if ($id) {
    try {
        // REMOVED: stream_id and stream_name fields/joins
        $sql = "SELECT 
                    ft.id, 
                    ft.fee_title, 
                    ft.description, 
                    ft.academic_year_id, 
                    ft.amount, 
                    ft.status, 
                    ft.class_id,
                    ft.medium_id,
                    ft.km_range,
                    c.class_name,
                    m.medium_name
                FROM fee_types ft
                LEFT JOIN classes c ON ft.class_id = c.id 
                LEFT JOIN mediums m ON ft.medium_id = m.id
                WHERE ft.id = :id";
                
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':id' => $id]);

        $fee_type = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($fee_type) {
            $response['status'] = 'success';
            $response['message'] = 'Data retrieved.';
            
            // Clean up null values for JS consistency
            $fee_type['km_range'] = $fee_type['km_range'] ?? 0;
            $fee_type['medium_id'] = $fee_type['medium_id'] ?? ""; 
            
            $response['data'] = $fee_type;
        } else {
            $response['message'] = 'Fee type not found in the database.';
        }
    } catch (PDOException $e) {
        $response['status'] = 'error';
        $response['message'] = 'Database Error: ' . $e->getMessage();
        error_log("Edit Fee API Error: " . $e->getMessage());
    }
}

echo json_encode($response);
?>