<?php

namespace KupShop\ContentBundle\View;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use Query\Operator;

class OrderSuccessView extends OrderView
{
    protected string $smartyFallback = 'ordering';
    protected $template = 'ordering.success.tpl';

    public function getBodyVariables()
    {
        if (is_null($this->error)) {
            $this->error = 1;
        }

        $vars = parent::getBodyVariables();
        $vars['url'] = createScriptURL([
            'URL' => 'launch.php',
            's' => 'orderView',
            'IDo' => $this->IDo,
            'cf' => getVal('cf'),
        ]);
        $vars['orderSent'] = true;
        $vars['stepName'] = 'success';

        if (!Contexts::get(UserContext::class)->getActive()) {
            // When the user is not logged, but the email is registered
            $vars['emailRegistered'] = $this->isEmailRegistered();
        }

        return $vars;
    }

    protected function isEmailRegistered(): bool
    {
        $order = $this->getOrder();

        return sqlQueryBuilder()->select('1')->from('users')
            ->where(Operator::equalsNullable(['email' => $order->invoice_email ?? null]))
            ->andWhere('figure = "Y"')
            ->execute()->fetchOne();
    }

    protected function getSmartyFallback(): ?string
    {
        if (!isset($this->smartyFallback)) {
            return 'Případně si povol fallback přes $smartyFallback v '.get_class($this);
        }

        return "smarty_fallback/{$this->smartyFallback}.html.twig";
    }

    public function getCorrectUrl(): ?string
    {
        return null;
    }
}
