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

use Dreamfox\DeliveryDate\Interfaces\RepositoryInterface;
use Dreamfox\DeliveryDate\Premium\HolidaySetting;
use stdClass;

class HolidaySettingRepository implements RepositoryInterface
{

  const KEY_COUNT_ONLY_WORKING_DAYS = 'dreamfox_wdd_premium_countOnlyWorkingDays';
  const KEY_DISABLE_DAYS = 'dreamfox_wdd_premium_disableDays';
  const KEY_HOLIDAYS = 'dreamfox_wdd_premium_holidays';

  public function load()
  {
    $result = new stdClass();
    $result->countOnlyWorkingDays = get_option(self::KEY_COUNT_ONLY_WORKING_DAYS, false);
    $result->disableDays = $this->_loadDisableDays();
    $result->holidays = $this->_loadHolidays();
    $setting = new HolidaySetting($result);
    return $setting;
  }

  private function _loadHolidays()
  {
    $metaHolidays = get_option(self::KEY_HOLIDAYS, []);
    if (!is_array($metaHolidays)) {
      $metaHolidays = [];
    }
    $holidays = [];
    $labels = ['I]', 'II]', 'III]', 'IV]', 'V]',];
    $id = 0;
    foreach ($labels as $label) {
      $id++;
      $item = new stdClass();
      $item->id = $id;
      $item->label = $label;
      $item->startDate = '';
      $item->endDate = '';
      $metaItem = $this->_exist($id, $metaHolidays);
      if ($metaItem) {
        $item->startDate = $metaItem->startDate;
        $item->endDate = $metaItem->endDate;
      }
      $holidays[] = $item;
    }
    return $holidays;
  }

  private function _loadDisableDays()
  {
    $metaDisableDays = get_option(self::KEY_DISABLE_DAYS, []);
    $allDisableDays = [
      2 => 'Monday',
      3 => 'Tuesday',
      4 => 'Wednesday',
      5 => 'Thursday',
      6 => 'Friday',
      7 => 'Saturday',
      1 => 'Sunday',
    ];
    $disableDays = [];
    foreach ($allDisableDays as $key => $text) {
      $item = new stdClass();
      $item->id = $key;
      $item->label = $text;
      $item->checked = false;
      $metaItem = $this->_exist($key, $metaDisableDays);
      if ($metaItem && $metaItem->checked) {
        $item->checked = true;
      }
      $disableDays[] = $item;
    }
    return $disableDays;
  }

  public function save($setting)
  {
    update_option(self::KEY_COUNT_ONLY_WORKING_DAYS, $setting->getCountOnlyWorkingDays());
    update_option(self::KEY_DISABLE_DAYS, $setting->getDisableDays());
    update_option(self::KEY_HOLIDAYS, $setting->getHolidays());
  }

  public function toArray()
  {
    return [];
  }

  protected function _exist($id, $metaItems)
  {
    foreach ($metaItems as $item) {
      if ($id == $item->id) {
        return $item;
      }
    }
    return false;
  }
}