<?php

namespace FiloBlu\Storelocator\Block\Adminhtml\Stores\Edit\Tab;

use FiloBlu\Storelocator\Block\Adminhtml\Renderer\Region;
use FiloBlu\Storelocator\Block\Adminhtml\Stores\Form\Renderer\Fieldset\GoogleMap;
use FiloBlu\Storelocator\Block\Adminhtml\Stores\Helper\Editor;
use FiloBlu\Storelocator\Block\Adminhtml\Stores\Helper\Image;
use FiloBlu\Storelocator\Model\Google\Api;
use FiloBlu\Storelocator\Model\Stores;
use Magento\Backend\Block\Store\Switcher\Form\Renderer\Fieldset\Element;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Element\Dependence;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Directory\Model\Config\Source\Country;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;

/**
 *
 */
class Store extends Generic implements TabInterface
{

    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $systemStore;
    /**
     * @var \Magento\Directory\Model\Config\Source\Country
     */
    protected $countryFactory;

    /**
     * @var \FiloBlu\Storelocator\Model\Google\Api
     */
    protected $googleApi;

    /**
     * @var ScopeConfigInterface
     */
    private $config;

    /**
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param \Magento\Store\Model\System\Store $systemStore
     * @param Country $countryFactory
     * @param Api $googleApi
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        FormFactory $formFactory,
        \Magento\Store\Model\System\Store $systemStore,
        Country $countryFactory,
        Api $googleApi,
        array $data = []
    ) {
        $this->systemStore = $systemStore;
        $this->countryFactory = $countryFactory;
        $this->googleApi = $googleApi;
        $this->config = $context->getScopeConfig();
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare title for tab
     *
     * @return string
     */
    public function getTabTitle()
    {
        return $this->getTabLabel();
    }

    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel()
    {
        return __('Store');
    }

