<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Security;
use App\Models\DemoData;
use App\Repositories\InstitutionRepository;
use App\Repositories\ReportRepository;
use App\Services\DocumentGenerator;
use App\Services\InstitutionDeliveryService;

final class ReportController extends Controller
{
    public function create(): string
    {
        return $this->view('reports/create', [
            'title' => 'Подай сигнал',
            'categories' => DemoData::categories(),
            'institutions' => (new InstitutionRepository())->all(),
        ]);
    }

    public function store(): string
    {
        if ($response = $this->ensureCsrf()) {
            return $response;
        }

        if (!Security::rateLimit('report:' . ($_SERVER['REMOTE_ADDR'] ?? 'local'), 8, 60)) {
            return $this->json(['ok' => false, 'message' => 'Твърде много заявки. Опитайте след минута.'], 429);
        }

        $input = $this->input();
        $institutionRepository = new InstitutionRepository();
        $institution = $institutionRepository->recommendedFor(
            (string) ($input['category'] ?? ''),
            (string) ($input['municipality'] ?? '')
        );

        $payload = [
            'category' => Security::cleanText((string) ($input['category'] ?? 'Друго'), 120),
            'title' => Security::cleanText((string) ($input['problem'] ?? $input['category'] ?? 'Нов сигнал'), 160),
            'description' => Security::cleanText((string) ($input['description'] ?? ''), 4000),
            'address' => Security::cleanText((string) ($input['address'] ?? ''), 300),
            'municipality' => Security::cleanText((string) ($input['municipality'] ?? 'Пловдив'), 120),
            'institution_id' => $institution['id'] ?? null,
            'institution' => $institution['name'] ?? 'Компетентна институция',
        ];

        $report = (new ReportRepository())->create($payload);
        $document = (new DocumentGenerator())->generate('signal', $payload);
        $delivery = null;

        if (($input['send_to_institution'] ?? '1') === '1') {
            $delivery = (new InstitutionDeliveryService())->sendReport(
                $report,
                $institution,
                $document,
                (string) ($input['delivery_channel'] ?? 'email')
            );
        }

        return $this->json([
            'ok' => true,
            'message' => $delivery ? 'Сигналът е подготвен и изпратен за доставка.' : 'Сигналът е подготвен.',
            'report' => $report,
            'document' => $document,
            'delivery' => $delivery,
        ]);
    }
}
