<?php
/**
 * Prohibit direct script loading
 */
defined('ABSPATH') || die('No direct script access allowed!');

/**
 * Class MetaSeoAddonSite
 * Class that holds most of the frontend functionality for Meta SEO Addon.
 */
class MetaSeoAddonSite
{
    /**
     * Google Tag Manager settings
     *
     * @var array
     */
    public $ga_tracking = array();

    /**
     * Google Tag Manager settings
     *
     * @var array
     */
    public $gaDisconnect = array();

    /**
     * Google Tag Manager settings
     *
     * @var array
     */
    public $google_tagmanager = array();

    /**
     * MetaSeoAddonSite constructor.
     */
    public function __construct()
    {
        $this->ga_tracking = array(
            'wpmsga_dash_tracking' => 1,
            'wpmsga_dash_tracking_type' => 'universal',
            'wpmsga_dash_anonim' => 0,
            'wpmsga_dash_remarketing' => 0,
            'wpmsga_event_tracking' => 0,
            'wpmsga_event_downloads' => 'zip|mp3*|mpe*g|pdf|docx*|pptx*|xlsx*|rar*',
            'wpmsga_aff_tracking' => 0,
            'wpmsga_event_affiliates' => '/out/',
            'wpmsga_hash_tracking' => 0,
            'wpmsga_author_dimindex' => 0,
            'wpmsga_pubyear_dimindex' => 0,
            'wpmsga_category_dimindex' => 0,
            'wpmsga_user_dimindex' => 0,
            'wpmsga_tag_dimindex' => 0,
            'wpmsga_speed_samplerate' => 1,
            'wpmsga_event_bouncerate' => 0,
            'wpmsga_enhanced_links' => 0,
            'wpmsga_dash_adsense' => 0,
            'wpmsga_crossdomain_tracking' => 0,
            'wpmsga_crossdomain_list' => '',
            'wpmsga_cookiedomain' => '',
            'wpmsga_cookiename' => '',
            'wpmsga_cookieexpires' => '',
            'wpmsga_track_exclude' => array(),
        );

        $ga_tracking = get_option('_metaseo_ggtracking_settings');
        if (is_array($ga_tracking)) {
            $this->ga_tracking = array_merge($this->ga_tracking, $ga_tracking);
        }

        $this->gaDisconnect = array(
            'wpms_gg_service_tracking_id' => '',
            'wpms_gg_service_tracking_type' => 'universal',
            'wpmsga_code_tracking' => '',
            'wpmstm_header_code_tracking' => '',
            'wpmstm_body_code_tracking' => ''
        );

        $this->google_tagmanager = array(
            'list_accounts' => array(),
            'list_containers' => array(),
            'selected_account' => '',
            'selected_container' => ''
        );

        $gg_tagmanager = get_option('wpms_tagmanager_setting');
        if (is_array($gg_tagmanager)) {
            $this->google_tagmanager = array_merge($this->google_tagmanager, $gg_tagmanager);
        }
        $gaDisconnect = get_option('_metaseo_ggtracking_disconnect_settings');
        if (is_array($gaDisconnect)) {
            $this->gaDisconnect = array_merge($this->gaDisconnect, $gaDisconnect);
        }

        add_action('wp_head', array($this, 'trackingCode'), 99);
        add_action('wp_head', array($this, 'wpmsGgDisconnectTrackingHeader'), 99);
        add_action('wp_body_open', array($this, 'wpmsGgDisconnectTrackingBody'), 99);
        add_action('wp_footer', array($this, 'loadSchema'), 1);
    }

