<?php
declare(strict_types=1);


/**
 * Plugin Lifecycle Handler
 *
 * @package ProRank\Core
 */

namespace ProRank\SEO\Core;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * Handles plugin activation, deactivation, and uninstall
 */


class Lifecycle {
    
    /**
     * Handle plugin activation
     *
     * @return void
     */
    public static function activate(): void {
        // Set activation flag
        update_option('prorank_activated', time());
        
        // Set default options
        self::set_default_options();
        
        // Create database tables
        self::create_tables();
        
        // Initialize plugin to register CPTs
        $plugin = \ProRank\SEO\Plugin::get_instance();
        $plugin->init();
        
        // Don't trigger init action during activation - it causes conflicts
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }
    
    /**
     * Handle plugin deactivation
     *
     * @return void
     */
    public static function deactivate(): void {
        // Flush rewrite rules
        flush_rewrite_rules();
    }
    
    /**
     * Handle plugin uninstall
     *
     * @return void
     */
    public static function uninstall(): void {
        // Only run if explicitly uninstalling
        if (!defined('WP_UNINSTALL_PLUGIN')) {
            return;
        }
        
        // Remove all plugin data
        self::remove_options();
        self::remove_user_meta();
        self::remove_post_meta();
        self::remove_snapshots();
        self::drop_tables();
    }
    
    /**
     * Set default options
     */
    private static function set_default_options(): void {
        $defaults = [
            'prorank_settings' => [],
            'prorank_db_version' => '1.0.0',
        ];
        
        foreach ($defaults as $option => $value) {
            if (false === get_option($option)) {
                update_option($option, $value);
            }
        }
    }
    
    /**
     * Remove options
     */
    private static function remove_options(): void {
        $options = [
            'prorank_settings',
            'prorank_db_version',
            'prorank_activated',
            'prorank_license_key',
            'prorank_license_status',
        ];
        
        foreach ( $options as $option ) {
            delete_option( $option );
        }
    }
    
