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

namespace OgreAlert;

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

class Alert {

    public static function load() {
        add_action('init', [__CLASS__, 'init']);
        add_filter('manage_alert_posts_columns', [__CLASS__, 'register_columns']);
        add_action('manage_alert_posts_custom_column', [__CLASS__, 'display_column'], 10, 2);

        // OgreAlert Content Filters
        add_filter('ogrealert/content', 'wptexturize');
        add_filter('ogrealert/content', 'convert_smilies', 20);
        add_filter('ogrealert/content', 'wpautop');
        add_filter('ogrealert/content', 'shortcode_unautop');
        add_filter('ogrealert/content', 'prepend_attachment');
        add_filter('ogrealert/content', 'wp_filter_content_tags');
        add_filter('ogrealert/content', 'do_shortcode', 11); // After wpautop
    }

    static function init() {
        $post_type_args = [
            'supports' => ['title', 'editor', 'revisions'],
            'public' => true,
            'exclude_from_search' => true,
            'publicly_queryable' => false,
            'show_in_nav_menus' => false,
            'show_ui' => true,
            'has_archive' => false,
            'show_in_admin_bar' => true,
            'menu_position' => apply_filters('ogrealert/menu_position', 20),
            'menu_icon' => 'dashicons-format-status',
        ];

        if (class_exists('Ogre')) {
            $post_type_args['labels'] = \Ogre::get_labels(__('Alerts', 'ogrealert'), __('Alert', 'ogrealert'));
        } else {
            $post_type_args['labels'] = [
                'name' => __('Alerts', 'ogrealert'),
                'singular_name' => __('Alert', 'ogrealert'),
            ];
        }

        register_post_type('alert', apply_filters('ogrealert/post_type_args', $post_type_args));
    }

    static function register_columns($columns) {
        $_columns = [];

        foreach ($columns as $key => $label) {
            if ($key == 'date') {
                $_columns['priority'] = __('Priority', 'ogrealert');
                $_columns['expiration'] = __('Expires On', 'ogrealert');
            }
            $_columns[$key] = $label;
        }

        return $_columns;
    }

    static function display_column($column, $post_id) {
        switch ($column) {
            case 'priority':
                esc_html_e(ucfirst(get_post_meta($post_id, '_ogrealert_priority', true)));
                break;
            case 'expiration':
                $exp_time = \OgreAlert\Expiration::get_timestamp($post_id);
                if (!!$exp_time) esc_html_e(date(get_option('date_format'), $exp_time));

                break;
        }
    }

    public static function valid($id) {
        if (is_a($id, 'WP_Post')) $id = $id->ID;

        $return = true;

        if (get_post_type($id) != 'alert' || get_post_status($id) != 'publish') $return = false;
        if (\OgreAlert\Settings::get('message_enabled') != '1') $return = false;
        if (empty(trim(self::get_content($id, false)))) $return = false;
        //if (isset($_COOKIE['ogrealert_' . strval($id)])) $return = false;

        return apply_filters('ogrealert/valid_id', $return, $id);
    }

    private static function validate_ids(&$ids) {
        if (!is_array($ids) || empty($ids)) return false;

        $ids = array_map('intval', $ids);

        $remove_keys = [];
        foreach ($ids as $key => $id) {
            if (!self::valid($id)) $remove_keys[] = $key;
        }
        foreach ($remove_keys as $key) {
            unset($ids[$key]);
        }

        return true;
    }

    public static function get_content($id, $echo = false) {
        if (is_a($id, 'WP_Post')) $id = $id->ID;

        $_post = get_post($id);
        if (is_wp_error($_post) || !is_a($_post, 'WP_Post')) return false;

        $content = apply_filters('ogrealert/content', $_post->post_content);

        if ($echo == true) {
            echo $content;
            return true;
        } else {
            return $content;
        }
    }

    public static function get_active() {
        $alerts = get_posts(apply_filters('ogrealert/get_active_args', [
            'posts_per_page' => -1,
            'offset' => 0,
            'orderby' => 'rand',
            'order' => 'ASC',
            'post_type' => 'alert',
            'post_stauts' => 'publish',
            'fields' => 'ids',
        ]));
        $alerts = !is_wp_error($alerts) && !empty($alerts) ? $alerts : false;

        self::validate_ids($alerts);

        return apply_filters('ogrealert/get_active', $alerts);
    }
    public static function has_active() {
        return apply_filters('ogrealert/has_active', !empty(self::get_active()));
    }

    public static function get_random() {
        $alerts = self::get_active();

        $return = false;
        if (!empty($alerts)) $return = array_values($alerts)[0];

        return apply_filters('ogrealert/get_random', $return);
    }

    public static function is_active($id = false) {
        if ($id === false) $id = self::get_random();
        if ($id === false) return false;

        $alert = get_post($id);
        if (is_wp_error($alert) || $alert === false) return false;

        if (!self::valid($alert)) return false;

        return apply_filters('ogrealert/is_active', true, $id);
    }

}

