<?php
namespace Dreamfox\DeliveryDate\Premium\Views;

use Dreamfox\DeliveryDate\Facades\SystemFacade as FreeSystemFacade;
use Dreamfox\DeliveryDate\Helpers\DeliveryDateHelper;
use Dreamfox\DeliveryDate\Interfaces\ApplicationInterface;
use Dreamfox\DeliveryDate\Premium\Facades\SystemFacade;

class DeliveryDateView extends PremiumView
{

  public function __construct(ApplicationInterface $app)
  {
    parent::__construct($app);
    $this->setTemplate('delivery_date');
  }

  public function getDescription()
  {
    $setting = SystemFacade::getInstance()->loadOtherSettings();
    return $setting->getDescriptionOnCheckout();
  }

	public function getMinDate()
	{
		$premium        = SystemFacade::getInstance();
		$deliveryDays   = DeliveryDateHelper::resolveCategoryDeliveryDays(
			$premium->loadCommonSettings()->getDeliveryDays(),
			$premium->loadCategorySettings()->getCategories()
		);
		$holidaySetting = $premium->loadHolidaySettings();

		$timestamp = DeliveryDateHelper::calculateMinTimestamp(
			$deliveryDays,
			(bool) $holidaySetting->getCountOnlyWorkingDays(),
			DeliveryDateHelper::getDisabledWeekdayIds( (array) $holidaySetting->getDisableDays() ),
			DeliveryDateHelper::expandHolidayRanges( (array) $holidaySetting->getHolidays() )
		);

		return DeliveryDateHelper::toJsMinDate( $timestamp );
	}

  public function getHolidays()
  {
    $setting = SystemFacade::getInstance()->loadHolidaySettings();
    return DeliveryDateHelper::expandHolidayRanges( (array) $setting->getHolidays() );
  }

  public function getDisableDays()
  {
    $setting = SystemFacade::getInstance()->loadHolidaySettings();
    return DeliveryDateHelper::getDisabledWeekdayIds( (array) $setting->getDisableDays() );
  }

	/**
	 * Whether timeslots are enabled in settings.
	 */
	public function isTimeslotsEnabled()
	{
		return FreeSystemFacade::getInstance()->loadTimeslotSettings()->getEnabled();
	}

	/**
	 * Data for the JS layer — only the keys the checkout script needs.
	 */
	public function getTimeslotData()
	{
		$settings = FreeSystemFacade::getInstance()->loadTimeslotSettings();
		return array(
			'enabled'   => $settings->getEnabled(),
			'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( 'dreamfox_wdd_frontend' ),
			'i18n'      => array(
				'loading'    => __( 'Loading timeslots…', 'woocommerce-delivery-date' ),
				'selectSlot' => __( '— Select a timeslot —', 'woocommerce-delivery-date' ),
				'noSlots'    => __( 'No timeslots available for this date.', 'woocommerce-delivery-date' ),
				'selectDate' => __( '— Please select a delivery date first —', 'woocommerce-delivery-date' ),
			),
		);
	}
}
