<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Components\Settings;

use Ferienpass\CoreBundle\Entity\PageConfig;
use Ferienpass\CoreBundle\Settings\MailConfigManager;
use Ferienpass\CoreBundle\Settings\PageConfigManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\ValidatableComponentTrait;
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;

#[AsLiveComponent(name: 'Admin:Settings:PageSettings', template: '@FerienpassAdmin/components/Settings/PageSettings.html.twig', route: 'live_component_admin')]
final class PageSettings extends AbstractController
{
    use DefaultActionTrait;
    use ValidatableComponentTrait;

    #[LiveProp(writable: ['pageTitle', 'adminEmail', 'adminEmailName', 'replyToEmail', 'replyToName'])]
    #[Assert\Valid]
    public PageConfig $config;

    #[LiveProp]
    public ?string $edit = null;

    public ?string $confirmation = null;

    public function __construct(private readonly MailConfigManager $mailConfigManager)
    {
    }

    #[LiveAction]
    public function activateEditing(#[LiveArg('field')] string $field): void
    {
        $this->edit = $field;
    }

    #[LiveAction]
    public function cancel(): void
    {
        $this->edit = null;
    }

    #[LiveAction]
    public function save(PageConfigManager $pageConfigManager): void
    {
        $this->validate();

        $pageConfigManager->savePageConfig($this->config);

        $this->edit = null;
        $this->confirmation = 'Einstellungen gespeichert.';
    }

    public function getMailConfigManager(): MailConfigManager
    {
        return $this->mailConfigManager;
    }

    #[ExposeInTemplate]
    public function isAdminEmailDisabled(): bool
    {
        return $this->mailConfigManager->isAdminEmailFromEnv();
    }
}
