<?php

declare(strict_types=1);

namespace App\Controllers;

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

final class InstructorsController
{
    public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $instructors = Instructor::where('tenant_id', $tenantId)->get();
        return $this->json($response, $instructors->toArray());
    }

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

        $instructor = Instructor::create([
            'tenant_id' => $tenantId,
            'first_name' => $data['first_name'] ?? '',
            'last_name' => $data['last_name'] ?? '',
            'color' => $data['color'] ?? '#0e5d80',
            'notes' => $data['notes'] ?? '',
            'is_active' => 1,
            'pre_start_buffer_minutes' => $data['pre_start_buffer_minutes'] ?? 60,
        ]);

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

    public function update(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $tenantId = $request->getAttribute('tenant_id');
        $instructor = Instructor::where('id', $args['id'])->where('tenant_id', $tenantId)->first();
        if (!$instructor) return $this->json($response, ['message' => 'Not found'], 404);

        $data = json_decode($request->getBody()->getContents(), true);
        $instructor->update(array_intersect_key($data, array_flip(['first_name', 'last_name', 'color', 'notes', 'is_active', 'pre_start_buffer_minutes'])));

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

    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');
    }
}