<?php

namespace Reach\App;

use Reach\App\Interfaces\WordPressHooks;
use Reach\App\Fields\SiteOptions;
use Reach\App\Theme\ThemeMenus;

/**
 * Class Setup
 *
 * @package Reach\App
 */
class Setup implements WordPressHooks {

    /**
     * Add class hooks.
     */
    public function addHooks() {
        add_action( 'init', [ $this, 'registerMenus' ] );
        add_action( 'wp_loaded', [ $this, 'removeRss' ], 9 );
        add_action( 'wp_loaded', [ $this, 'removeEmoji' ], 9 );
        add_action( 'wp_loaded', [ $this, 'removeLiveWriter' ], 9 );
        add_action( 'wp_loaded', [ $this, 'removeXMLRPC' ], 9 );
        add_action( 'wp_head', [ $this, 'outputSiteFavicons' ] );
        add_action( 'wp_head', [ $this, 'maybeOutputGoogleAnalytics' ] );
        add_action( 'admin_footer_text', [ $this, 'printThemeVersion' ], 11 );
        add_action( 'check_ajax_referer', [ $this, 'preventMetaBoxOrder' ] );
//        remove_action ('wp_head', 'rsd_link');
    }

    /**
     * Prepend theme current Theme Version into the admin footer of WP for quick reference.
     *
     * @return string
     */
    public function printThemeVersion() {
        return sprintf(
            '<span id="footer-thankyou">%1$s v%2$s</span>',
            wp_get_theme()->name,
            REACH_THEME_VERSION
        );
    }

    /**
     * Registers nav menu locations.
     */
    public function registerMenus() {
        // get site options
        $options = SiteOptions::getSiteOptions();

        // check if we have any navigation menus turned on
        $navigation = ! empty( $options['navigation'] ) ? $options['navigation'] : [];
        $locations  = ThemeMenus::getThemeMenuLocations();

        // always register our primary navigation menu
        register_nav_menu( 'primary', __( 'Primary', 'reach' ) );

        // loop through navigation menus and register their location
        foreach ( $navigation as $menu ) {
            if ( ! array_key_exists( $menu, $locations ) ) {
                continue;
            }
            register_nav_menu( $menu, $locations[ $menu ] );
        }
    }

    public function removeXMLRPC(){
        $enableXMLRPC = (bool) get_option('rl_enable_xmlrpc', false);
        // default we want to remove the link
        // unless someone wants to keep it
        if(!$enableXMLRPC) {
            remove_action ('wp_head', 'rsd_link');
        }
    }

    public function removeLiveWriter(){
        $enableLiveWriter = (bool) get_option('rl_enable_live_writer', false);
        // default we want to remove the link
        // unless someone wants to keep it
        if(!$enableLiveWriter) {
            remove_action('wp_head', 'wlwmanifest_link');
        }
    }
    //remove select head links to improve Google Core Vitals
    public function removeRss() {
        $enableRss = (bool) get_option('rl_enable_rss', false);
        // remove the rss link from the head by default unless desired
        if(!$enableRss) {
            remove_action( 'wp_head', 'feed_links', 2 );
            remove_action( 'wp_head', 'feed_links_extra', 3 );
        }
    }

    public function removeEmoji() {
        $enableEmoji = (bool) get_option('rl_enable_emoji', false);
        // remove the emoji link and styles from the head by default unless desired
        if(!$enableEmoji) {
            remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
            remove_action( 'wp_print_styles', 'print_emoji_styles' );
        }
    }

    /**
     * Output our favicon markup in the header
     */
    public function outputSiteFavicons() {
        $assets_dir = AD_THEME_DIR_URI . '/assets/images/favicon/';

        if(empty(get_site_icon_url(192))){
            $icon_url = $assets_dir . 'favicon.ico';
            $andriod_url = $assets_dir . 'android-chrome-192x192.png';
        } else {
            $icon_url = get_site_icon_url(192);
            $andriod_url = get_site_icon_url(192);
        }
        ?>
        <link rel="shortcut icon" href="<?php echo $icon_url; ?> " type="image/x-icon"/>
        <?php
    }

    public function get_touch_icon($size){
        return $this->icon_link($size, 'apple-touch-icon', "apple-touch-icon-");
    }

    public function get_favicon($size){
        return  $this->icon_link($size, 'icon', "favicon-");
//        return "{$path}favicon-{$size}x{$size}.png";
    }

    /**
     * @param $size
     * @param $icon_type
     * @param $icon_name
     * @return string
     */
    protected function icon_link($size, $icon_type, $icon_name) {
        $icon_path = get_site_icon_url($size);
        $assets_dir = AD_THEME_DIR_URI . '/assets/images/favicon/';
        if (empty($icon_path)) {
            $icon_path = "{$assets_dir}{$icon_name}{$size}x{$size}.png";
        }
        return "<link rel=\"$icon_type\" sizes=\"{$size}x{$size}\" href=\"{$icon_path}\">";
    }

    /**
     * Check for a GA ID set in the Site Options
     * If set, output the proper Google Analytics tracking code in the head
     *
     * @return bool
     */
    public function maybeOutputGoogleAnalytics() {
        // get site options
        $options = SiteOptions::getSiteOptions();

        // check for GA tracking ID
        $tracking_id = ! empty( $options['google_analytics_id'] ) ? esc_attr( $options['google_analytics_id'] ) : false;
        if ( ! $tracking_id ) {
            return false;
        }
        ?>
        <!-- Global Site Tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $tracking_id; ?>"></script>
        <script>
          window.dataLayer = window.dataLayer || [];

          function gtag() {
            dataLayer.push(arguments)
          };
          gtag('js', new Date());

          gtag('config', '<?php echo $tracking_id; ?>');
        </script>
        <?php
        return true;
    }

    /**
     * Prevents meta box order from being saved
     *
     * @param $action
     */
    function preventMetaBoxOrder( $action ) {
        if ( 'meta-box-order' == $action ) {
            die( '-1' );
        }
    }

}
