<?php

declare(strict_types=1);

namespace App\Modules\Settings;

use App\Modules\Auth\AuthService;
use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;
use App\Core\I18n\Translator;
use App\Modules\Sms\SmsTemplateRepository;
use Throwable;

final class SmsTemplateController
{
    private const VARIABLE_GROUPS = [
        'zamowienie' => [
            'label' => 'Zamowienie',
            'vars' => [
                'numer' => 'Numer wewnetrzny (OP...)',
                'numer_zewnetrzny' => 'Numer z platformy',
                'zrodlo' => 'Zrodlo (Allegro/shopPRO/...)',
                'kwota' => 'Kwota brutto',
                'waluta' => 'Waluta (PLN/EUR/...)',
                'data' => 'Data zamowienia',
            ],
        ],
        'kupujacy' => [
            'label' => 'Kupujacy',
            'vars' => [
                'imie_nazwisko' => 'Imie i nazwisko',
                'email' => 'Adres e-mail',
                'telefon' => 'Telefon',
                'login' => 'Login platformy',
            ],
        ],
        'adres' => [
            'label' => 'Adres dostawy',
            'vars' => [
                'ulica' => 'Ulica z numerem',
                'miasto' => 'Miasto',
                'kod_pocztowy' => 'Kod pocztowy',
                'kraj' => 'Kraj',
            ],
        ],
        'firma' => [
            'label' => 'Firma',
            'vars' => [
                'nazwa' => 'Nazwa firmy',
                'nip' => 'NIP',
            ],
        ],
        'przesylka' => [
            'label' => 'Przesylka',
            'vars' => [
                'numer' => 'Numer przesylki (tracking)',
                'link_sledzenia' => 'Link sledzenia zalezny od kuriera',
            ],
        ],
    ];

    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly SmsTemplateRepository $repository
    ) {
    }

    public function index(Request $request): Response
    {
        $templates = $this->repository->listAll();

        $html = $this->template->render('settings/sms-templates', [
            'title' => 'Szablony SMS',
            'activeMenu' => 'settings',
            'activeSettings' => 'sms-templates',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'templates' => $templates,
            'successMessage' => Flash::get('settings.sms_templates.success', ''),
            'errorMessage' => Flash::get('settings.sms_templates.error', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function create(Request $request): Response
    {
        return $this->renderForm(null);
    }

    public function edit(Request $request): Response
    {
        $id = (int) $request->input('id', '0');
        $template = $id > 0 ? $this->repository->findById($id) : null;

        if ($template === null) {
            Flash::set('settings.sms_templates.error', 'Nie znaleziono szablonu');
            return Response::redirect('/settings/sms-templates');
        }

        return $this->renderForm($template);
    }

    public function save(Request $request): Response
    {
        $templateId = (int) $request->input('id', '0');
        $formPath = $this->buildFormPath($templateId > 0 ? $templateId : null);

        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings.sms_templates.error', 'Nieprawidlowy token CSRF');
            return Response::redirect($formPath);
        }

        $name = trim((string) $request->input('name', ''));
        $body = (string) $request->input('body', '');

        if ($name === '' || trim($body) === '') {
            Flash::set('settings.sms_templates.error', 'Nazwa i tresc sa wymagane');
            return Response::redirect($formPath);
        }

        try {
            $this->repository->save([
                'id' => $request->input('id', ''),
                'name' => $name,
                'body' => $body,
                'is_active' => $request->input('is_active', null),
            ]);

            Flash::set('settings.sms_templates.success', 'Szablon SMS zapisany');
        } catch (Throwable $exception) {
            Flash::set('settings.sms_templates.error', 'Blad zapisu szablonu: ' . $exception->getMessage());
            return Response::redirect($formPath);
        }

        return Response::redirect('/settings/sms-templates');
    }

    public function delete(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings.sms_templates.error', 'Nieprawidlowy token CSRF');
            return Response::redirect('/settings/sms-templates');
        }

        $id = (int) $request->input('id', '0');
        if ($id <= 0) {
            Flash::set('settings.sms_templates.error', 'Nieprawidlowy identyfikator szablonu');
            return Response::redirect('/settings/sms-templates');
        }

        try {
            $this->repository->delete($id);
            Flash::set('settings.sms_templates.success', 'Szablon SMS usuniety');
        } catch (Throwable) {
            Flash::set('settings.sms_templates.error', 'Blad usuwania szablonu');
        }

        return Response::redirect('/settings/sms-templates');
    }

    public function toggleStatus(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            return Response::json(['success' => false, 'message' => 'Nieprawidlowy token CSRF'], 403);
        }

        $id = (int) $request->input('id', '0');
        if ($id <= 0) {
            return Response::json(['success' => false, 'message' => 'Nieprawidlowy identyfikator'], 400);
        }

        try {
            $this->repository->toggleStatus($id);
            return Response::json(['success' => true]);
        } catch (Throwable) {
            return Response::json(['success' => false, 'message' => 'Blad zmiany statusu'], 500);
        }
    }

    public function getVariables(Request $request): Response
    {
        return Response::json([
            'success' => true,
            'groups' => self::VARIABLE_GROUPS,
        ]);
    }

    private function renderForm(?array $template): Response
    {
        $html = $this->template->render('settings/sms-templates-form', [
            'title' => $template !== null ? 'Edytuj szablon SMS' : 'Nowy szablon SMS',
            'activeMenu' => 'settings',
            'activeSettings' => 'sms-templates',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'template' => $template,
            'variableGroups' => self::VARIABLE_GROUPS,
            'successMessage' => Flash::get('settings.sms_templates.success', ''),
            'errorMessage' => Flash::get('settings.sms_templates.error', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    private function buildFormPath(?int $templateId): string
    {
        if ($templateId !== null && $templateId > 0) {
            return '/settings/sms-templates/edit?id=' . $templateId;
        }

        return '/settings/sms-templates/create';
    }
}
