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

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

class CategorySettingRepository implements RepositoryInterface
{

  const KEY_CATEGORIES = 'dreamfox_wdd_premium_categories';

  public function load()
  {
    $metaCategories = get_option(self::KEY_CATEGORIES, []);
    $categories = get_categories( array(
      'taxonomy' => 'product_cat',
      'hierarchical' => 1,
      'orderby' => 'name',
      'order'   => 'ASC',
      'hide_empty' => false,
    ));
    $result = [];
    foreach ($categories as $category) {
      $item = new stdClass();
      $item->id = $category->term_id;
      $item->name = $category->name;
      $item->selected = false;
      $item->days = 0;
      $metaCategory = $this->_exist($item->id, $metaCategories);
      if ($metaCategory) {
        $item->selected = true;
        $item->days = $metaCategory->days;
      }
      $result[] = $item;
    }
    $setting = new CategorySetting($result);
    return $setting;
  }

  public function save($setting)
  {
    $categories = $setting->getCategories();
    $metaCategories = [];
    foreach ($categories as $category) {
      if ($category->selected) {
        $metaCategories[] = $category;
      }
    }
    update_option(self::KEY_CATEGORIES, $metaCategories);
  }

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