<?php

namespace App\Routes;

use App\Database;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;

return function (App $app) {

    /**
     * GET /api/fee/{adm_no}
     * Returns student fee records by admission number
     * Same response format as original apifee.php
     */
    $app->get('/api/fee/{adm_no}', function (Request $request, Response $response, array $args) {

        $adm_no = $args['adm_no'];
        $db     = Database::getConnection();

        $stmt = $db->prepare("SELECT * FROM rec_fee WHERE adm_no = :adm_no");
        $stmt->execute([':adm_no' => $adm_no]);
        $rows = $stmt->fetchAll();

        if (empty($rows)) {
            $payload = [
                "status"   => "false",
                "message"  => "No fee records found for this admission number",
                "Students" => []
            ];
        } else {
            $students = [];
            foreach ($rows as $row) {
                $students[] = [
                    "date"         => $row['date'],
                    "RollNo"       => $row['adm_no'],
                    "Student Name" => $row['stdname'],
                    "Fee PAid"     => $row['feerec'],
                ];
            }

            $payload = [
                "status"   => "true",
                "message"  => "Students Details",
                "Students" => $students
            ];
        }

        $response->getBody()->write(json_encode($payload));
        return $response->withHeader('Content-Type', 'application/json');
    });
};