    /**
     * Create tracking code on front-end
     *
     * @return boolean
     */
    public function trackingCode()
    {
        if (WpmsGaTools::checkRoles($this->ga_tracking['wpmsga_track_exclude'], true)) {
            return false;
        }

        $google_alanytics = get_option('wpms_google_alanytics');
        $traking_mode = $this->ga_tracking['wpmsga_dash_tracking'];

        // If enabled tracking option
        if ($traking_mode > 0) {
            // If have tracking-id then WPMS tracking data
            if (!empty($google_alanytics['tableid_jail'])) {
                // Get selected profile
                $profile_info = WpmsGaTools::getSelectedProfile(
                    $google_alanytics['profile_list'],
                    $google_alanytics['tableid_jail']
                );

                // Add google analytics tag to website
                if (!isset($profile_info[4])) {
                    return false;
                }
                if ($profile_info[4] === 'UA') {
                    $traking_type = $this->ga_tracking['wpmsga_dash_tracking_type'];
                    if ($traking_type === 'classic') {
                        echo "\n<!-- Classic Tracking - https://wordpress.org/plugins/wp-meta-seo/ -->\n";
                        if ($this->ga_tracking['wpmsga_event_tracking']) {
                            require_once 'google_analytics/tracking/events-classic.php';
                        }
                        require_once 'google_analytics/tracking/code-classic.php';
                        echo "\n<!-- END wpmsProGA Classic Tracking -->\n\n";
                    } elseif ($traking_type === 'universal') {
                        echo "\n<!-- Universal Tracking - https://wordpress.org/plugins/wp-meta-seo/ -->\n";
                        if ($this->ga_tracking['wpmsga_event_tracking']
                            || $this->ga_tracking['wpmsga_aff_tracking']
                            || $this->ga_tracking['wpmsga_hash_tracking']) {
                            require_once 'google_analytics/tracking/events-universal.php';
                        }
                        require_once 'google_analytics/tracking/code-universal.php';
                        echo "\n<!-- END wpmsProGA Universal Tracking -->\n\n";
                    } else {
                        return false;
                    }
                } else {
                    echo "\n<!-- wpmsProGA Google Analytics 4 Tracking - https://wordpress.org/plugins/wp-meta-seo/ -->\n";
                    if ($this->ga_tracking['wpmsga_event_tracking']
                        || $this->ga_tracking['wpmsga_aff_tracking'] || $this->ga_tracking['wpmsga_hash_tracking']) {
                        // Add tag for both Universal and Google analytics 4 property
                        echo "\n<!-- Events tracking -->\n\n";
                        require_once 'google_analytics/tracking/events-ga4.php';
                        echo "\n<!-- End events tracking -->\n\n";
                    }
                    require_once 'google_analytics/tracking/code-ga4.php';
                    echo "\n<!-- END wpmsProGA Google Analytics 4 Tracking -->\n\n";
                }
            }
        }
        return true;
    }

