<?php

namespace KupShop\ComponentsBundle\Twig\Components\EditableContent;

use KupShop\ComponentsBundle\Attributes\Blocek;
use KupShop\ComponentsBundle\Attributes\BlocekAttribute;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\Components\ContactForm\Types\FormType;
use KupShop\ComponentsBundle\Twig\Components\ContactForm\Utils\Entity;
use KupShop\ComponentsBundle\Twig\Components\Utils\EditableContent\BlocekDataTrait;
use KupShop\ComponentsBundle\Twig\Components\Utils\Forms\EmailForm;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;

#[AsLiveComponent(template: '@Components/components/EditableContent/ContactForm/ContactForm.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
#[Blocek(title: 'Kontaktní formulář')]
class ContactForm extends EmailForm
{
    use BlocekDataTrait;
    use ComponentWithFormTrait;

    public string $subject = 'Kontaktní formulář';
    public string $btnType = 'btn-secondary';

    #[LiveProp]
    #[BlocekAttribute(title: 'Zobrazit Newsletter')]
    public bool $showNewsLetter = false;

    #[LiveProp]
    #[BlocekAttribute(title: 'Příjemce (Když není vyplněn, vezme se adresa shopu)')]
    public ?string $receiver = null;

    #[LiveProp]
    public array $multipleUploadFilenames = [];

    public function __construct(private readonly UserContext $userContext, private readonly UrlFinder $urlFinder)
    {
    }

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(FormType::class, null, [
            'action' => 'javascript:void(0);',
        ]);
    }

    #[LiveAction]
    public function handleForm(Request $request): void
    {
        $this->submitForm();

        /** @var Entity $entity */
        $entity = $this->getForm()->getData();

        try {
            $loggedUser = $this->userContext->getActive();

            $userEmail = $loggedUser->email ?? $entity->email;
            addUserEmail($userEmail, [], ['get_news' => !empty($entity->news) ? 'Y' : 'N']);

            $attachments = [];
            foreach ($request->files->get('form')['attachment'] ?? [] as $file) {
                if ($filename = $this->upload($file)) {
                    $attachments[$filename] = [
                        'originalName' => $file->getClientOriginalName(),
                        'path' => $this->urlFinder->shopUrlAbsolute($this->getTargetDirectory().$filename),
                    ];
                }
            }

            $this->sendEmail(ContactEmail::getType(), function (ContactEmail $emailService) use ($entity, $userEmail, $attachments) {
                $emailService->setSender($userEmail);
                if ($this->receiver != null) {
                    $emailService->setReceiver($this->receiver);
                }
                $emailService->setSubject($this->subject);
                $emailService->setData([
                    'DATA_SUBJECT' => $this->subject,
                    'DATA_MESSAGE' => $entity->message,
                    'DATA_ATTACHMENTS' => $attachments,
                    'DATA_NAME' => $loggedUser->name ?? $entity->name ?? '',
                    'DATA_SURNAME' => $loggedUser->surname ?? $entity->surname ?? '',
                    'DATA_EMAIL' => $userEmail,
                    'DATA_PHONE' => $loggedUser->phone ?? $entity->phone ?? '',
                ]);

                return $emailService;
            });

            addUserMessage($this->translator->trans('lowestPriceGuarantee.add.success', [], 'products'), 'success');
        } catch (\Exception $e) {
            addUserMessage($this->translator->trans('lowestPriceGuarantee.add.error', [], 'products'), 'error');
        }

        $this->resetForm();
    }

    public function getIsUser(): bool
    {
        return !empty($this->userContext->getActiveId());
    }

    public function getPrivacyPolicyUrl(): string
    {
        return $this->processUrl(['s' => 'page', 'label' => 'privacy_policy']);
    }

    public function showSubscribeCheckBox(): bool
    {
        return ($this->userContext->getActive()->get_news ?? 'N') == 'N' and $this->showNewsLetter;
    }

    private function processUrl($params): string
    {
        return htmlspecialchars(createScriptURL($params), ENT_QUOTES);
    }
}
