<?php
/*
    announcement module
    integrated in core theme
*/
if( ! defined( 'ABSPATH' ) ) exit;

new announce();
class announce {

    /**
     * Constructor 
     */
    function __construct() {
        $this->customizer();
        $this->meta_box();
        $this->render();
    }


    /**
     * =================================================================
     *                          Customizer & Processor
     * =================================================================
     */
    public function customizer() {
        add_action( 'get_header', array($this, 'add_process_defaults') );
        add_action( 'customize_register', array($this, 'add_customizer_settings') );
        add_action( 'customize_controls_enqueue_scripts', array( $this, 'add_customizer_scripts' ), 99 );
    }
    
    /**
     * Add inline script to customizer
     */
    public function add_customizer_scripts() {
        
        $js = "jQuery(function($) {
                    sessionStorage.removeItem('announcement_preview');
                    $('#_customize-input-show_announcement').on('click', function () {
                        if (!sessionStorage.getItem('announcement_preview')) {
                            sessionStorage.setItem('announcement_preview', JSON.stringify( { 'set': new Date().getTime() } ));
                            wp.customize.previewer.refresh();
                        }
                    } );
                    $('#_customize-input-hide_announcement').on('click', function () {
                        if (sessionStorage.getItem('announcement_preview')) {
                            sessionStorage.removeItem('announcement_preview');
                            wp.customize.previewer.refresh();
                        }
                    } );        
                    wp.customize.section('section_modules', function(section) {
                        section.expanded.bind(function(isExpanded) {
                            if (!isExpanded) {
                                if (sessionStorage.getItem('announcement_preview')) {
                                    sessionStorage.removeItem('announcement_preview');
                                    wp.customize.previewer.refresh();
                                }
                            }
                        } );
                    } );               
                } );";
        wp_add_inline_script('customizer_admin', $js, 'after');
    }

    /**
     * Add vars to the processor
     */
    public function add_process_defaults() {

        if (!array_key_exists('ANOseparator' ,processor::$root)) {
            // common prio to bundle sets
            $prio = 30;
            $section = 'section_modules';
            processor::$root = array_merge(processor::$root, array(
                'ANOseparator'      => array( 'section' => $section, 'type' => 'separator', 'label' => 'Announcements', 'mod' => 'sep_announcement', 'priority' => $prio ),
                'ANOenable'         => array( 'section' => $section, 'type' => 'checkbox',  'label' => 'Announcements aktivieren', 'description' => 'Der Inhalt der Announcement-Box wird auf jeder Seite individuell eingestellt.', 'mod' => 'enable_announce', 'priority' => $prio, 'default' => 0, 'transport' => 'refresh' ),

                'ANOgroup'          => array( 'section' => $section, 'type' => 'group',     'label' => 'Einstellungen', 'mod' => 'group_announcement', 'priority' => $prio, 'input_attrs' => array( 'children' => 16 ), 
                                                                                                'dependency' => 'enable_announce' ),                
                
                'ANOshow'           => array( 'section' => $section, 'type' => 'button',    'label' => 'Vorschau anzeigen', 'mod' => 'show_announcement', 'priority' => $prio, 'class' => 'secondary', 
                                                                                                'dependency' => array( 'enable_announcement' ) ),
                'ANOhide'           => array( 'section' => $section, 'type' => 'button',    'label' => 'Vorschau verstecken', 'mod' => 'hide_announcement', 'priority' => $prio, 'class' => 'secondary', 
                                                                                                'dependency' => array( 'enable_announcement' ) ),

                'ANOtoggle'         => array( 'section' => $section, 'type' => 'range',     'label' => 'Allgemein', 'lbl' => 'Darstellung ab (Breite):', 'mod' => 'announcement_toggle', 'priority' => $prio, 'default' => 1024, 'unit' => 'px', 'input_attrs' => array( 'min' => 0, 'max' => 1920, 'step'  => 1 ), 'transport' => 'refresh', 
                                                                                                'dependency' => 'enable_announce' ),
                '--ANOheight'       => array( 'section' => $section, 'type' => 'range',       'lbl' => 'Höhe:', 'mod' => 'announcement_height', 'priority' => $prio, 'default' => 80, 'unit' => 'px', 'input_attrs' => array( 'min' => 20, 'max' => 200, 'step'  => 1 ), 
                                                                                                'dependency' => 'enable_announce' ),
                '--ANOjustifyContent' => array( 'section' => $section, 'type' => 'select',     'description' => 'Anordnung Inhalte', 'mod' => 'announcement_justify_content', 'priority' => $prio, 'default' => 'center', 
                                                                                                'dependency' => 'enable_announce', 
                                                                                                'choices' => array( 'flex-start' => 'links', 'center' => 'mittig', 'flex-end' => 'rechts', 'space-around' => 'Abstand außen', 'space-between' => 'Abstand dazwischen' ) ),
                '--ANOalignItems'   => array( 'section' => $section, 'type' => 'select',      'description' => 'Ausrichtung Inhalte', 'mod' => 'announcement_align_items', 'priority' => $prio, 'default' => 'center', 
                                                                                                'dependency' => 'enable_announce', 
                                                                                                'choices' => array( 'flex-start' => 'oben', 'center' => 'mittig', 'flex-end' => 'unten' ) ),
                
                '--ANbgcolor'       => array( 'section' => $section, 'type' => 'colselect',   'description' => 'Hintergrundfarbe', 'mod' => 'announcement_background_color2', 'priority' => $prio, 'default' => 'color21', 'transport' => 'refresh', 
                                                                                                'dependency' => array( 'enable_announce' ) ),
                '--ANtxtcolor'      => array( 'section' => $section, 'type' => 'colselect',   'description' => 'Schriftfarbe', 'mod' => 'announcement_text_color2', 'priority' => $prio, 'default' => 'color22', 'transport' => 'refresh', 
                                                                                                'dependency' => array( 'enable_announce' ) ),
                '--ANLtxtcolor'     => array( 'section' => $section, 'type' => 'colselect',  'label' => 'Links', 'description' => 'Linkfarbe', 'mod' => 'announcement_link_color2', 'priority' => $prio, 'default' => 'color22', 'transport' => 'refresh', 
                                                                                                'dependency' => array( 'enable_announce' ) ),
                '--ANLtxtcolorHover'=> array( 'section' => $section, 'type' => 'colselect',   'description' => 'Linkfarbe Hover', 'mod' => 'announcement_link_hover_color2', 'priority' => $prio, 'default' => 'color11', 'transport' => 'refresh', 
                                                                                                'dependency' => array( 'enable_announce' ) ),

                '--ANOIMGheight'    => array( 'section' => $section, 'type' => 'range',     'label' => 'Bild', 'lbl' => 'Bildhöhe:', 'mod' => 'announcement_image_height', 'priority' => $prio, 'default' => 40, 'unit' => 'px', 'input_attrs' => array( 'min' => 20, 'max' => 200, 'step'  => 1 ), 
                                                                                                'dependency' => 'enable_announce' ),
                '--ANOIMGpadding'   => array( 'section' => $section, 'type' => 'range',       'lbl' => 'Bild Padding:', 'mod' => 'announcement_image_padding', 'priority' => $prio, 'default' => 30, 'unit' => 'px', 'input_attrs' => array( 'min' => 0, 'max' => 50, 'step'  => 1 ), 
                                                                                                'dependency' => 'enable_announce' ),
            ));
        }

    }

    /**
     * Add the vars to the customizer settings
     */
    public function add_customizer_settings($wp_customize) {
        $this->add_process_defaults();
    }


    /**
     * =================================================================
     *                          Meta Box
     * =================================================================
     */
    public function meta_box() {
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('save_post', array($this, 'save_post'), 20, 2);
    }

    /**
     * Add meta box
     */
    public function add_meta_box() {
        if (!get_theme_mod('enable_announce')) return;

        add_meta_box(
            "announce_metabox", // ID
            __('Announcement Info Box', 'core'), // Title
            array($this, 'render_meta_box'), // Callback
            'page', // CPT name
            'advanced', // advanced = at bottom of page
            'default' // Priority
            //array $callback_args = null // Arguments passed to the callback
        );
    }
    
    /**
     * Render the meta box
     */
    public function render_meta_box($post) {

        $announce_active = (get_post_meta($post->ID, '_announce_active', true) != -1) ? 'checked' : '';
        $announce_content = get_post_meta($post->ID, '_announce_content', true);
        $announce_read_more_text = get_post_meta($post->ID, '_announce_read_more_text', true);
        $announce_read_more_link = get_post_meta($post->ID, '_announce_read_more_link', true);
        $announce_image = get_post_meta($post->ID, '_announce_image', true);

        echo "<table class='form-table'>";
        // Zeile
        echo "<tr><th>".
                "<label>".__('Aktivieren?', 'core')."</label>".
                "<small>".__('Announcement aktivieren?', 'core')."</small>
            </th><td>
                <input id='announce_toggle' class='".uniqid()."'type='checkbox' name='announce_active' value='$announce_active' $announce_active>
            </td></tr>";
        $checked = "style='display:table-row'";
        if ($announce_active != 'checked')
            $checked = "style='display:none'";
        // Zeile
        echo "<tr class='toggle_row' $checked><th>".
                "<label>".__('Text', 'core')."</label>".
                "<small>".__('Inhalt des Announcements', 'core')."</small>
            </th><td>
                <input type='text' name='announce_content' value='$announce_content'>
            </td></tr>";
        // Zeile
        echo "<tr class='toggle_row' $checked><th>".
                "<label>".__('Linktext', 'core')."</label>
            </th><td>
                <input type='text' name='announce_read_more_text' value='$announce_read_more_text'>
            </td></tr>";
        // Zeile
        echo "<tr class='toggle_row' $checked><th>".
                "<label>".__('Link URL', 'core')."</label>
            </th><td>
                <input type='text' name='announce_read_more_link' value='$announce_read_more_link'>
            </td></tr>";
        // Zeile
        echo "<tr class='toggle_row' $checked><th>".
                "<label>".__('Bild', 'core')."</label>".
                "<small>".__('Bild wird links neben dem Inhalt angezeigt', 'core')."</small>
            </th><td>";
                $hide_pick = "hidden";
                $hide_remove = "";
                $hide_preview = "";
                if ($announce_image == "") {
                    $hide_pick = "";
                    $hide_remove = "hidden";
                    $hide_preview = "style='display:none'";
                }
                echo "<input class='hidden' id='announce_image' type='text' name='announce_image' value='$announce_image' />
                    <input class='button $hide_pick' id='announce_img_button' type='button' value='".__('Bild auswählen', 'core')."' />
                    <input class='button $hide_remove' id='announce_img_remove' type='button' value='".__('Bild entfernen', 'core')."' />
                    <div class='image_src'><small id='announce_img_url'>$announce_image'</small></div>
                    <div class='image_preview' $hide_preview><img id='announce_img_src' src='$announce_image' /></div>";
        echo "</td></tr>";
        echo "</table>";

    }
    
    /**
     * Save the meta box informations
     */
    public function save_post($post_id, $post) {
        if (!get_theme_mod('enable_announce')) return;
        if ($post->post_type != 'page') return;
        if (!is_admin()) return;
        if (empty($_POST)) return;
        if ( isset($_POST['action']) && $_POST['action'] === 'greyd_ajax' ) return; // posttype inserted via ajax

        update_post_meta($post_id, '_announce_active', (isset($_POST['announce_active'])) ? 'on' : -1);
        if (isset($_POST['announce_content'])) update_post_meta($post_id, '_announce_content', esc_attr($_POST['announce_content']));
        if (isset($_POST['announce_read_more_text'])) update_post_meta($post_id, '_announce_read_more_text', esc_attr($_POST['announce_read_more_text']));
        if (isset($_POST['announce_read_more_link'])) update_post_meta($post_id, '_announce_read_more_link', esc_attr($_POST['announce_read_more_link']));
        if (isset($_POST['announce_image'])) update_post_meta($post_id, '_announce_image', esc_attr($_POST['announce_image']));
    }


    /**
     * =================================================================
     *                          Render
     * =================================================================
     */
    public function render() {
        add_action('announcement_hook', array($this, 'add_announcement'));
        add_action('render_announcement', array($this, 'render_announcement'));
        add_action('the_post', array($this, 'check_announce'));
    }

    /**
     * Add announcement box into navigation
     * 
     * @hook 'announcement_hook'
     */
    public function add_announcement() {
        if ( !is_search()) do_action('render_announcement', get_the_ID());
    }

    /**
     * Echo the announcement box for a specific post
     * 
     * @param $post_id  WP_Post ID. Defaults to global post ID.
     */
    public function render_announcement($post_id=null) {
        
        $post_id = $post_id ?? get_the_ID();

        if ($this->check_announce($post_id)) {
            $announce = $this->get_announce($post_id);
            if (!$announce) return;
            $preview  = !empty($announce->preview) ? "on" : "off";
            $id       = !empty($announce->id) ? $announce->id : 0;
            $image    = !empty($announce->image) ? "<img class='image animate_fast' style='height:100%;' src='".$announce->image."' title='".$announce->title."'>" : '';
            $btn      = !empty($announce->uri) ? " <a href='".$announce->uri."' class='animate_fast'>".$announce->btn."</a>" : '';
            $content  = !empty($announce->content) ? "<div class='content'>".$announce->content." ".$btn."</div>" : "<div class='content'>".$btn."</div>";

            $inline_style = "";
            if ( get_theme_mod('navi_header_sec_mode', 'none') !== 'none' ) {
                if ( 'column-reverse' === get_theme_mod('navi_header_sec_position', 'column') ) {
                    $inline_style = "style='-webkit-box-ordinal-group: 10; -moz-box-ordinal-group: 10; -ms-flex-order: 10; -webkit-order: 10; order: 10;'";
                }
            }

            echo "<div class='announce animate_fast' data-announce-id='".$id."' data-preview='".$preview."' $inline_style>
                    <div class='close_ animate_fast' data-close='announce'>
                        <span aria-hidden='true' class='icon_close'></span>
                    </div>
                    <div class='container animate_fast'>
                        <div class='announce_image'>".$image."</div>
                        <div class='announce_content animate_fast'>".$content."</div>
                    </div>
                </div>";
        }
    }

    /**
     * Get announcement metadata
     * 
     * @param $post_id  WP_Post ID. Defaults to global post ID.
     */
    public function get_announce($post_id=null) {
        $id = $post_id ?? get_the_ID();
        $active = get_post_meta($id, '_announce_active', true);
        if ($active != "on") {
            $announce = (object)array(
                'id'      => 0,
                'content' => 'Announcement Inhalt',
                'image'   => get_template_directory_uri().'/assets/icon/wizard/logo.svg',
                'uri'     => site_url('/'),
                'btn'     => 'Link',
                'title'   => 'Announcement Titel',
                'preview' => true,
            );
            // return false;
        }
        else {
            $announce = (object)array(
                'id'      => $id,
                'content' => get_post_meta($id, '_announce_content', true),
                'image'   => get_post_meta($id, '_announce_image', true),
                'uri'     => get_post_meta($id, '_announce_read_more_link', true),
                'btn'     => get_Post_meta($id, '_announce_read_more_text', true),
                'title'   => wp_strip_all_tags(get_post_meta($id, '_announce_content', true)),
            );
        }
        if (strpos($announce->uri, "http://") !== 0 && strpos($announce->uri, "https://") !== 0) {
            $announce->uri = "https://".$announce->uri;
        }

        if ( empty($announce->content) && empty($announce->image) && empty($announce->btn) && empty($announce->title) ) return false;
        return $announce;
    }

    /**
     * Check if announcement exists and should be rendered on this page
     * 
     * @param $post_id  WP_Post ID. Defaults to global post ID.
     */
    public function check_announce($post_id=null) {
        if (!get_theme_mod('enable_announce')) return false;
        if (is_customize_preview()) return true;

        $id = $post_id ?? get_the_ID();
        $active = get_post_meta($id, '_announce_active', true);
        return ($active == 'on') ? true : false;
    }

}