\OgreAlert\Alert::load();

class AlertMetaBox {

    public static function load() {
        if (is_admin()) {
            add_action('load-post.php', [__CLASS__, 'init']);
            add_action('load-post-new.php', [__CLASS__, 'init']);
        }
    }

    public static function init() {
        add_action('add_meta_boxes_alert', [__CLASS__, 'add']);
        add_action('save_post', [__CLASS__, 'save'], 10, 2);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
    }

    static function enqueue_scripts() {
        if (!wp_style_is('jquery-ui-datepicker', 'enqueued')) {
            wp_enqueue_style('jquery-ui-datepicker');
        }
        wp_enqueue_script('ogrealert-post', \OgreAlert\Settings::get('dir') . 'assets/js/post.js', ['jquery', 'jquery-ui-core', 'jquery-ui-datepicker'], \OgreAlert\Settings::get('version'), true);
    }

    static function add() {
        add_meta_box(
            'ogrealert_post_settings',
            __('Message Settings', 'ogrealert'),
            [__CLASS__, 'render'],
            'alert',
            'side',
            'default'
        );
    }

    static function render($post) {
        wp_nonce_field('post_settings', '_ogrealert_nonce');

        echo '<p>';
        self::field_select([
            'id' => 'ogrealert_post_settings_priority',
            'name' => '_ogrealert_priority',
            'label' => __('Priority', 'ogrealert'),
            'options' => [
                'high' => __('High', 'ogrealert'),
                'normal' => __('Normal', 'ogrealert'),
                'low' => __('Low', 'ogrealert'),
            ],
            'default' => 'normal',
            'class' => 'widefat',
        ]);
        echo '</p>';

        echo '<p>';
        self::field_date([
            'id' => 'ogrealert_post_settings_expiration',
            'name' => '_ogrealert_expiration',
            'label' => __('Expires On', 'ogrealert'),
            'class' => 'widefat',
        ]);
        echo '</p>';

        echo '<p>';
        self::field_select([
            'id' => 'ogrealert_post_settings_duration',
            'name' => '_ogrealert_duration',
            'label' => __('Dismiss Duration', 'ogrealert'),
            '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('message_dismiss_duration'),
            'class' => 'widefat',
            'description' => __('If "None" is selected, the notice will not be able to be dismissed.', 'ogrealert'),
        ]);
        echo '</p>';
    }

    static function save($post_id, $post) {
        // Check if nonce is valid
        if (!wp_verify_nonce(isset($_POST['_ogrealert_nonce']) ? $_POST['_ogrealert_nonce'] : '', 'post_settings')) return;

        // Check if user is capable
        if (!current_user_can(\OgreAlert\Settings::get('capability'), $post_id)) return;

        // Check if not an autosave or revision
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) return;

        $keys = [
            '_ogrealert_priority',
            '_ogrealert_expiration',
            '_ogrealert_duration',
        ];
        foreach ($keys as $key) {
            if (isset($_POST[$key])) update_post_meta($post_id, $key, $_POST[$key]);
        }
    }

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

        if (isset($args['label']) && !empty($args['label'])) {
            self::field_label([
                'title' => $args['label'],
                'required' => isset($args['required']) && $args['required'] == true,
            ]);
        }

        $selected = '';
        $value = get_post_meta(get_the_ID(), $args['name'], true);
        if (!empty($value) && in_array($value, array_keys($args['options']))) {
            $selected = $value;
        } else if (isset($args['default'])) {
            $selected = $args['default'];
        }

        echo '<select id="' . esc_attr($args['id']) . '"';

        if (isset($args['name'])) {
            echo ' name="' . esc_attr($args['name']) . '"';
        } else {
            echo ' name="' . 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_date($args) {
        if (!isset($args['id']) || empty($args['id'])) return;

        if (isset($args['label']) && !empty($args['label'])) {
            self::field_label([
                'title' => $args['label'],
                'required' => isset($args['required']) && $args['required'] == true,
            ]);
        }

        $value = get_post_meta(get_the_ID(), $args['name'], true);
        if (empty($value) && isset($args['default'])) $value = $args['default'];

        echo '<input type="date" class="ogrealert-date-picker ' . esc_attr($args['class']) . '" value="' . esc_attr($value) . '"';

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

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

        if (isset($args['required']) && $args['required'] == true) {
            echo ' required="required"';
        }

        echo ' />';

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

    public static function field_label($args) {
        if (!isset($args['title'])) return false;

        echo '<label';
        if (isset($args['class']) && !empty($args['class'])) echo ' class="' . esc_attr($args['class']) . '"';
        if (isset($args['id']) && !empty($args['id'])) echo ' for="' . esc_attr($args['id']) . '"';
        echo '>';
        esc_html_e($args['title']);
        if (isset($args['required']) && $args['required'] == true) echo ' <span class="required req">*</span>';
        echo '</label>';
    }

}

\OgreAlert\AlertMetaBox::load();
