<?php
namespace Dreamfox\DeliveryDate\Premium;

use Dreamfox\DeliveryDate\Abstracts\AbstractCheckoutFieldManager;
use Dreamfox\DeliveryDate\Helpers\DeliveryDateHelper;
use Dreamfox\DeliveryDate\Premium\Facades\SystemFacade;

class CheckoutFieldManager extends AbstractCheckoutFieldManager
{

  public function process()
  {
    $system = SystemFacade::getInstance();
    $categorySetting = $system->loadCategorySettings();
    $appliedCategories = array();
    foreach ( $categorySetting->getCategories() as $item ) {
      if ( ! empty( $item->selected ) ) {
        $appliedCategories[] = $item->id;
      }
    }
    if (!$this->_isAvailable($appliedCategories)) {
      return;
    }
    $commonSetting = $system->loadCommonSettings();
    $datesToDeliver = DeliveryDateHelper::resolveCategoryDeliveryDays(
      $commonSetting->getDeliveryDays(),
      $categorySetting->getCategories()
    );
    $holidaySetting = $system->loadHolidaySettings();
    $minDateOptions = array(
      'countOnlyWorkingDays' => (bool) $holidaySetting->getCountOnlyWorkingDays(),
      'disabledWeekdays'     => DeliveryDateHelper::getDisabledWeekdayIds( (array) $holidaySetting->getDisableDays() ),
      'holidayDatesYmd'      => DeliveryDateHelper::expandHolidayRanges( (array) $holidaySetting->getHolidays() ),
    );
    $minDeliveryDate = $this->_getMinDeliveryDate( $datesToDeliver, $minDateOptions );
    $otherSetting = $system->loadOtherSettings();
    $label = $otherSetting->getLabelOnCheckout();
    $required = $otherSetting->getRequired();
    $default = $otherSetting->getShowEmptyOnCheckout() ? '' : $minDeliveryDate;
		$this->_fields[DREAMFOX_WDD_FIELD_NAME] = array(
			DREAMFOX_WDD_FIELD_NAME => array(
				'type' => 'text',
				'class' => array('dreamfox-delivery-date form-row-wide'),
				'label' => $label,
				'default' => $default,
				'required' => $required,
			)
		);
  }
}
