<?php
namespace Dreamfox\DeliveryDate\Repositories;

use Dreamfox\DeliveryDate\Settings;
use Dreamfox\DeliveryDate\TimeslotSettings;

class SettingRepository
{
	const KEY_DELIVERY_DAYS      = 'dreamfox_wdd_delivery_days';
	const KEY_CATEGORIES         = 'dreamfox_wdd_categories';
	const KEY_TIMESLOTS_ENABLED  = 'dreamfox_wdd_timeslots_enabled';
	const KEY_TIMESLOT_DURATION  = 'dreamfox_wdd_timeslot_duration';
	const KEY_TIMESLOT_START     = 'dreamfox_wdd_timeslot_start';
	const KEY_TIMESLOT_END       = 'dreamfox_wdd_timeslot_end';
	const KEY_TIMESLOT_MAX       = 'dreamfox_wdd_timeslot_max_orders';

	public function load()
	{
		$days       = get_option( self::KEY_DELIVERY_DAYS, 0 );
		$categories = get_option( self::KEY_CATEGORIES );
		if ( ! is_array( $categories ) ) {
			$categories = array();
		}
		$settings = new Settings();
		$settings->setDeliveryDays( $days );
		$settings->setCategories( $categories );
		return $settings;
	}

	public function save( Settings $data )
	{
		update_option( self::KEY_DELIVERY_DAYS, $data->getDeliveryDays() );
		update_option( self::KEY_CATEGORIES, $data->getCategories() );
	}

	public function loadTimeslotSettings()
	{
		$s = new TimeslotSettings();
		$s->setEnabled(   (bool) get_option( self::KEY_TIMESLOTS_ENABLED, false ) );
		$s->setDuration(  (int)  get_option( self::KEY_TIMESLOT_DURATION, 2 ) );
		$s->setStartTime(        get_option( self::KEY_TIMESLOT_START, '08:00' ) );
		$s->setEndTime(          get_option( self::KEY_TIMESLOT_END, '20:00' ) );
		$s->setMaxOrders( (int)  get_option( self::KEY_TIMESLOT_MAX, 10 ) );
		return $s;
	}

	public function saveTimeslotSettings( TimeslotSettings $s )
	{
		update_option( self::KEY_TIMESLOTS_ENABLED, $s->getEnabled() ? 1 : 0 );
		update_option( self::KEY_TIMESLOT_DURATION, $s->getDuration() );
		update_option( self::KEY_TIMESLOT_START,    $s->getStartTime() );
		update_option( self::KEY_TIMESLOT_END,      $s->getEndTime() );
		update_option( self::KEY_TIMESLOT_MAX,      $s->getMaxOrders() );
	}
}