<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Models\Tenant;
use App\Models\User;
use App\Models\Student;
use App\Models\Instructor;
use App\Models\Appointment;
use App\Models\LessonType;
use App\Models\LicenseClassTemplate;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final class BootstrapController
{
    public function handle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $user = $request->getAttribute('user');
        $tenantId = (int) $user['tenant_id'];

        // Load tenant
        $tenant = Tenant::find($tenantId);
        if (!$tenant) {
            return $this->json($response, ['message' => 'Tenant not found'], 404);
        }

        // Load all related data
        $students = Student::where('tenant_id', $tenantId)->with('template')->get();
        $instructors = Instructor::where('tenant_id', $tenantId)->get();
        $lessonTypes = LessonType::where('tenant_id', $tenantId)->orderBy('sort_order')->get();
        $templates = LicenseClassTemplate::where('tenant_id', $tenantId)->with('requirements')->get();

        // Date range from query params
        $params = $request->getQueryParams();
        $from = $params['from'] ?? gmdate('Y-m-d\TH:i:s\Z', strtotime('monday this week'));
        $to = $params['to'] ?? gmdate('Y-m-d\TH:i:s\Z', strtotime('+7 day', strtotime($from)));

        // Load appointments
        $appointments = Appointment::where('tenant_id', $tenantId)
            ->whereBetween('start_at', [$from, $to])
            ->with(['student', 'instructor', 'lessonType'])
            ->get();

        $payload = [
            'session' => ['user' => $user],
            'tenant' => $tenant->toArray(),
            'students' => $students->toArray(),
            'instructors' => $instructors->toArray(),
            'lessonTypes' => $lessonTypes->toArray(),
            'templates' => $templates->toArray(),
            'appointments' => $appointments->toArray(),
        ];

        return $this->json($response, $payload);
    }

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