<?php

declare(strict_types=1);

namespace KupShop\PreordersBundle\Admin\Actions;

use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\PreordersBundle\Entity\UserPreorder;

class CreateOrderAction extends UserPreorderAction
{
    private ?bool $enabled = null;

    public function execute(&$data, array $config, string $type): ActionResult
    {
        return new ActionResult(true);
    }

    public function getLaunchHandler(): string
    {
        return "nw('preordersCreateOrder', '', 'ID={$this->getId()}&acn=edit',);";
    }

    public function hasDialog(): bool
    {
        return false;
    }

    protected function checkEnabled(): bool
    {
        $script = str_replace('.php', '', (string) getVal('s', default: ''));
        if (!in_array($script, $this->getTypes())) {
            return false;
        }

        $ids = explode('-', $this->getId() ?? '');
        if (count($ids) < 2) {
            return false;
        }

        if ($this->enabled === null) {
            [$userId, $dateId] = $ids;

            $preorder = new UserPreorder((int) $userId, (int) $dateId);
            $date = $preorder->getPreorderDate();

            $this->enabled = \DateTimeImmutable::createFromFormat('Y-m-d', $date['date_end'])
                <= (new \DateTimeImmutable())->sub(\DateInterval::createFromDateString('1 day'));
        }

        return $this->enabled;
    }
}
