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

if ( ! class_exists( 'WPCM_Hub_Core' ) ) {
    
    class WPCM_Hub_Core {
        
        public function __construct() {
            add_action( 'init', array( $this, 'init_components' ), 0 );
            add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_assets' ) );

            add_action( 'update_option_wpcm_hub_global_settings', array( $this, 'on_global_settings_update' ), 10, 0 );
            add_action( 'save_post_wpcm_hub_service', array( $this, 'on_global_service_update' ), 10, 2 );
            add_action( 'save_post_wpcm_hub_profile', array( $this, 'on_profile_update' ), 10, 2 );
            add_action( 'save_post_wpcm_hub_site', array( $this, 'on_site_update' ), 10, 2 );
            add_action( 'delete_post', array( $this, 'on_post_delete' ), 10, 1 );
            add_action( 'wpcm_hub_daily_log_cleanup', array( $this, 'run_hub_log_cleanup' ) );
        }

        public function init_components() {
            new WPCM_Hub_API();
            new WPCM_Hub_CPT_Sites();
            new WPCM_Hub_CPT_Services_Global();
            new WPCM_Hub_CPT_Profiles(); 
            new WPCM_Hub_Settings();
            new WPCM_Hub_Setup_Wizard();
            new WPCM_Hub_Ajax_Handler();
            new WPCM_Hub_Log_Dashboard();
            new WPCM_Hub_Job_Runner();
            new WPCM_Hub_Help_Page();
        }

        public function load_admin_assets( $hook_suffix ) {
            $screen = get_current_screen();

            $is_settings_page = ( $hook_suffix === 'wpcm_hub_site_page_wpcm_hub_settings' );
            $is_services_page = ( $hook_suffix === 'edit.php' && $screen && $screen->post_type === 'wpcm_hub_service' );
            $is_profile_page = ( ($hook_suffix === 'post.php' || $hook_suffix === 'post-new.php') && $screen && $screen->post_type === 'wpcm_hub_profile' );
            
            $is_site_page = ( ($hook_suffix === 'post.php' || $hook_suffix === 'post-new.php') && $screen && $screen->post_type === 'wpcm_hub_site' );

            if ( $is_settings_page || $is_services_page || $is_profile_page || $is_site_page ) {
                wp_enqueue_script( 
                    'wpcm-hub-admin-script', 
                    WPCM_HUB_URL . 'assets/js/admin-legacy.js',
                    array( 'jquery', 'wp-color-picker' ), 
                    WPCM_HUB_VERSION, 
                    true 
                );
                wp_localize_script(
                    'wpcm-hub-admin-script',
                    'wpcm_hub_admin',
                    array(
                        'ajax_url' => admin_url( 'admin-ajax.php' ),
                        'sync_nonce' => wp_create_nonce( 'wpcm_hub_sync_nonce' ),
                    )
                );
            }
            
            if ( $is_profile_page || $is_settings_page ) {
                 wp_enqueue_style( 'wp-color-picker' );
            }

            $is_log_dashboard = ( $hook_suffix === 'wpcm_hub_site_page_wpcm_hub_logs' );
            if ( $is_log_dashboard ) {
                wp_enqueue_script( 'chart-js', WPCM_HUB_URL . 'assets/js/chart.min.js', array(), '3.9.1', true );
                
                wp_enqueue_style( 'wpcm-hub-dashboard-style', WPCM_HUB_URL . 'assets/css/admin-dashboard.css', array(), WPCM_HUB_VERSION );
                wp_enqueue_script( 'wpcm-hub-dashboard-script', WPCM_HUB_URL . 'assets/js/admin-dashboard.js', array( 'jquery', 'chart-js' ), WPCM_HUB_VERSION, true );
                wp_localize_script( 'wpcm-hub-dashboard-script', 'wpcm_hub_dashboard', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce'    => wp_create_nonce( 'wpcm_hub_chart_nonce' ) ) );
            }

            $is_help_page = ( $hook_suffix === 'wpcm_hub_site_page_wpcm_hub_help' );
            if ( $is_help_page ) {
                wp_enqueue_style( 'wpcm-hub-help-style', WPCM_HUB_URL . 'assets/css/admin-help.css', array(), WPCM_HUB_VERSION );
            }
        }

        public function on_global_settings_update() { WPCM_Hub_Job_Scheduler::schedule_global_sync(); }
        public function on_global_service_update( $post_id, $post ) {
            if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) return;
            if ( $post->post_status != 'publish' ) return;
            WPCM_Hub_Job_Scheduler::schedule_global_sync();
        }
        public function on_profile_update( $post_id, $post ) {
            if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) return;
            if ( $post->post_status != 'publish' ) return;
            WPCM_Hub_Job_Scheduler::schedule_sync_for_profile( $post_id );
        }
        public function on_site_update( $post_id, $post ) {
            if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) return;
            if ( $post->post_status != 'publish' ) return;
            WPCM_Hub_Job_Scheduler::schedule_sync_for_site( $post_id );
        }
        public function on_post_delete( $post_id ) {
            $post_type = get_post_type( $post_id );
            $valid_post_types = array('wpcm_hub_service', 'wpcm_hub_profile');
            if ( in_array( $post_type, $valid_post_types) ) {
                WPCM_Hub_Job_Scheduler::schedule_global_sync();
            }
        }
        
        public function run_hub_log_cleanup() {
            $options = get_option( 'wpcm_hub_global_settings' );
            if ( !is_array($options) ) $options = array();
            $period = $options['hub_log_retention_period'] ?? '12';
            if ( empty( $period ) || $period === '0' ) { return; }
            
            global $wpdb;
            $table_name = $wpdb->prefix . 'wpcm_hub_logs';
            
            $sql = "DELETE FROM $table_name WHERE timestamp < DATE_SUB( NOW(), INTERVAL %d MONTH )";

            // CORREÇÃO: Flags completas para cobrir NotPrepared e Interpolated
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $wpdb->query( 
                $wpdb->prepare( 
                    $sql, 
                    intval( $period ) 
                ) 
            );
        }
        
        public static function activate() {
            global $wpdb;
            $charset_collate = $wpdb->get_charset_collate();
            $table_name = $wpdb->prefix . 'wpcm_hub_logs';
            
            $sql = "CREATE TABLE $table_name (
                id BIGINT(20) NOT NULL AUTO_INCREMENT,
                site_post_id BIGINT(20) NOT NULL,
                client_log_id BIGINT(20) NOT NULL,
                user_hash VARCHAR(64) NOT NULL,
                timestamp DATETIME NOT NULL,
                consent_categories VARCHAR(255) NOT NULL,
                policy_version VARCHAR(20) NOT NULL,
                ip_address VARCHAR(45) NOT NULL DEFAULT '', 
                PRIMARY KEY (id),
                UNIQUE KEY unq_site_client_id (site_post_id, client_log_id),
                INDEX idx_site_post_id (site_post_id),
                INDEX idx_timestamp (timestamp)
            ) $charset_collate;";
            
            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $sql );
            
            set_transient( 'wpcm_activation_redirect', true, 60 );
            if ( ! wp_next_scheduled( 'wpcm_hub_daily_log_cleanup' ) ) {
                wp_schedule_event( time(), 'daily', 'wpcm_hub_daily_log_cleanup' );
            }
            flush_rewrite_rules();
        }
        
        public static function deactivate() {
            wp_clear_scheduled_hook( 'wpcm_hub_daily_log_cleanup' );
            flush_rewrite_rules();
        }
    }
}