<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Gerencia os presets de serviços globais do Hub e sua criação.
 * CORRIGIDO: Títulos e descrições agora são traduzíveis.
 */
class WPCM_Hub_Service_Presets {

    /**
     * Retorna a lista de todos os presets disponíveis.
     */
    public static function get_all_presets() {
        return array(
            'google_analytics' => array(
                'title'       => __( 'Google Analytics / GTM', 'wpcm-agency-hub' ),
                'category'    => 'analytics',
                'description' => __( 'Used to analyze website traffic and user behavior.', 'wpcm-agency-hub' ),
                'keywords'    => "google-analytics.com\ngoogletagmanager.com\ngtm.js\nanalytics.js",
                'scripts'     => "",
            ),
            'meta_pixel' => array(
                'title'       => __( 'Meta (Facebook) Pixel', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track conversions and build audiences for Meta ads.', 'wpcm-agency-hub' ),
                'keywords'    => "connect.facebook.net\nfbevents.js",
                'scripts'     => "",
            ),
            'google_ads' => array(
                 'title'       => __( 'Google Ads (Conversion Linker)', 'wpcm-agency-hub' ),
                 'category'    => 'marketing',
                 'description' => __( 'Used to track conversions from Google Ads.', 'wpcm-agency-hub' ),
                 'keywords'    => "googleadservices.com\nconversion_async.js",
                 'scripts'     => "",
            ),
            'youtube_vimeo' => array(
                'title'       => __( 'YouTube / Vimeo Embeds', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Allows embedded videos from YouTube and Vimeo to load.', 'wpcm-agency-hub' ),
                'keywords'    => "youtube.com\nyoutube-nocookie.com\nvimeo.com\nplayer.vimeo.com",
                'scripts'     => "", 
            ),
            'tiktok_pixel' => array(
                'title'       => __( 'TikTok Pixel', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track visitor actions for TikTok advertising.', 'wpcm-agency-hub' ),
                'keywords'    => "analytics.tiktok.com\ntiktok.com",
                'scripts'     => "",
            ),
            'linkedin' => array(
                'title'       => __( 'LinkedIn Insight Tag', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track conversions and build audiences for LinkedIn ads.', 'wpcm-agency-hub' ),
                'keywords'    => "snap.licdn.com\nli.lms-analytics\ninsight.min.js",
                'scripts'     => "",
            ),
            'microsoft_ads' => array(
                'title'       => __( 'Microsoft (Bing) Ads', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track conversions for Microsoft Advertising (Bing).', 'wpcm-agency-hub' ),
                'keywords'    => "bat.bing.com\nbat.js\nuet.js",
                'scripts'     => "",
            ),
            'x_twitter' => array(
                'title'       => __( 'X (Twitter) Pixel', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track conversions and build audiences for X ads.', 'wpcm-agency-hub' ),
                'keywords'    => "static.ads-twitter.com\ntwq.js",
                'scripts'     => "",
            ),
            'pinterest' => array(
                'title'       => __( 'Pinterest Tag', 'wpcm-agency-hub' ),
                'category'    => 'marketing',
                'description' => __( 'Used to track conversions and build audiences for Pinterest ads.', 'wpcm-agency-hub' ),
                'keywords'    => "ads.pinterest.com\npinit.js",
                'scripts'     => "",
            ),
            'hotjar' => array(
                'title'       => __( 'Hotjar', 'wpcm-agency-hub' ),
                'category'    => 'analytics',
                'description' => __( 'Used for heatmaps, session recordings, and user behavior analytics.', 'wpcm-agency-hub' ),
                'keywords'    => "static.hotjar.com\nhotjar.js",
                'scripts'     => "",
            ),
        );
    }

    /**
     * Cria TODOS os presets, definindo o status como 'publish' ou 'draft'
     *
     * @param array $selected_keys Lista de chaves dos presets a serem 'Publicados'.
     */
    public static function create_all_presets_from_wizard( $selected_keys ) {
        $all_presets = self::get_all_presets();

        foreach ( $all_presets as $key => $preset ) {
            // Se o serviço já existe (de uma instalação anterior), pula
            // Usamos o 'title' (que é traduzível) como o identificador único
            if ( self::service_exists( $preset['title'] ) ) {
                continue;
            }

            // Determina o status: 'publish' se foi selecionado, 'draft' se não foi
            $post_status = in_array( $key, $selected_keys ) ? 'publish' : 'draft';

            $post_data = array(
                'post_title'  => $preset['title'], // O título agora vem da função __()
                'post_type'   => 'wpcm_hub_service', // CPT do Hub
                'post_status' => $post_status,      // 'publish' ou 'draft'
            );

            $post_id = wp_insert_post( $post_data );

            if ( ! is_wp_error( $post_id ) ) {
                update_post_meta( $post_id, '_wpcm_category', $preset['category'] );
                update_post_meta( $post_id, '_wpcm_description', $preset['description'] ); // A descrição tbm vem da função __()
                update_post_meta( $post_id, '_wpcm_keywords', $preset['keywords'] );
                update_post_meta( $post_id, '_wpcm_scripts', $preset['scripts'] );
            }
        }
    }


    /**
     * (Função antiga - não é mais usada pelo Wizard)
     */
    public static function create_services_from_presets( $preset_keys ) {
        // ... (código antigo sem alterações) ...
    }

    /**
     * Verifica se um serviço global com o título dado já existe.
     */
    private static function service_exists( $title ) {
        $query = new WP_Query( array(
            'post_type'      => 'wpcm_hub_service', // CPT do Hub
            'post_status'    => 'any', // Verifica em 'publish', 'draft', etc.
            'title'          => $title,
            'posts_per_page' => 1,
            'fields'         => 'ids',
        ) );
        return $query->have_posts();
    }
}