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

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

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

        if (empty($rows)) {
            $payload = [
                "status"   => "false",
                "message"  => "No attendance found for this roll number",
                "Students" => []
            ];
        } else {
            $students = [];
            foreach ($rows as $row) {
                $students[] = [
                    "date"    => $row['date'],
                    "rollno"  => $row['rollno'],
                    "stdname" => $row['stdname'],
                    "status"  => $row['status'],
                ];
            }

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

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