    /**
     * Add Google service analytics and tag manager tracking code to header website
     *
     * @return void
     */
    public function wpmsGgDisconnectTrackingHeader()
    {
        $head_tracking_codes = get_option('wpms_tracking_list');
        if (empty($head_tracking_codes) || !is_array($head_tracking_codes)) {
            return;
        }
        foreach ($head_tracking_codes as $key => $tracking) {
            switch ($tracking['tracking_type']) {
                case 'analytics4':
                    $measurement_id = $tracking['tracking_identifier'];
                    require 'google_analytics/tracking/ga4_disconnect.php';
                    break;
                case 'tagmanager':
                    $measurement_id = $tracking['tracking_identifier'];
                    require 'google-tag-manager/tracking/gtm-header.php';
                    break;
                case 'analytics4_custom':
                case 'tagmanager_custom':
                case 'other_custom':
                    if ($tracking['tracking_insert_in_head']) {
                        echo htmlspecialchars_decode(htmlspecialchars_decode($tracking['tracking_head_code'])); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Add Google Tag Manager to body website
     *
     * @return void
     */
    public function wpmsGgDisconnectTrackingBody()
    {
        $head_tracking_codes = get_option('wpms_tracking_list');
        if (empty($head_tracking_codes) || !is_array($head_tracking_codes)) {
            return;
        }
        foreach ($head_tracking_codes as $key => $tracking) {
            switch ($tracking['tracking_type']) {
                case 'tagmanager_custom':
                    // fall-through
                case 'other_custom':
                    if ($tracking['tracking_insert_in_body']) {
                        echo htmlspecialchars_decode(htmlspecialchars_decode($tracking['tracking_body_code'])); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Get json encode
     *
     * @param array $data Data list
     *
     * @return null|string
     */
    public function getJsonEncode($data = array())
    {
        $html = null;
        if (!empty($data) && is_array($data)) {
            $html .= '<script type="application/ld+json">';
            // phpcs:ignore PHPCompatibility.Constants.NewConstants.json_pretty_printFound, PHPCompatibility.Constants.NewConstants.json_unescaped_slashesFound, PHPCompatibility.Constants.NewConstants.json_unescaped_unicodeFound -- Wrong business structure data
            $html .= json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $html .= '</script>';
        }

        return $html;
    }

    /**
     * Sanitize outPut
     *
     * @param string $value Value
     * @param string $type  Element type
     *
     * @return mixed|null|string
     */
    public function sanitizeOutPut($value, $type = 'text')
    {
        $newValue = null;
        if ($value) {
            if ($type === 'text') {
                $newValue = esc_html(stripslashes($value));
            } elseif ($type === 'url') {
                $newValue = esc_url(stripslashes($value));
            } elseif ($type === 'textarea') {
                $newValue = esc_textarea(stripslashes($value));
            } else {
                $newValue = esc_html(stripslashes($value));
            }
        }

        return $newValue;
    }

    /**
     * Load local business
     *
     * @return void
     */
    public function loadSchema()
    {
        $html = null;
        // get all local business settings
        $opts = array(
            'enable' => 0,
            'logo' => '',
            'type_name' => '',
            'country' => '',
            'address' => '',
            'city' => '',
            'state' => '',
            'phone' => '',
            'site_image' => '',
            'pricerange' => '$$'
        );

        $business = get_option('wpms_local_business');
        if (is_array($business)) {
            $opts = array_merge($opts, $business);
        }

        if ((int)$opts['enable'] === 1) {
            if (is_home() || is_front_page()) {
                $metaData = array();
                $metaData['@context'] = 'http://schema.org/';
                $metaData['@type'] = 'WebSite';
                $metaData['url'] = get_home_url();
                $metaData['potentialAction'] = array(
                    '@type' => 'SearchAction',
                    'target' => get_home_url() . '/?s={query}',
                    'query-input' => 'required name=query'
                );
                $html .= $this->getJsonEncode($metaData);
            }
            $webMeta = array();
            $webMeta['@context'] = 'http://schema.org';
            $siteType = 'LocalBusiness';
            $webMeta['@type'] = $siteType;

            $imgID = absint($opts['site_image']);
            if (!empty($opts['site_image']) && $imgID) {
                $image_url = wp_get_attachment_url($imgID);
                $webMeta['image'] = $this->sanitizeOutPut($image_url, 'url');
            } else {
                $webMeta['image'] = null;
            }

            $webMeta['priceRange'] = !empty($opts['pricerange']) ? $this->sanitizeOutPut($opts['pricerange']) : null;
            $webMeta['telephone'] = !empty($opts['phone']) ? $this->sanitizeOutPut($opts['phone']) : null;

            $sitename = get_bloginfo('name');
            $webMeta['name'] = !empty($opts['type_name']) ? $this->sanitizeOutPut($opts['type_name']) : $sitename;

            $imgID = absint($opts['logo']);
            if (!empty($opts['logo']) && $imgID) {
                $image_url = wp_get_attachment_url($imgID);
                $webMeta['image'] = $this->sanitizeOutPut($image_url, 'url');
            } else {
                $webMeta['image'] = null;
            }

            if (!empty($opts['web_url'])) {
                $webMeta['url'] = $this->sanitizeOutPut($opts['web_url'], 'url');
            } else {
                $webMeta['url'] = $this->sanitizeOutPut(get_home_url(), 'url');
            }

            if (!empty($opts['social']) && is_array($opts['social'])) {
                $link = array();
                foreach ($opts['social'] as $socialD) {
                    if ($socialD['link']) {
                        $link[] = $socialD['link'];
                    }
                }
                if (!empty($link)) {
                    $webMeta['sameAs'] = $link;
                }
            }

            $webMeta['address'] = array(
                '@type' => 'PostalAddress',
                'addressCountry' => !empty($opts['country']) ? $this->sanitizeOutPut($opts['country']) : null,
                'addressLocality' => !empty($opts['city']) ? $this->sanitizeOutPut($opts['city']) : null,
                'addressRegion' => !empty($opts['state']) ? $this->sanitizeOutPut($opts['state']) : null,
                'streetAddress' => !empty($opts['address']) ? $this->sanitizeOutPut($opts['address']) : null
            );

            if ($webMeta['@type']) {
                $html .= $this->getJsonEncode($webMeta);
            }

            // phpcs:ignore WordPress.Security.EscapeOutput -- Content escaped in the method sanitizeOutPut
            echo $html;
        }
    }
}
