<?php
/**
 * @package CleverOgre
 * @subpackage OgreAlert
 * @since OgreAlert 0.1.7
 */

namespace OgreAlert;

if (!defined('ABSPATH')) exit;

class Settings {

    private static $defaults;

    // Plugin Settings
    public static $name;
    public static $version;
    public static $capability;
    public static $path;
    public static $dir;
    public static $hook;

    // Message Settings
    public static $message_enabled;
    public static $message_position;
    public static $message_container;
    public static $message_transition_duration;
    public static $message_transition_animation;
    public static $message_dismiss_duration;
    public static $message_index;

    public static $message_high_text_color;
    public static $message_high_background_color;

    public static $message_normal_text_color;
    public static $message_normal_background_color;

    public static $message_low_text_color;
    public static $message_low_background_color;

    public static function init() {
        self::$defaults = [
            'message_enabled' => '1',
            'message_position' => 'bottom',
            'message_container' => '1200',
            'message_transition_duration' => '250',
            'message_dismiss_duration' => 'day',
            'message_animation' => 'slide',
            'message_index' => '10001',

            'message_high_text_color' => 'rgba(255, 255, 255, 1)',
            'message_high_background_color' => 'rgba(220, 53, 69, 1)',

            'message_normal_text_color' => 'rgba(52, 58, 64, 1)',
            'message_normal_background_color' => 'rgba(255, 255, 255, 1)',

            'message_low_text_color' => 'rgba(255, 255, 255, 1)',
            'message_low_background_color' => 'rgba(23, 162, 184, 1)',
        ];
    }

    public static function get($key) {
        if (!property_exists(__CLASS__, $key)) return false;

        switch ($key) {
            /* // Constant properties
            case 'readonly':
                return false;
            */

            default:
                $options = get_option('ogrealert_options');

                if (isset($options["ogrealert_settings_{$key}"])) {
                    return $options["ogrealert_settings_{$key}"];
                } else if (isset(self::$defaults[$key])) {
                    return self::$defaults[$key];
                } else {
                    return false;
                }

                break;
        }

        return null;
    }

    public static function set($key, $value) {
        if (!property_exists(__CLASS__, $key)) return false;

        switch ($key) {
            /* // Read-only properties
            case 'readonly':
                break;
            */

            default:
                $options = get_option('ogrealert_options');
                if (!is_array($options)) $options = [];
                $options["ogrealert_settings_{$key}"] = $value;
                update_option('ogrealert_options', $options);
                break;
        }

        return true;
    }

    public static function get_default($key) {
        if (!property_exists(__CLASS__, $key)) return null;

        if (!array_key_exists($key, self::$defaults)) return null;

        return self::$defaults[$key];
    }

    public static function parse_hex_color($hex) {
        // Check if empty
        if (!isset($hex) || trim($hex) == '') return false;

        // Validate with Regex
        $regex = '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/';
        if (preg_match($regex, $hex) != 1) return false;

        $dec = ['r' => 0, 'g' => 0, 'b' => 0];

        if (strlen($hex) == strlen('#000')) {
            $dec['r'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $dec['g'] = hexdec(substr($hex, 2, 1) . substr($hex, 1, 1));
            $dec['b'] = hexdec(substr($hex, 3, 1) . substr($hex, 1, 1));
        } else {
            $dec['r'] = hexdec(substr($hex, 1, 2));
            $dec['g'] = hexdec(substr($hex, 3, 2));
            $dec['b'] = hexdec(substr($hex, 5, 2));
        }

        return $dec;
    }

    public static function parse_dismiss_duration($duration) {
        if (is_numeric($duration)) return intval($duration);

        if (!is_string($duration)) $duration = self::get_default('message_dismiss_duration');

        switch ($duration) {
            case 'none':
                return -1;
            case 'page':
                return 0;
            case 'minute':
                return MINUTE_IN_SECONDS;
            case 'hour':
                return HOUR_IN_SECONDS;
            case 'day':
                return DAY_IN_SECONDS;
            case 'week':
                return WEEK_IN_SECONDS;
            case 'month':
                return MONTH_IN_SECONDS;
            case 'year':
                return YEAR_IN_SECONDS;
            default:
                return HOUR_IN_SECONDS;
        }
    }

}

class SettingsPage {

