<?php

/**
 * LinkCentral Activator Class
 *
 * This class handles the activation and deactivation logic for the plugin.
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
// Include required automation classes
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/automations/cleanup.php';
class LinkCentral_Activator {
    /**
     * Activation logic for a single site.
     * 
     * This method is called:
     * - During regular single-site WordPress activation
     * - For each site during network activation
     * - When activating on a single site within a multisite network
     * - When a new site is added to a network where the plugin is network-activated
     */
    public static function activate() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        // Create stats table
        $stats_table = $wpdb->prefix . 'linkcentral_stats';
        $sql = "CREATE TABLE {$stats_table} (\n            id mediumint(9) NOT NULL AUTO_INCREMENT,\n            link_id mediumint(9) NOT NULL,\n            click_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,\n            referring_url TEXT,\n            user_agent text NOT NULL,\n            visitor_id varchar(36),\n            destination_url TEXT,\n            country varchar(2) DEFAULT '',\n            first_click TINYINT DEFAULT 0,\n            PRIMARY KEY  (id)\n        ) {$charset_collate};";
        dbDelta( $sql );
        // Add database indexes for optimal performance
        self::create_database_indexes( $stats_table );
        // Create the keywords table for auto-keyword linking
        $keywords_table = $wpdb->prefix . 'linkcentral_keywords';
        $keywords_sql = "CREATE TABLE {$keywords_table} (\n            id mediumint(9) NOT NULL AUTO_INCREMENT,\n            link_id mediumint(9) NOT NULL,\n            keyword varchar(255) NOT NULL,\n            density enum('high', 'medium', 'low') NOT NULL DEFAULT 'medium',\n            PRIMARY KEY (id),\n            KEY link_id (link_id),\n            KEY keyword (keyword(50))\n        ) {$charset_collate};";
        dbDelta( $keywords_sql );
        // Get current version and determine if this is a first installation
        $current_version = get_option( 'linkcentral_db_version' );
        $is_first_installation = $current_version === false;
        // Set default options if they don't exist
        $default_options = array(
            'linkcentral_url_prefix'                            => 'go',
            'linkcentral_case_sensitive_redirects'              => false,
            'linkcentral_excluded_ips'                          => '',
            'linkcentral_excluded_roles'                        => array(),
            'linkcentral_disable_reporting'                     => false,
            'linkcentral_enable_data_expiry'                    => false,
            'linkcentral_data_expiry_days'                      => 90,
            'linkcentral_global_nofollow'                       => true,
            'linkcentral_global_sponsored'                      => false,
            'linkcentral_global_redirection_type'               => '307',
            'linkcentral_global_parameter_forwarding'           => false,
            'linkcentral_exclude_bots'                          => false,
            'linkcentral_track_user_agent'                      => true,
            'linkcentral_delete_tracking_data_on_link_deletion' => true,
            'linkcentral_enable_ga'                             => false,
            'linkcentral_ga_measurement_id'                     => '',
            'linkcentral_ga_api_secret'                         => '',
            'linkcentral_track_unique_visitors'                 => true,
            'linkcentral_default_link_insertion_type'           => 'synchronized',
        );
        foreach ( $default_options as $option_name => $default_value ) {
            if ( get_option( $option_name ) === false ) {
                add_option( $option_name, $default_value );
            }
        }
        // Add custom capabilities
        self::add_linkcentral_capabilities( $is_first_installation );
        // Schedule events
        LinkCentral_Cleanup::schedule_cleanup();
        // Only update version after all changes are applied successfully
        if ( $is_first_installation ) {
            add_option( 'linkcentral_db_version', LINKCENTRAL_DB_VERSION );
        }
    }

    /**
     * Add custom capabilities for LinkCentral plugin.
     * When $is_first_installation is true, performs a full initialization of capabilities:
     * - Removes all LinkCentral capabilities from non-admin roles (just in case)
     * - Ensures administrators have all capabilities
     * - Sets default capabilities for editors
     * 
     * @param bool $is_first_installation Whether this is a first installation
     */
    public static function add_linkcentral_capabilities( $is_first_installation = false ) {
        global $wp_roles;
        if ( !isset( $wp_roles ) ) {
            $wp_roles = new WP_Roles();
        }
        // Get the administrator role
        $admin = get_role( 'administrator' );
        if ( !$admin ) {
            return;
        }
        // List of all LinkCentral capabilities
        $all_capabilities = array(
            'linkcentral_manage_settings',
            'linkcentral_view_links',
            'linkcentral_create_edit_links',
            'linkcentral_view_stats'
        );
        // Always ensure administrators have all capabilities
        foreach ( $all_capabilities as $cap ) {
            $admin->add_cap( $cap );
        }
        // Get the editor role
        $editor = get_role( 'editor' );
        if ( $editor ) {
            // Always ensure editors have the view links capability
            $editor->add_cap( 'linkcentral_view_links' );
        }
        // Only modify other roles during first installation
        if ( $is_first_installation ) {
            // First remove all capabilities from all roles except administrator and editor. Clean baseline.
            foreach ( $wp_roles->role_objects as $role_name => $role_object ) {
                if ( $role_name !== 'administrator' && $role_name !== 'editor' ) {
                    foreach ( $all_capabilities as $cap ) {
                        $role_object->remove_cap( $cap );
                    }
                }
            }
            // Then set default capabilities for editors
            if ( $editor ) {
                $editor_caps = array('linkcentral_create_edit_links', 'linkcentral_view_stats');
                foreach ( $editor_caps as $cap ) {
                    $editor->add_cap( $cap );
                }
            }
        }
    }

    /**
     * Create database indexes for optimal performance.
     *
     * @param string $table_name The table name to create indexes on
     */
    private static function create_database_indexes( $table_name ) {
        global $wpdb;
        // Check if indexes already exist to avoid duplicate creation
        $existing_indexes = $wpdb->get_results( "SHOW INDEX FROM {$table_name}" );
        $index_names = array();
        foreach ( $existing_indexes as $index ) {
            $index_names[] = $index->Key_name;
        }
        // Primary composite index for most common queries (link_id + date filtering)
        if ( !in_array( 'idx_link_date', $index_names ) ) {
            $wpdb->query( "CREATE INDEX idx_link_date ON {$table_name} (link_id, click_date)" );
        }
        // Index for date-only queries (used in cleanup, date range reports)
        if ( !in_array( 'idx_click_date', $index_names ) ) {
            $wpdb->query( "CREATE INDEX idx_click_date ON {$table_name} (click_date)" );
        }
        // Index for referrer analysis (limited to 255 chars for performance)
        if ( !in_array( 'idx_referring_url', $index_names ) ) {
            $wpdb->query( "CREATE INDEX idx_referring_url ON {$table_name} (referring_url(255))" );
        }
    }

    /**
     * Deactivation logic for a single site.
     * 
     * This method is called:
     * - During regular single-site WordPress deactivation
     * - For each site during network deactivation
     * - When deactivating on a single site within a multisite network
     * - When a site is deleted from a network where the plugin is network-activated
     */
    public static function deactivate() {
        // Clear the scheduled cleanup event
        LinkCentral_Cleanup::deactivate_cleanup();
        // Set the cleanup setting to false upon deactivation, in case plugin is re-activated later
        update_option( 'linkcentral_enable_data_expiry', false );
    }

    /**
     * Delete all LinkCentral tables for the current site.
     */
    public static function delete_tables() {
        global $wpdb;
        // Drop the stats table
        $stats_table = $wpdb->prefix . 'linkcentral_stats';
        $wpdb->query( "DROP TABLE IF EXISTS {$stats_table}" );
        // Drop the keywords table
        $keywords_table = $wpdb->prefix . 'linkcentral_keywords';
        $wpdb->query( "DROP TABLE IF EXISTS {$keywords_table}" );
    }

}

/**
 * Activation hook callback.
 */
function linkcentral_activate() {
    LinkCentral_Activator::activate();
}

/**
 * Deactivation hook callback.
 */
function linkcentral_deactivate() {
    LinkCentral_Activator::deactivate();
}
