<?php

namespace Autogedal\Retragere\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Customer\Model\Session as CustomerSession;

class RetragereForm extends Template
{
    private const DATA_PERSISTOR_KEY = 'autogedal_retragere';

    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var CustomerSession
     */
    private $customerSession;

    public function __construct(
        Context $context,
        DataPersistorInterface $dataPersistor,
        CustomerSession $customerSession,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->dataPersistor = $dataPersistor;
        $this->customerSession = $customerSession;
    }

    /**
     * Get previously submitted form data (after a validation error) or
     * prefill firstname/lastname/email from the logged in customer.
     *
     * @return array
     */
    public function getFormData(): array
    {
        $data = $this->dataPersistor->get(self::DATA_PERSISTOR_KEY);
        $this->dataPersistor->clear(self::DATA_PERSISTOR_KEY);

        if (is_array($data)) {
            return $data;
        }

        if ($this->customerSession->isLoggedIn()) {
            $customer = $this->customerSession->getCustomer();
            return [
                'firstname' => $customer->getFirstname(),
                'lastname' => $customer->getLastname(),
                'email' => $customer->getEmail(),
            ];
        }

        return [];
    }

    /**
     * @return string
     */
    public function getPostUrl(): string
    {
        return $this->getUrl('retragere/index/post');
    }
}
