<?php

namespace auctionforge\inc\helpers;

use DateTime;
use DateTimeImmutable;
use DateTimeZone;
use stdClass;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\model\Auction;

class SettingsHelper
{
    const STATUS_FUTURE = 'future';
    const STATUS_PUBLISH = 'publish';
    const STATUS_DRAFT = 'draft';
    const STATUS_TRASH = 'trash';

    public static function getTermOption($termId, $key, $default = '')
    {
        $options = get_term_meta($termId, $key);
        if (!empty($options)) {
            return apply_filters('auctionforge_get_term_option', $options[0], $key);
        }
        return apply_filters('auctionforge_get_term_option', $default, $key);
    }

    /**
     * Set option value on file
     * @param $key string
     * @param $value mixed
     * @return int|false
     */
    public static function setOption($key, $value)
    {
        /** @var stdClass $config */
        $config = self::prepareOptionsFromFile();
        $config->{$key} = $value;

        $pluginDir = getDirAuctionForgePlugins();
        $confFile = $pluginDir . "/inc/services/configs.json";

        return file_put_contents($confFile, json_encode($config));
    }

    /**
     * Get option value by option name
     * @param $key string
     * @param $default string
     * @return mixed
     */
    public static function getOption($key, $default, $type = 'db')
    {
        if ($type == 'db') {
            $options = self::getPluginOptions();
            $args = wp_parse_args($options, array(
                $key => $default
            ));
            if ($args[$key] == '') {
                $args[$key] = $default;
            }
        } else {
            $args[$key] = self::getOptionFromFile($key, $default);
        }
        return apply_filters('auctionforge_get_option', $args[$key], $key);
    }

    public static function getPluginOptions()
    {
        return get_option('bidspirit_settings');
    }

    public static function getOptionFromFile($key, $default)
    {
        $config = self::prepareOptionsFromFile();

        if (!empty($config->{$key})) {
            return $config->{$key};
        } else {
            return $default;
        }
    }

    private static function prepareOptionsFromFile()
    {
        $pluginDir = getDirAuctionForgePlugins();
        $confPath = get_stylesheet_directory() . "/auctionforge/services/configs.json";
        if (!file_exists($confPath)) {
            $confPath = $pluginDir . "/inc/services/configs.json";
        }
        $obj = new stdClass();

        if (!file_exists($confPath)) {
            file_put_contents($confPath, $obj);
        }

        $config = file_get_contents($confPath);
        if ($config == "") {
            $config = $obj;
        } else {
            $config = json_decode($config);
        }
        return $config;
    }

    /**
     * @param $nameOption string
     * @param $value mixed
     */
    public static function updateOption($nameOption, $value)
    {
        $options = self::getPluginOptions();
        $options[$nameOption] = $value;
        return update_option("bidspirit_settings", $options, 'no');
    }

    /**
     * Convert string value of parameter to boolean
     * @param $checkboxId string
     * @return bool
     */
    public static function isChecked($checkboxId, $default = 'on') {
        $settings = new Settings();
        $defaultValues = $settings->getCheckboxDefault($checkboxId, $default);
        $value = SettingsHelper::getOption($checkboxId, $defaultValues);
        return $value == 'on';
    }

    /**
     * Get list of auctions excluded from import
     * @return array
     */
    public static function getAuctionExclude()
    {
        $values = self::getOption('exclude_auction', 0);
        return explode("\r\n", $values);
    }

    public static function getAuctionListFromSettings($key)
    {
        $values = self::getOption($key, 0);
        return explode("\r\n", $values);
    }

    /**
     * @param $newValue string
     * @param $oldValue array
     * @return bool
     */
    public static function updateAuctionExclude($newValue, $oldValue)
    {
        $separator = "\r\n";
        if (!empty($oldValue)) {
            $newValue = implode($separator, $oldValue) . $separator . $newValue;
        } else {
            $newValue .= $separator;
        }
        return self::updateOption('exclude_auction', $newValue);
    }

    /**
     * Get value option type import
     * @param $lotOption string
     * @return string
     */
    public static function getPostStatus($lotOption)
    {
        $setting = self::getOption('type', 'auto');
        switch ($setting) {
            case self::STATUS_PUBLISH :
                $value = self::STATUS_PUBLISH;
                break;
            case self::STATUS_DRAFT :
                $value = self::STATUS_DRAFT;
                break;
            default :
                $value = ($lotOption) ? self::STATUS_DRAFT : self::STATUS_PUBLISH;
                break;
        }
        return $value;
    }

    /**
     * @param $time
     * @return string
     * @throws \Exception
     */
    public static function getDateTime($time = "now")
    {
        $timeZoneName = SettingsHelper::getOption(Settings::OPTIONS_TIMEZONES, "");
        if (!empty($timeZoneName)) {
            $dt = new DateTime($time, new DateTimeZone('UTC'));
            $dt->setTimezone(new DateTimeZone($timeZoneName));
            $dateTime = $dt->format(Auction::DATE_FORMAT);
        } else {
            $timeZoneSetting = SettingsHelper::getOption('time_zone', "+3");
            preg_match("/\d+/", $timeZoneSetting, $hour);
            preg_match("/\W/", $timeZoneSetting, $sign);
            if (isset($hour[0]) && isset($sign[0])) {
                $timeZoneValue = sprintf( '%s%02d:%02d', $sign[0], $hour[0], 0);
            } else {
                $timeZoneValue = "+03:00";
            }
            $timeZone = new DateTimeZone($timeZoneValue);
            $dateTime = (new DateTime($time, $timeZone))->format(Auction::DATE_FORMAT);
        }
        return preg_replace("/\s/", "T", $dateTime);
    }

    public static function dateTimeFormat($dateTime)
    {
        $timeZoneName = SettingsHelper::getOption(Settings::OPTIONS_TIMEZONES, "");
        if ($timeZoneName == "") {
            $timeZoneSetting = SettingsHelper::getOption('time_zone', "+3");
            preg_match("/\d+/", $timeZoneSetting, $hour);
            preg_match("/\W/", $timeZoneSetting, $sign);
            if (isset($hour[0]) && isset($sign[0])) {
                $timeZoneValue = sprintf( '%s%02d:%02d', $sign[0], $hour[0], 0);
            } else {
                $timeZoneValue = "+03:00";
            }
            return  $dateTime . $timeZoneValue;
        } else {
            $dt = new DateTimeImmutable($dateTime, new DateTimeZone($timeZoneName));
            return preg_replace("/\#/", "T", $dt->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d#H:i')) . ":00Z";
        }
    }

    /**
     * @param $date
     * @return int
     */
    public static function isDST($date) {
        $time = strtotime($date);

        $year = date('Y');
        $dst_start = strtotime('last sunday april ' . $year);
        $dst_end = strtotime('last sunday november ' . $year);

        return ($time >= $dst_start && $time < $dst_end) ? 1 : 0;
    }
}