<?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;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\BookEntry;
use Ferienpass\CoreBundle\Entity\Debtor;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\ValidatableComponentTrait;

#[AsLiveComponent(route: 'live_component_admin')]
#[IsGranted('ROLE_ADMIN')]
class CreateBooking extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;
    use ValidatableComponentTrait;

    #[LiveProp]
    public Debtor $debtor;

    #[LiveProp(writable: true)]
    #[Assert\NotEqualTo(0)]
    public float $bookingValue = 0;
    #[LiveProp(writable: true)]
    #[Assert\NotBlank]
    public string $postingRecord = '';

    public bool $submitted = false;

    #[LiveAction]
    public function submit(EntityManagerInterface $entityManager): void
    {
        $bookingValue = (int) ($this->bookingValue * 100);
        $bookEntry = new BookEntry($bookingValue, $this->debtor, type: 'manual', postingRecord: $this->postingRecord);

        $entityManager->persist($bookEntry);
        $entityManager->flush();

        $this->submitted = true;
        $this->emit('debtor_balance:changed');

        $this->bookingValue = 0;
        $this->postingRecord = '';
    }
}
