<?php

/**
 * Class CT_Ultimate_GDPR_Service_Google_Tag_Manager
 */
class CT_Ultimate_GDPR_Service_Google_Tag_Manager extends CT_Ultimate_GDPR_Service_Abstract {
    /**
     * @return void
     */
    public function init() {}

    /**
     * @return mixed
     */
    public function get_name() {
        return apply_filters( "ct_ultimate_gdpr_service_{$this->get_id()}_name", 'Google Tag Manager' );
    }

    /**
     * @return bool
     */
    public function is_active() {
        return true;
    }

    /**
     * @return bool
     */
    public function is_forgettable() {
        return false;
    }

    /**
     * @throws Exception
     * @return void
     */
    public function forget() {
    }

    /**
     * Collect data of a specific user
     *
     * @return $this
     */
    public function collect() {
        return $this;
    }

    /**
     * @return mixed
     */
    public function front_action() {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_static' ), 1 );
        add_action('wp_head', array( $this, 'head_snippet'), 1);
    }

    private function is_consent_mode_active(){
        $consent_mode = $this->get_admin_controller()->get_option_value( 'cookie_consent_mode', '', $this->front_controller->find_controller('cookie')->get_id() );
        if($consent_mode){
            return true;
        }
        return false;
    }

    public function head_snippet(){

        $id = $this->get_admin_controller()->get_option_value( 'cookie_services_google_tag_manager_gtm_id2', '', $this->front_controller->find_controller('cookie')->get_id() );

        // no ga id was set in option
        if ( ! $id ) {
            return;
        }

        $consentCode = '';

        if($this->is_consent_mode_active()){
            $consentCode = <<<EOT
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
      dataLayer.push(arguments);
    }
    if(localStorage.getItem('consentMode') === null) {
      gtag("consent", "default", {
        ad_personalization: "denied",
        ad_storage: "denied",
        ad_user_data: "denied",
        analytics_storage: "denied",
        functionality_storage: "denied",
        personalization_storage: "denied",
        security_storage: "granted"        
      });
    } else {
      gtag('consent', 'default', JSON.parse(localStorage.getItem('consentMode')));
    }  
  </script>
EOT;
        }

        $html = <<<EOT
    {$consentCode}
    <!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','{$id}');</script>
    <!-- End Google Tag Manager -->
EOT;

        $html = apply_filters('ct_ultimate_gdpr_service_gtm_head_snippet', $html, $id);

        echo $html;
    }

    /**
     *
     */
    public function enqueue_static() {
        if($this->is_consent_mode_active()) {
            wp_enqueue_script(
                'ct-ultimate-gdpr-cookie-consent-mode',
                ct_ultimate_gdpr_url( 'assets/js/consent-mode.js' ),
                array( 'jquery' ),
                ct_ultimate_gdpr_get_plugin_version(),
                false
            );
        }
    }


    /**
     * @return mixed
     */
    public function add_option_fields() {
        add_settings_field(
            "cookie_services_{$this->get_id()}_gtm_id2", // ID
            esc_html__( "Your GTM ID", 'ct-ultimate-gdpr' ), // Title
            array( $this, "render_field_cookie_services_{$this->get_id()}_gtm_id2" ), // Callback
            $this->front_controller->find_controller('cookie')->get_id(), // Page
            'ct-ultimate-gdpr-cookie_tab-1_section-5' // Section
        );

    }

    /**
     *
     */
    public function render_field_cookie_services_google_tag_manager_gtm_id2() {

        $admin = $this->get_admin_controller();

        $field_name = $admin->get_field_name( __FUNCTION__ );
        printf(
            "<input class='ct-ultimate-gdpr-field' type='text' id='%s' name='%s' value='%s' />",
            $admin->get_field_name( __FUNCTION__ ),
            $admin->get_field_name_prefixed( $field_name ),
            $admin->get_option_value_escaped( $field_name )
        );

        echo '<p class="description">';
        echo "Provide your unique Google Tag Manager ID (e.g., GTM-XXXXXX) here. If specified, the plugin will automatically insert the necessary GTM code snippet into the head section of your website's pages. <u>If opting for GTM, there's no need to also enter a GA4 ID.</u>";
        echo '</p>';

    }

}
