<?php
declare(strict_types=1);

namespace App\Modules\Settings;

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

final class ReceiptConfigController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly ReceiptConfigRepository $repository
    ) {
    }

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

        $editConfig = null;
        $editId = (int) $request->input('edit', '0');
        if ($editId > 0) {
            $editConfig = $this->repository->findById($editId);
        }

        $html = $this->template->render('settings/accounting', [
            'title' => $t->get('settings.accounting.title'),
            'activeMenu' => 'settings',
            'activeSettings' => 'accounting',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'configs' => $configs,
            'editConfig' => $editConfig,
            'successMessage' => Flash::get('settings.accounting.success', ''),
            'errorMessage' => Flash::get('settings.accounting.error', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

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

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

        if ($name === '') {
            Flash::set('settings.accounting.error', 'Nazwa konfiguracji jest wymagana');
            return Response::redirect('/settings/accounting');
        }

        if ($numberFormat === '' || strpos($numberFormat, '%N') === false) {
            Flash::set('settings.accounting.error', 'Format numeracji jest wymagany i musi zawierac %N');
            return Response::redirect('/settings/accounting');
        }

        try {
            $this->repository->save([
                'id' => $request->input('id', ''),
                'name' => $name,
                'is_active' => $request->input('is_active', null),
                'number_format' => $numberFormat,
                'numbering_type' => $request->input('numbering_type', 'monthly'),
                'is_named' => $request->input('is_named', null),
                'sale_date_source' => $request->input('sale_date_source', 'issue_date'),
                'order_reference' => $request->input('order_reference', 'none'),
            ]);

            Flash::set('settings.accounting.success', $this->translator->get('settings.accounting.flash.saved'));
        } catch (Throwable) {
            Flash::set('settings.accounting.error', $this->translator->get('settings.accounting.flash.save_failed'));
        }

        return Response::redirect('/settings/accounting');
    }

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

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

        try {
            $this->repository->toggleStatus($id);
            Flash::set('settings.accounting.success', $this->translator->get('settings.accounting.flash.toggled'));
        } catch (Throwable) {
            Flash::set('settings.accounting.error', 'Blad zmiany statusu');
        }

        return Response::redirect('/settings/accounting');
    }

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

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

        try {
            $this->repository->delete($id);
            Flash::set('settings.accounting.success', $this->translator->get('settings.accounting.flash.deleted'));
        } catch (Throwable) {
            Flash::set('settings.accounting.error', $this->translator->get('settings.accounting.flash.delete_failed'));
        }

        return Response::redirect('/settings/accounting');
    }
}
