<?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/result/{rollno}
     * Returns student result by roll number
     * Same response format as original apiresult.php
     */
    $app->get('/api/result/{rollno}', function (Request $request, Response $response, array $args) {

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

        // Prepared statement prevents SQL injection
        $stmt = $db->prepare("SELECT * FROM result WHERE std_rollno = :rollno");
        $stmt->execute([':rollno' => $rollno]);
        $rows = $stmt->fetchAll();

        if (empty($rows)) {
            $payload = [
                "status"   => "false",
                "message"  => "No result found for this roll number",
                "Students" => []
            ];
        } else {
            // Build clean array — same fields as original
            $students = [];
            foreach ($rows as $row) {
                $students[] = [
                    "std_rollno" => $row['std_rollno'],
                    "std_name"   => $row['std_name'],
                    "sess1"      => $row['sess1'],
                    "term"       => $row['term'],
                    "month_name" => $row['month_name'],
                    "totalmark"  => $row['totalmark'],
                    "obtmark"    => $row['obtmark'],
                    "per"        => $row['per'],
                    "status"     => $row['status'],
                    "grade"      => $row['grade'],
                    "remarks"    => $row['remarks'],
                ];
            }

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

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