    public static function init() {
        add_action('admin_init', [__CLASS__, 'register_settings']);
        add_action('admin_menu', [__CLASS__, 'menu']);
    }

    static function menu() {
        if (!current_user_can(\OgreAlert\Settings::get('capability'))) return;

        $page = add_submenu_page('edit.php?post_type=alert', __('OgreAlert Settings', 'ogrealert'), __('Settings', 'ogrealert'), \OgreAlert\Settings::get('capability'), 'ogrealert_settings', [__CLASS__, 'page']);
        add_action('load-' . $page, [__CLASS__, 'load_page']);
    }

    static function load_page() {
        if (!current_user_can(\OgreAlert\Settings::get('capability'))) return;

        add_action('admin_enqueue_scripts', [__CLASS__, 'admin_enqueue_scripts']);
    }

    static function admin_enqueue_scripts() {
        if (!wp_style_is('wp-color-picker', 'enqueued')) {
            wp_enqueue_style('wp-color-picker');
        }
        wp_enqueue_script('ogrealert-settings', \OgreAlert\Settings::get('dir') . 'assets/js/settings.js', ['jquery', 'wp-color-picker'], \OgreAlert\Settings::get('version'), true);
    }

    static function register_settings() {
        register_setting('ogrealert', 'ogrealert_options');

        // Message Settings

        add_settings_section('ogrealert_section_general', __('General Settings', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');

        add_settings_field('ogrealert_message_enabled', __('Enable Alerts', 'ogrealert'), [__CLASS__, 'field_checkbox'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_enabled',
            'default' => \OgreAlert\Settings::get_default('message_enabled'),
        ]);

        add_settings_field('ogrealert_message_position', __('Position', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_position',
            'options' => [
                'top' => __('Fixed Top', 'ogrealert'),
                'bottom' => __('Fixed Bottom', 'ogrealert'),
                'footer' => __('After Footer', 'ogrealert'),
                'custom' => __('Custom', 'ogrealert'),
            ],
            'default' => \OgreAlert\Settings::get_default('message_position'),
            'description' => __('If you choose Custom, you must add "do_action(\'display_alerts\');" to a suitable location in your template files.', 'ogrealert'),
        ]);

        add_settings_field('ogrealert_message_container', __('Container Width', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_container',
            'description' => 'A positive integer in pixels.',
            'placeholder' => \OgreAlert\Settings::get_default('message_container'),
            'default' => \OgreAlert\Settings::get_default('message_container'),
        ]);

        add_settings_field('ogrealert_message_transition_duration', __('Transition Duration', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_transition_duration',
            'description' => 'A positive integer in milliseconds.',
            'placeholder' => \OgreAlert\Settings::get_default('message_transition_duration'),
            'default' => \OgreAlert\Settings::get_default('message_transition_duration'),
        ]);

        add_settings_field('ogrealert_message_transition_animation', __('Transition Animation', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_transition_animation',
            'options' => [
                'slide' => __('Slide', 'ogrealert'),
                'fade' => __('Fade', 'ogrealert'),
                'custom' => __('Custom', 'ogrealert'),
            ],
            'default' => \OgreAlert\Settings::get_default('message_transition_animation'),
            'description' => __('If you choose Custom, the animation must be handled with the "ogrealert-message-transition-custom" class in css.', 'ogrealert'),
        ]);

        add_settings_field('ogrealert_message_dismiss_duration', __('Default Dismiss Duration', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_dismiss_duration',
            'options' => [
                'none' => __('None', 'ogrealert'),
                'page' => __('Page', 'ogrealert'),
                'minute' => __('Minute', 'ogrealert'),
                'hour' => __('Hour', 'ogrealert'),
                'day' => __('Day', 'ogrealert'),
                'week' => __('Week', 'ogrealert'),
                'month' => __('Month', 'ogrealert'),
                'year' => __('Year', 'ogrealert'),
            ],
            'default' => \OgreAlert\Settings::get_default('message_dismiss_duration'),
        ]);

        add_settings_field('ogrealert_message_index', __('Z-Index', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
            'id' => 'ogrealert_settings_message_index',
            'description' => 'Sets the z-index value of all OgreAlert messages. Useful for ensuring your messages appear above certain elements of your site.',
            'placeholder' => \OgreAlert\Settings::get_default('message_index'),
            'default' => \OgreAlert\Settings::get_default('message_index'),
        ]);

        add_settings_section('ogrealert_section_high', __('High Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');

        add_settings_field('ogrealert_message_high_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_high', [
            'id' => 'ogrealert_settings_message_high_text_color',
            'default' => \OgreAlert\Settings::get_default('message_high_text_color'),
        ]);

        add_settings_field('ogrealert_message_high_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_high', [
            'id' => 'ogrealert_settings_message_high_background_color',
            'default' => \OgreAlert\Settings::get_default('message_high_background_color'),
        ]);

        add_settings_section('ogrealert_section_normal', __('Normal Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');

        add_settings_field('ogrealert_message_normal_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_normal', [
            'id' => 'ogrealert_settings_message_normal_text_color',
            'default' => \OgreAlert\Settings::get_default('message_normal_text_color'),
        ]);

        add_settings_field('ogrealert_message_normal_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_normal', [
            'id' => 'ogrealert_settings_message_normal_background_color',
            'default' => \OgreAlert\Settings::get_default('message_normal_background_color'),
        ]);

        add_settings_section('ogrealert_section_low', __('Low Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');

        add_settings_field('ogrealert_message_low_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_low', [
            'id' => 'ogrealert_settings_message_low_text_color',
            'default' => \OgreAlert\Settings::get_default('message_low_text_color'),
        ]);

        add_settings_field('ogrealert_message_low_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_low', [
            'id' => 'ogrealert_settings_message_low_background_color',
            'default' => \OgreAlert\Settings::get_default('message_low_background_color'),
        ]);
    }

    static function page() {
        if (!current_user_can(\OgreAlert\Settings::get('capability'))) return;

        // Show error/update messages
        settings_errors('ogrealert_messages');
?>
<div class="wrap">
    <h1><?php esc_html_e(get_admin_page_title()); ?></h1>
    <form action="options.php" method="post"><?php
        settings_fields('ogrealert');
        do_settings_sections('ogrealert');
        submit_button(__('Save Settings', 'ogrealert'));
    ?></form>
</div>
<?php
    }

    // Sections

    public static function section($args) {
        // <p>Description</p>
    }

    // Fields

    public static function field_text($args) {
        $value = '';
        $options = get_option('ogrealert_options');
        if (isset($args['default'])) $value = $args['default'];
        if (isset($args['id']) && !empty($args['id']) && isset($options[$args['id']]) && !empty($options[$args['id']])) $value = $options[$args['id']];

        $type = 'text';
        if (isset($args['type']) && !empty($args['type'])) {
            $type = $args['type'];
        }

        echo '<input class="regular-text" type="' . $type . '" value="' . esc_attr($value) . '"';

        if (isset($args['id']) && !empty($args['id'])) {
            echo ' id="' . esc_attr($args['id']) . '"';
            echo ' name="ogrealert_options[' . esc_attr($args['id']) . ']"';
        }
        if (isset($args['placeholder']) && !empty($args['placeholder'])) {
            echo ' placeholder="' . esc_attr($args['placeholder']) . '"';
        }

        echo ' />';

        if (isset($args['description']) && !empty($args['description'])) {
            echo '<p class="description">';
            _e($args['description'], 'ogrealert');
            echo '</p>';
        }
    }

    public static function field_checkbox($args) {
        $value = false;
        $options = get_option('ogrealert_options');
        if (isset($args['default'])) $value = $args['default'];
        if (isset($args['id']) && !empty($args['id']) && isset($options[$args['id']]) && !empty($options[$args['id']])) $value = $options[$args['id']];

        echo '<input type="checkbox" value="1" type="checkbox" ' . checked($value, 1, false);

        if (isset($args['id']) && !empty($args['id'])) {
            echo ' id="' . esc_attr($args['id']) . '"';
            echo ' name="ogrealert_options[' . esc_attr($args['id']) . ']"';
        }
        echo ' />';

        if (isset($args['description']) && !empty($args['description'])) {
            echo '<p class="description">';
            esc_html_e($args['description'], 'ogrealert');
            echo '</p>';
        }
    }

    public static function field_wysiwyg($args) {
        if (!isset($args['id']) || empty($args['id'])) return;

        $value = '';
        $options = get_option('ogrealert_options');
        if (isset($args['default'])) $value = $args['default'];
        if (isset($options[$args['id']]) && !empty($options[$args['id']])) $value = $options[$args['id']];

        $settings = [
            'tinymce' => true,
            'textarea_name' => 'ogrealert_options[' . $args['id'] . ']',
            'textarea_rows' => 15,
            'tabindex' => 1,
        ];
        wp_editor($value, $args['id'], $settings);

        if (isset($args['description']) && !empty($args['description'])) {
            echo '<p class="description">';
            esc_html_e($args['description'], 'ogrealert');
            echo '</p>';
        }
    }

    public static function field_select($args) {
        if (!isset($args['id']) || empty($args['id'])) return;

        $selected = '';
        $options = get_option('ogrealert_options');
        if (isset($args['default'])) $selected = $args['default'];
        if (isset($options[$args['id']]) && !empty($options[$args['id']])) $selected = $options[$args['id']];

        echo '<select id="' . esc_attr($args['id']) . '" name="ogrealert_options[' . esc_attr($args['id']) . ']"';
        if (isset($args['class']) && !empty($args['class'])) echo ' class="' . esc_attr($args['class']) . '"';
        if (isset($args['required']) && $args['required'] == true) echo ' required="required"';
        echo '>';

        if (isset($args['placeholder']) && !empty($args['placeholder'])) {
            echo '<option value="">' . esc_html($args['placeholder']) . '</option>';
        }

        foreach ($args['options'] as $value => $title) {
            echo '<option value="' . esc_attr($value) . '" ' . selected($selected, $value, false) . '>' . esc_html($title) . '</option>';
        }

        echo '</select>';

        if (isset($args['description']) && !empty($args['description'])) {
            echo '<p class="description">';
            _e($args['description'], 'ogrealert');
            echo '</p>';
        }
    }

    public static function field_color($args) {
        $value = '';
        $options = get_option('ogrealert_options');
        if (isset($args['default'])) $value = $args['default'];
        if (isset($args['id']) && !empty($args['id']) && isset($options[$args['id']])) $value = $options[$args['id']];

        echo '<input class="ogrealert-color-picker" type="text" value="' . esc_attr($value) . '"';

        if (isset($args['id']) && !empty($args['id'])) {
            echo ' id="' . esc_attr($args['id']) . '"';
            echo ' name="ogrealert_options[' . esc_attr($args['id']) . ']"';
        }

        if (isset($args['placeholder']) && !empty($args['placeholder'])) {
            echo ' placeholder="' . esc_attr($args['placeholder']) . '"';
        }

        echo ' />';

        if (isset($args['description']) && !empty($args['description'])) {
            echo '<p class="description">';
            _e($args['description'], 'ogrealert');
            echo '</p>';
        }
    }

}

\OgreAlert\SettingsPage::init();