    /**
     * Can show tab in tabs
     *
     * @return bool
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * Tab is hidden
     *
     * @return bool
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * Init form
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('storelocator_store_form');
        $this->setTitle(__('Store Information'));
    }

    /**
     * Prepare form
     *
     * @return $this
     * @throws LocalizedException
     */
    protected function _prepareForm()
    {
        /** @var Stores $model */
        $model = $this->_coreRegistry->registry('storelocator_store');

        $form = $this->_formFactory->create();

        $form->setHtmlIdPrefix('storelocator_store_');

        // ## General Information ##
        $fieldset = $form->addFieldset(
            'base_fieldset', ['legend' => __('General Information'), 'class' => 'fieldset-wide']
        );

        $fieldset->addType('image', Image::class);

        if ($model->getStoreId()) {
            $fieldset->addField('store_id', 'hidden', ['name' => 'store_id']);
        }

        $fieldset->addField(
            'title', 'text', [
                'name'     => 'title',
                'label'    => __('Title'),
                'title'    => __('Title'),
                'required' => true
            ]
        );

        $fieldset->addField(
            'store_code', 'text', [
                'name'     => 'store_code',
                'label'    => __('Store Code'),
                'title'    => __('Store Code'),
                'required' => false
            ]
        );

        $fieldset->addField(
            'store_filename_prefix', 'text', [
                'name'  => 'store_filename_prefix',
                'label' => __('Store image file prefix'),
                'title' => __('Store image file prefix')
            ]
        );

        $fieldset->addField(
            'enabled', 'select', [
                'label'    => __('Status'),
                'title'    => __('Status'),
                'name'     => 'enabled',
                'required' => true,
                'options'  => ['1' => __('Enabled'), '0' => __('Disabled')]
            ]
        );

       $isEnabledForPickupInStore = $fieldset->addField(
            'is_enabled_for_pickup_in_store', 'select', [
                'label'    => __('Enabled For Pickup In Store'),
                'title'    => __('Enabled For Pickup In Store'),
                'name'     => 'is_enabled_for_pickup_in_store',
                'required' => true,
                'options'  => ['1' => __('Enabled'), '0' => __('Disabled')]
            ]
        );

       $emailToStoreDisabled = $fieldset->addField(
          'email_to_store_disabled'  ,'select', [
                'label'    => __('Disable Email To Store'),
                'title'    => __('Disable Email To Store'),
                'name'     => 'email_to_store_disabled',
                'required' => true,
                'options'  => ['1' => __('Yes'), '0' => __('No')]
            ]
        );

        $fieldset->addField(
            'is_enabled_for_return_in_store', 'select', [
                'label'    => __('Enabled For Return In Store'),
                'title'    => __('Enabled For Return In Store'),
                'name'     => 'is_enabled_for_return_in_store',
                'required' => true,
                'options'  => ['1' => __('Enabled'), '0' => __('Disabled')]
            ]
        );

        $fieldset->addField(
            'is_enabled_shop_details', 'select', [
                'label'    => __('Enabled Shop details'),
                'title'    => __('Enabled Shop details'),
                'name'     => 'is_enabled_shop_details',
                'required' => true,
                'options'  => ['1' => __('Enabled'), '0' => __('Disabled')]
            ]
        );

        if (!$model->getId()) {
            $model->setData('enabled', '1');
        }

        if (!$this->_storeManager->isSingleStoreMode()) {
            $field = $fieldset->addField(
                'store_ids', 'multiselect', [
                    'name'     => 'store_ids[]',
                    'label'    => __('Assign to Store Views'),
                    'title'    => __('Assign to Store Views'),
                    'required' => true,
                    'values'   => $this->systemStore->getStoreValuesForForm(false, true)
                ]
            );
            $renderer = $this->getLayout()->createBlock(Element::class);
            $field->setRenderer($renderer);
        }

        $fieldset->addField(
            'image', 'image', [
                'name'  => 'image',
                'label' => __('Image'),
                'title' => __('Image')
            ]
        );

        $fieldset->addField(
            'marker_image', 'image', [
                'name'  => 'marker_image',
                'label' => __('Marker Image'),
                'title' => __('Marker Image')
            ]
        );

        // ## Address ##
        $fieldset = $form->addFieldset(
            'address_fieldset', ['legend' => __('Address'), 'class' => 'fieldset-wide']
        );

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

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

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

        // $model->setCountryId($model->getCountry());

        $optionsc = $this->countryFactory->toOptionArray();
        $fieldset->addField(
            'country', 'select', [
                'name'   => 'country',
                'label'  => __('Country'),
                'title'  => __('Country'),
                // 'onchange' => 'getstate(this)',
                'values' => $optionsc,
            ]
        );

        $regionField = $fieldset->addField(
            'region',
            'text',
            ['name' => 'region', 'label' => __('State/Province'), 'required' => true]
        );

        $regionUpdaterBlock = $this->getLayout()->createBlock(Region::class);
        $regionUpdaterBlock->setRegionIdValue($model->getRegionId());
        $regionUpdaterBlock->setRegionValue($model->getRegion());
        $regionField->setRenderer($regionUpdaterBlock);

        $fieldset->addField(
            'additional_text', Editor::class, [
                'name'  => 'additional_text',
                'label' => __('Additional Text'),
                'title' => __('Additional Text'),
            ]
        );
        $fieldset->addField(
            'additional_text_2', Editor::class, [
                'name'  => 'additional_text_2',
                'label' => __('Additional Text 2'),
                'title' => __('Additional Text 2'),
            ]
        );

        $fieldset->addField(
            'store_external_iframe_appointment', Editor::class, [
                'name'  => 'store_external_iframe_appointment',
                'label' => __('External Iframe Appointment'),
                'title' => __('External Iframe Appointment'),
            ]
        );

        // ## Contacts ##
        $fieldset = $form->addFieldset(
            'contacts_fieldset', ['legend' => __('Contacts'), 'class' => 'fieldset-wide']
        );

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

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

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

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

        $fieldset->addField(
            'website_url', 'text', [
                'name'  => 'website_url',
                'label' => __('Website Url'),
                'title' => __('Website Url')
            ]
        );

        // ## Geolocation ##
        $fieldset = $form->addFieldset(
            'geolocation_fieldset', ['legend' => __('Geolocation data'), 'class' => 'fieldset-wide']
        );

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

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

        $fieldGMap = $fieldset->addField(
            'google_map', 'label', [
                'latitude'  => $model->getLatitude(),
                'longitude' => $model->getLongitude(),
                'required'  => false,
            ]
        );
        $renderer = $this->getLayout()->createBlock(
            GoogleMap::class
        );
        $fieldGMap->setRenderer($renderer);


        // ## Google My Business ##
        $gmb_enabled = $this->config->getValue('filoblu_storelocator_section/google_my_business/gmb_enabled');

        if ($gmb_enabled) {
            $fieldset = $form->addFieldset(
                'gmb_fieldset', ['legend' => __('Google My Business'), 'class' => 'fieldset-wide']
            );

            $language = 'it-IT';
            $country = 'IT';

            if ($model->getId()) {
                if ($model->getGmbLanguageCode()) {
                    $language = $model->getGmbLanguageCode();
                }
                if ($model->getCountry()) {
                    $country = $model->getCountry();
                }
            }


            $fieldset->addField(
                'gmb_cat', 'select', [
                    'name'     => 'gmb_cat',
                    'label'    => __('Category'),
                    'title'    => __('Category'),
                    'required' => true,
                    'options'  => $this->googleApi->getCategoryList($country, $language)
                ]
            );

            $fieldset->addField(
                'gmb_language_code', 'text', [
                    'name'     => 'gmb_language_code',
                    'label'    => __('Language'),
                    'title'    => __('Language'),
                    'required' => true,
                ]
            );
        }

        $this->setChild(
            'form_after',
            $this->getLayout()->createBlock(Dependence::class)
                 ->addFieldMap($isEnabledForPickupInStore->getHtmlId(), $isEnabledForPickupInStore->getName())
                ->addFieldMap($emailToStoreDisabled->getHtmlId(), $emailToStoreDisabled->getName())
                ->addFieldDependence($emailToStoreDisabled->getName(), $isEnabledForPickupInStore->getName(), '1')
        );

        $form->setValues($model->getData());
//        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }

}
