<?php

namespace FiloBlu\Rma\Block\Adminhtml\Rma\NewRma\Tab;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Rma\Block\Adminhtml\Rma\Edit\Tab\General;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Directory\Model\Config\Source\Country;
use Magento\Directory\Helper\Data as DirectoryHelper;
use Magento\Directory\Model\ResourceModel\Region\CollectionFactory as RegionCollectionFactory;


class EasyReturn  extends General
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var Registry
     */
    protected $registry;
    /**
     * @var FormFactory
     */
    protected $formFactory;
    /**
     * @var Country
     */
    protected $countrySource;
    /**
     * @var DirectoryHelper
     */
    protected $directoryHelper;
    /**
     * @var RegionCollectionFactory
     */
    private $regionCollectionFactory;
    /**
     * @var Json
     */
    private $serializer;

    /**
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param Country $countrySource
     * @param DirectoryHelper $directoryHelper
     * @param RegionCollectionFactory $regionCollectionFactory
     * @param Json $serializer
     */
    public function __construct(
        Context                 $context,
        Registry                $registry,
        FormFactory             $formFactory,
        Country                 $countrySource,
        DirectoryHelper         $directoryHelper,
        RegionCollectionFactory $regionCollectionFactory,
        Json                    $serializer,
        array                   $data = []
    )
    {
        parent::__construct($context, $registry, $formFactory, $data);
        $this->registry = $registry;
        $this->formFactory = $formFactory;
        $this->countrySource = $countrySource;
        $this->directoryHelper = $directoryHelper;
        $this->regionCollectionFactory = $regionCollectionFactory;
        $this->serializer = $serializer;
    }


    public function getTabLabel()
    {
        return __('Easy Return');
    }

    public function getTabTitle()
    {
        return $this->getTabLabel();
    }

    public function isChecked()
    {
        return (bool) $this->getRequest()->getParam('custom_checkbox', false);
    }

    public function getOrder()
    {
        return $this->_coreRegistry->registry('current_order');
    }

    protected function _construct()
    {
        $this->setId('filoblu_easyreturn_form');
        $this->setTitle(__('Easy Return'));
        parent::_construct(); // TODO: Change the autogenerated stub
    }

    protected function _prepareForm()
    {
        $form = $this->formFactory->create();
        $form->setHtmlIdPrefix('filoblu_');
        $order = $this->getOrder();
        $address = $order->getShippingAddress();

        if (empty($address)) {
            $address = $order->getBillingAddress();
        }

        if (empty($address)) {
            return false;
        }

        // === FIELDSET EASY RETURN FLAG ===
        $flagFieldset = $form->addFieldset(
            'filoblu_easy_return_fieldset',
            [
                'legend' => __('Easy Return'),
                'class'  => 'admin__fieldset-wide'
            ]
        );

        $flagFieldset->addField('easy_return', 'checkbox', [
            'name'  => 'easy_return',
            'label' => __('Is Easy Return'),
            'title' => __('Is Easy Return'),
            'value' => 1,
            'checked' => true
        ]);

        // === FIELDSET SHIPPING ADDRESS ===
        $fieldset = $form->addFieldset('filoblu_easy_return_pickup_address_fieldset', [
            'legend' => __('Pickup Address'),
            'class'  => 'filoblu-easy-return-pickup-address',
        ]);

        $fieldset->setData('html_id', 'address_fieldset');

        $fieldset->addField('firstname', 'text', [
            'name'  => 'firstname',
            'label' => __('First Name'),
            'title' => __('First Name'),
        ]);

        $fieldset->addField('lastname', 'text', [
            'name'  => 'lastname',
            'label' => __('Last Name'),
            'title' => __('Last Name'),
        ]);

        $fieldset->addField('street', 'text', [
            'name'  => 'street[0]',
            'label' => __('Street Address'),
            'title' => __('Street Address'),
             'class' => 'required-entry',
        ]);

        $fieldset->addField('street_2', 'text', [
            'name'  => 'street[1]',
            'label' => __('Street Line 2'),
            'title' => __('Street Line 2'),
        ]);

        $fieldset->addField('postcode', 'text', [
            'name'  => 'postcode',
            'label' => __('Postcode'),
            'title' => __('Postcode'),
        ]);

        $fieldset->addField('city', 'text', [
            'name'  => 'city',
            'label' => __('City'),
            'title' => __('City'),
        ]);


        $fieldset->addField('telephone', 'text', [
            'name'  => 'telephone',
            'label' => __('Phone Number'),
            'title' => __('Phone Number'),
        ]);

        // === COUNTRY SELECT ===
        $fieldset->addField('country_id', 'select', [
            'name'   => 'country_id',
            'label'  => __('Country'),
            'values' => $this->countrySource->toOptionArray(),
            'class' => 'required-entry',
            'disabled' => true
        ]);

        // === REGION SELECT ===
        $regions = $this->regionCollectionFactory->create()
            ->addFieldToFilter('country_id', $address->getCountryId()) // opzionale default
            ->setOrder('default_name', 'ASC');

        $regionOptions = [['value' => '', 'label' => __('-- Please Select --')]];
        foreach ($regions as $region) {
            $regionOptions[] = [
                'value' => $region->getId(),
                'label' => $region->getName(),
            ];
        }

        if (count($regionOptions) > 1) {
            $fieldset->addField('region_id', 'select', [
                'name'     => 'region_id',
                'label'    => __('State/Region'),
                'title'    => __('State/Region'),
                'values'   => $regionOptions,
                'required' => true,
                'class'    => 'required-entry',
            ]);
            $fieldset->addField('region', 'hidden', [
                'name'  => 'region'
            ]);
        } else {
            $fieldset->addField('region_id', 'hidden', [
                'name'  => 'region_id',
                'value' => NULL
            ]);
        }

        $form->setValues($address->getData());

        // === Inject JS per il region updater ===
        $this->setForm($form);
        $this->setChild(
            'form_after',
            $this->getLayout()->createBlock(\Magento\Directory\Block\Data::class)
        );

        return $this;
    }
}
