<?php

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

use FiloBlu\Storelocator\Model\Stores;
use FiloBlu\Storelocator\Model\WorkingTimesFactory;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;

/**
 *
 */
class WorkingTimes extends Generic implements TabInterface
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $systemStore;
    /**
     * @var \FiloBlu\Storelocator\Model\WorkingTimesFactory
     */
    private $workingTimesFactory;

    /**
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param \Magento\Store\Model\System\Store $systemStore
     * @param \FiloBlu\Storelocator\Model\WorkingTimesFactory $workingTimesFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        FormFactory $formFactory,
        \Magento\Store\Model\System\Store $systemStore,
        WorkingTimesFactory $workingTimesFactory,
        array $data = []
    ) {
        $this->systemStore = $systemStore;
        parent::__construct($context, $registry, $formFactory, $data);
        $this->workingTimesFactory = $workingTimesFactory;
    }

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

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

    /**
     * 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_workingtimes');
    }

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

        $storeId = $model->getStoreId();

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

        $form->setHtmlIdPrefix('storelocator_store_workingtimes_');

        // ## Working Times ##

        for ($wt = 1; $wt <= 7; $wt++) {
            $dayStr = '';

            switch ($wt) {
                case 1:
                    $dayStr = 'monday';
                    break;
                case 2:
                    $dayStr = 'tuesday';
                    break;
                case 3:
                    $dayStr = 'wednesday';
                    break;
                case 4:
                    $dayStr = 'thursday';
                    break;
                case 5:
                    $dayStr = 'friday';
                    break;
                case 6:
                    $dayStr = 'saturday';
                    break;
                case 7:
                    $dayStr = 'sunday';
                    break;

                default:
                    break;
            }

            $fieldset = $form->addFieldset(
                $dayStr . '_fieldset',
                ['legend' => __(ucfirst($dayStr)), 'class' => 'fieldset-wide']
            );

            $fieldset->addField(
                $dayStr . '_morning_time_from',
                'time',
                [
                    'name'        => $dayStr . '_morning_time_from',
                    'label'       => __('Morning From'),
                    'time_format' => 'hh:mm:ss'
                ]
            );

            $fieldset->addField(
                $dayStr . '_morning_time_to',
                'time',
                [
                    'name'        => $dayStr . '_morning_time_to',
                    'label'       => __('Morning To'),
                    'time_format' => 'hh:mm:ss'
                ]
            );

            $fieldset->addField(
                'closed_' . $dayStr . '_morning',
                'select',
                [
                    'label'    => __('Closed Morning'),
                    'title'    => __('Closed Morning'),
                    'name'     => 'closed_' . $dayStr . '_morning',
                    'required' => true,
                    'options'  => [true => __('Yes'), false => __('No')]
                ]
            );


            $fieldset->addField(
                $dayStr . '_afternoon_time_from',
                'time',
                [
                    'name'        => $dayStr . '_afternoon_time_from',
                    'label'       => __('Afternoon From'),
                    'time_format' => 'hh:mm:ss'
                ]
            );

            $fieldset->addField(
                $dayStr . '_afternoon_time_to',
                'time',
                [
                    'name'        => $dayStr . '_afternoon_time_to',
                    'label'       => __('Afternoon To'),
                    'time_format' => 'hh:mm:ss'
                ]
            );

            $fieldset->addField(
                'closed_' . $dayStr . '_afternoon',
                'select',
                [
                    'label'    => __('Closed Afternoon'),
                    'title'    => __('Closed Afternoon'),
                    'name'     => 'closed_' . $dayStr . '_afternoon',
                    'required' => true,
                    'options'  => [true => __('Yes'), false => __('No')]
                ]
            );
        }

        if ($storeId) {
            $objDataForm = [];

            $modelWT = $this->workingTimesFactory->create();

            $workingTimesCollection = $modelWT->loadByStoreId($storeId);

            foreach ($workingTimesCollection as $workingTime) {
                $isClosed = $workingTime['closed'];

                $fromHH = '00';
                $fromMM = '00';
                $fromSS = '00';

                if ($workingTime['from']) {
                    $timeFrom = explode(':', explode(' ', $workingTime['from'])[1]);
                    $fromHH = $timeFrom[0];
                    $fromMM = $timeFrom[1];
                    $fromSS = $timeFrom[2];
                }

                $toHH = '00';
                $toMM = '00';
                $toSS = '00';

                if ($workingTime['to']) {
                    $timeTo = explode(':', explode(' ', $workingTime['to'])[1]);
                    $toHH = $timeTo[0];
                    $toMM = $timeTo[1];
                    $toSS = $timeTo[2];
                }

                $dayStr = '';

                switch ($workingTime->getDay()) {
                    case 1:
                        $dayStr = 'monday';
                        break;
                    case 2:
                        $dayStr = 'tuesday';
                        break;
                    case 3:
                        $dayStr = 'wednesday';
                        break;
                    case 4:
                        $dayStr = 'thursday';
                        break;
                    case 5:
                        $dayStr = 'friday';
                        break;
                    case 6:
                        $dayStr = 'saturday';
                        break;
                    case 7:
                        $dayStr = 'sunday';
                        break;

                    default:
                        break;
                }

                switch ($workingTime->getPeriod()) {
                    case 1:

                        $objDataForm[$dayStr . '_morning_time_from'] = $fromHH . ',' . $fromMM . ',' . $fromSS;
                        $objDataForm[$dayStr . '_morning_time_to'] = $toHH . ',' . $toMM . ',' . $toSS;
                        $objDataForm['closed_' . $dayStr . '_morning'] = $isClosed;

                        break;
                    case 2:

                        $objDataForm[$dayStr . '_afternoon_time_from'] = $fromHH . ',' . $fromMM . ',' . $fromSS;
                        $objDataForm[$dayStr . '_afternoon_time_to'] = $toHH . ',' . $toMM . ',' . $toSS;
                        $objDataForm['closed_' . $dayStr . '_afternoon'] = $isClosed;

                        break;

                    default:
                        break;
                }
            }

            $form->setValues($objDataForm);
        }

        $this->setForm($form);

        return parent::_prepareForm();
    }

    /**
     * @return string
     */
    protected function _formatTime()
    {
        return '';
    }
}
