<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Models\Student;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final class StudentsController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $students = Student::where('tenant_id', $tenantId)->with('template')->get();
        return $this->json($response, $students->toArray());
    }

    public function store(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $data = json_decode($request->getBody()->getContents(), true);

        $student = Student::create([
            'tenant_id' => $tenantId,
            'template_id' => $data['template_id'] ?? null,
            'first_name' => $data['first_name'] ?? '',
            'last_name' => $data['last_name'] ?? '',
            'email' => $data['email'] ?? '',
            'phone' => $data['phone'] ?? '',
            'needs_glasses' => $data['needs_glasses'] ?? 0,
            'status' => $data['status'] ?? 'active',
            'notes' => $data['notes'] ?? '',
        ]);

        return $this->json($response, $student->toArray(), 201);
    }

    public function update(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $student = Student::where('id', $args['id'])->where('tenant_id', $tenantId)->first();

        if (!$student) {
            return $this->json($response, ['message' => 'Student not found'], 404);
        }

        $data = json_decode($request->getBody()->getContents(), true);
        $student->update(array_intersect_key($data, array_flip([
            'first_name', 'last_name', 'email', 'phone', 'needs_glasses', 'status', 'notes', 'template_id'
        ])));

        return $this->json($response, $student->fresh()->toArray());
    }

    public function destroy(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $student = Student::where('id', $args['id'])->where('tenant_id', $tenantId)->first();

        if (!$student) {
            return $this->json($response, ['message' => 'Student not found'], 404);
        }

        $student->delete();
        return $this->json($response, ['message' => 'Deleted']);
    }

    private function json(ResponseInterface $response, array $data, int $status = 200): ResponseInterface
    {
        $response->getBody()->write(json_encode($data));
        return $response->withStatus($status)->withHeader('Content-Type', 'application/json');
    }
}