    /**
     * Remove user meta
     */
    private static function remove_user_meta(): void {
        global $wpdb;
        
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->usermeta} 
                 WHERE meta_key LIKE %s",
                'prorank_%'
            )
        );
    }
    
    /**
     * Remove post meta
     */
    private static function remove_post_meta(): void {
        global $wpdb;
        
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->postmeta} 
                 WHERE meta_key LIKE %s",
                '_prorank_%'
            )
        );
    }
    
    /**
     * Remove settings snapshots
     */
    private static function remove_snapshots(): void {
        global $wpdb;
        
        // Delete all snapshot options
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} 
                 WHERE option_name LIKE %s",
                '_prorank_settings_snapshot_%'
            )
        );
        
        // Delete snapshot index
        delete_option('_prorank_settings_snapshots');
    }
    
    /**
     * Create database tables
     *
     * @return void
     */
    private static function create_tables(): void {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // PSI History table
        $psi_history_table = $wpdb->prefix . 'prorank_psi_history';
        $psi_history_sql = "CREATE TABLE IF NOT EXISTS {$psi_history_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            url varchar(255) NOT NULL,
            timestamp datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            strategy varchar(10) NOT NULL DEFAULT 'mobile',
            lcp decimal(10,2) DEFAULT NULL,
            inp decimal(10,2) DEFAULT NULL,
            cls decimal(10,4) DEFAULT NULL,
            tbt decimal(10,2) DEFAULT NULL,
            fcp decimal(10,2) DEFAULT NULL,
            ttfb decimal(10,2) DEFAULT NULL,
            speed_index decimal(10,2) DEFAULT NULL,
            performance_score int(3) DEFAULT NULL,
            error_message text DEFAULT NULL,
            PRIMARY KEY (id),
            KEY url (url),
            KEY timestamp (timestamp),
            KEY strategy (strategy),
            KEY url_strategy_timestamp (url, strategy, timestamp)
        ) $charset_collate;";
        
        // Execute table creation
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($psi_history_sql);
        
        // Voice Search Analytics table
        $voice_analytics_table = $wpdb->prefix . 'prorank_voice_analytics';
        $voice_analytics_sql = "CREATE TABLE IF NOT EXISTS {$voice_analytics_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            total_queries int(11) NOT NULL DEFAULT 0,
            voice_queries int(11) NOT NULL DEFAULT 0,
            voice_percentage decimal(5,2) NOT NULL DEFAULT 0,
            voice_clicks int(11) NOT NULL DEFAULT 0,
            voice_impressions int(11) NOT NULL DEFAULT 0,
            voice_ctr decimal(5,2) NOT NULL DEFAULT 0,
            pattern_data longtext,
            PRIMARY KEY (id),
            KEY date_idx (date)
        ) $charset_collate;";
        
        dbDelta($voice_analytics_sql);
        
        // Content Library tables
        if (class_exists('\\ProRank\\SEO\\Database\\Schema\\ContentLibrarySchema')) {
            \ProRank\SEO\Database\Schema\ContentLibrarySchema::create_tables();
        }
        
        // Audit Log table
        $audit_log_table = $wpdb->prefix . 'prorank_audit_log';
        $audit_log_sql = "CREATE TABLE IF NOT EXISTS {$audit_log_table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            timestamp datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            user_id bigint(20) unsigned NOT NULL DEFAULT 0,
            action varchar(50) NOT NULL,
            object_type varchar(50) NOT NULL,
            object_id bigint(20) unsigned NOT NULL DEFAULT 0,
            meta_json longtext,
            PRIMARY KEY (id),
            KEY user_id (user_id),
            KEY action (action),
            KEY object_type (object_type),
            KEY timestamp (timestamp),
            KEY user_action_timestamp (user_id, action, timestamp)
        ) $charset_collate;";
        
        dbDelta($audit_log_sql);
        
        // Audit tables removed - audits now run on external ProRank.io servers
        // Clean up old audit tables if they exist during upgrade
        self::cleanup_old_audit_tables();
        
        // Create roadmap tables
        require_once dirname(__DIR__) . '/Database/RoadmapTableInstaller.php';
        \ProRank\SEO\Database\RoadmapTableInstaller::install();
        
        // Create redirect and 404 monitoring tables
        require_once dirname(__DIR__) . '/Database/RedirectsTableInstaller.php';
        \ProRank\SEO\Database\RedirectsTableInstaller::install();
        
        // Update database version
        update_option('prorank_db_version', '1.5.0');
    }
    
    /**
     * Drop database tables
     *
     * @return void
     */
    private static function drop_tables(): void {
        global $wpdb;
        
        $tables = [
            $wpdb->prefix . 'prorank_psi_history',
            $wpdb->prefix . 'prorank_voice_analytics',
            $wpdb->prefix . 'prorank_audit_log',
            $wpdb->prefix . 'prorank_roadmap_items',
            // Content Library tables
            $wpdb->prefix . 'prorank_ai_content_library',
            $wpdb->prefix . 'prorank_ai_templates',
            $wpdb->prefix . 'prorank_ai_generation_history',
            // Old audit tables - no longer needed
            $wpdb->prefix . 'prorank_audits',
            $wpdb->prefix . 'prorank_audit_urls',
            $wpdb->prefix . 'prorank_audit_issues',
        ];
        
        foreach ($tables as $table) {
            $wpdb->query("DROP TABLE IF EXISTS {$table}");
        }
        
        // Drop roadmap tables using installer
        require_once dirname(__DIR__) . '/Database/RoadmapTableInstaller.php';
        \ProRank\SEO\Database\RoadmapTableInstaller::uninstall();
        
        // Drop redirect tables using installer
        require_once dirname(__DIR__) . '/Database/RedirectsTableInstaller.php';
        \ProRank\SEO\Database\RedirectsTableInstaller::uninstall();
    }
    
    /**
     * Clean up old audit tables during upgrade
     *
     * @return void
     */
    private static function cleanup_old_audit_tables(): void {
        global $wpdb;
        
        $old_tables = [
            $wpdb->prefix . 'prorank_audits',
            $wpdb->prefix . 'prorank_audit_urls',
            $wpdb->prefix . 'prorank_audit_issues',
        ];
        
        foreach ($old_tables as $table) {
            $wpdb->query("DROP TABLE IF EXISTS {$table}");
        }
        
        // Clean up old audit options
        $old_options = [
            'prorank_site_audit_running',
            'prorank_site_audit_current_id',
            'prorank_site_audit_offset',
            'prorank_site_audit_total_posts',
            'prorank_site_audit_processed_posts',
            'prorank_site_audit_start_time',
            'prorank_site_audit_last_error',
            'prorank_audit_state',
            'prorank_audit_id',
            'prorank_audit_current_id',
            'prorank_audit_start_time',
        ];
        
        foreach ($old_options as $option) {
            delete_option($option);
        }
    }
}
