<?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\PageConfigManager;
use Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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;

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

    #[LiveProp(writable: [
        'friendsBooking',
        'preferredPostalCodes',
        'requirePostalAddress',
        'eraseDataPeriod',
        'attendanceRemindPeriod',
        'paymentAllowSelect',
        'ageTolerance',
        'withdrawGracePeriod',
        'noWithdrawAfterGracePeriod',
        'noWithdrawAfterApplicationDeadline',
        'receiptNumberPrefix',
        'remindAttendance',
        'hostDataRetentionPeriod',
        'imprintName',
        'imprintDepartment',
        'imprintStreet',
        'imprintPostalCode',
        'imprintCity',
    ])]
    #[Assert\Valid]
    public PageConfig $config;

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

    public ?string $confirmation = null;

    public function __construct(
        private readonly SystemSettingsManager $systemSettingsManager,
        private readonly PageConfigManager $pageConfigManager
    ) {
    }

    public function getSystemSettingsManager(): SystemSettingsManager
    {
        return $this->systemSettingsManager;
    }

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

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

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

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

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