<?php

/**
 * Plugin Name: LinkCentral
 * Plugin URI: https://designforwp.com/linkcentral
 * Description: Easy URL shortener, custom link manager, and affiliate link tracking.
 * Version: 1.7.0
 * Author: Design for WP
 * Author URI: https://designforwp.com
 * License: GPL-3.0+
 * Text Domain: linkcentral
 * Domain Path: /languages
 * 
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
    // Exit if accessed directly
}
if ( function_exists( 'linkcentral_fs' ) ) {
    linkcentral_fs()->set_basename( false, __FILE__ );
} else {
    // Define plugin constants
    define( 'LINKCENTRAL_VERSION', '1.7.0' );
    define( 'LINKCENTRAL_DB_VERSION', '1.0.10' );
    define( 'LINKCENTRAL_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
    define( 'LINKCENTRAL_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
    // Freemius initialization
    if ( !function_exists( 'linkcentral_fs' ) ) {
        // Create a helper function for easy SDK access.
        function linkcentral_fs() {
            global $linkcentral_fs;
            if ( !isset( $linkcentral_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/wordpress-sdk/start.php';
                $linkcentral_fs = fs_dynamic_init( array(
                    'id'               => '16835',
                    'slug'             => 'linkcentral',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_cbedf270c66e652bc776cff7b3b03',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Premium',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'menu'             => array(
                        'slug'        => 'linkcentral',
                        'contact'     => false,
                        'support'     => false,
                        'pricing'     => false,
                        'affiliation' => false,
                    ),
                    'anonymous_mode'   => true,
                    'is_live'          => true,
                ) );
            }
            return $linkcentral_fs;
        }

        // Init Freemius.
        linkcentral_fs();
        // Signal that SDK was initiated.
        do_action( 'linkcentral_fs_loaded' );
        // i18n override
        add_action( 'init', function () {
            // Rename to license page
            linkcentral_fs()->override_i18n( [
                'account' => __( 'License', 'linkcentral' ),
            ] );
        } );
        // Disable opt-in option by default
        linkcentral_fs()->add_filter( 'permission_diagnostic_default', '__return_false' );
        linkcentral_fs()->add_filter( 'permission_extensions_default', '__return_false' );
        linkcentral_fs()->add_filter( 'hide_freemius_powered_by', '__return_true' );
        // Hide some admin notices
        linkcentral_fs()->add_filter(
            'show_admin_notice',
            function ( $show, $message ) {
                if ( $message['id'] === 'premium_activated' || $message['id'] === 'connect_account' || $message['id'] === 'plan_upgraded' ) {
                    return false;
                }
                return $show;
            },
            10,
            2
        );
        // Hide Opt-In link from Plugin page
        global $pagenow;
        if ( $pagenow === 'plugins.php' && !linkcentral_fs()->is_registered( true ) ) {
            add_action( 'admin_head', function () {
                echo '<style>.opt-in-or-opt-out.linkcentral {display: none !important;}</style>';
            } );
        }
        // Exclude LinkCentral links from speculative loading in WordPress 6.8+
        add_filter( 'wp_speculation_rules_href_exclude_paths', function ( $href_exclude_paths ) {
            $url_prefix = get_option( 'linkcentral_url_prefix', 'go' );
            $href_exclude_paths[] = '/' . $url_prefix . '/*';
            return $href_exclude_paths;
        } );
    }
    // Include files needed for both admin and front-end
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/post-type/post-type.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/rest-api.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/integrations/frontend/shortcode.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/redirection.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/integrations/frontend/content-filter.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/activator.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/updater.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/link-helpers.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/user-agent-parser.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/utils/password-page.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/visitor-manager.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/geolocation.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/dynamic-rules.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/click-tracker.php';
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/redirection/webhook-handler.php';
    // Include required automation classes
    require_once LINKCENTRAL_PLUGIN_DIR . 'includes/automations/cleanup.php';
    /**
     * Main LinkCentral Class
     *
     * This class is the core of LinkCentral, initializing all major components.
     */
    class LinkCentral {
        private $url_prefix;

        private $post_type;

        private $shortcode;

        private $redirection;

        private $content_filter;

        private $rest_api;

        // Utility classes
        private $visitor_manager;

        private $geolocation;

        private $dynamic_rules;

        private $click_tracker;

        private $webhook_handler;

        // Admin-only properties
        private $admin;

        public function __construct() {
            $this->url_prefix = get_option( 'linkcentral_url_prefix', 'go' );
            // Initialize utility classes
            $this->visitor_manager = new LinkCentral_Visitor_Manager();
            $this->geolocation = new LinkCentral_Geolocation($this->visitor_manager);
            $this->dynamic_rules = new LinkCentral_Dynamic_Rules($this->geolocation, $this->visitor_manager);
            $this->click_tracker = new LinkCentral_Tracker($this->visitor_manager, $this->geolocation);
            $this->webhook_handler = new LinkCentral_Webhook_Handler($this->visitor_manager, $this->geolocation);
            // Initialize main components
            $this->post_type = new LinkCentral_Post_Type();
            $this->rest_api = new LinkCentral_REST_API();
            $this->shortcode = new LinkCentral_Shortcode($this->url_prefix);
            $this->redirection = new LinkCentral_Redirection(
                $this->url_prefix,
                $this->visitor_manager,
                $this->geolocation,
                $this->dynamic_rules,
                $this->click_tracker,
                $this->webhook_handler
            );
            $this->content_filter = new LinkCentral_Content_Filter();
            $this->load_admin_files();
        }

        public function init() {
            $this->post_type->init();
            $this->rest_api->init();
            $this->shortcode->init();
            $this->redirection->init();
            $this->content_filter->init();
        }

        public function load_admin_files() {
            if ( is_admin() || is_user_logged_in() ) {
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/admin.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/links-overview.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/settings.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/insights.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/import-admin.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/migration-notices.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/admin/dashboard-widget.php';
                require_once LINKCENTRAL_PLUGIN_DIR . 'includes/integrations/backend/integrations.php';
                $this->admin = new LinkCentral_Admin();
                $this->admin->init();
                // Initialize LinkCentral_Links_Overview for bulk processing actions
                LinkCentral_Links_Overview::init();
            }
        }

    }

    /**
     * Initialize the plugin.
     */
    function linkcentral_init() {
        // Run database update check
        linkcentral_update_db_check();
        $linkcentral = new LinkCentral();
        $linkcentral->init();
    }

    add_action( 'plugins_loaded', 'linkcentral_init' );
    // Activation hook
    register_activation_hook( __FILE__, 'linkcentral_activate_handler' );
    // Deactivation hook
    register_deactivation_hook( __FILE__, 'linkcentral_deactivate_handler' );
    // (For possible future uninstallation hook, use freemius' after_uninstall hook)
    /**
     * Activation handler that detects network activation.
     * 
     * @param bool $network_wide Whether the plugin is being network-activated.
     */
    function linkcentral_activate_handler(  $network_wide  ) {
        if ( is_multisite() && $network_wide ) {
            // Network activation: activate on all sites
            linkcentral_network_activate();
        } else {
            // Single site activation
            linkcentral_activate();
        }
    }

    /**
     * Deactivation handler that detects network deactivation.
     * 
     * @param bool $network_wide Whether the plugin is being network-deactivated.
     */
    function linkcentral_deactivate_handler(  $network_wide  ) {
        if ( is_multisite() && $network_wide ) {
            // Network deactivation: deactivate on all sites
            linkcentral_network_deactivate();
        } else {
            // Single site deactivation
            linkcentral_deactivate();
        }
    }

    /**
     * Network activation: iterate through all sites and activate.
     */
    function linkcentral_network_activate() {
        global $wpdb;
        // Get all site IDs
        $site_ids = get_sites( array(
            'fields' => 'ids',
            'number' => 0,
        ) );
        foreach ( $site_ids as $site_id ) {
            switch_to_blog( $site_id );
            linkcentral_activate();
            restore_current_blog();
        }
    }

    /**
     * Network deactivation: iterate through all sites and deactivate.
     */
    function linkcentral_network_deactivate() {
        global $wpdb;
        // Get all site IDs
        $site_ids = get_sites( array(
            'fields' => 'ids',
            'number' => 0,
        ) );
        foreach ( $site_ids as $site_id ) {
            switch_to_blog( $site_id );
            linkcentral_deactivate();
            restore_current_blog();
        }
    }

    /**
     * Handle new site creation in a multisite network.
     * Runs activation logic on newly created sites if plugin is network-activated.
     * 
     * @param WP_Site $new_site New site object.
     */
    function linkcentral_new_site_created(  $new_site  ) {
        // Check if the plugin is network-activated
        if ( !is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) {
            return;
        }
        // Switch to the new site and run activation
        switch_to_blog( $new_site->blog_id );
        linkcentral_activate();
        restore_current_blog();
    }

    add_action( 'wp_initialize_site', 'linkcentral_new_site_created', 99 );
    /**
     * Handle site deletion in a multisite network.
     * Clean up all LinkCentral data when a site is deleted.
     * 
     * @param WP_Site $old_site Deleted site object.
     */
    function linkcentral_site_deleted(  $old_site  ) {
        // Switch to the deleted site to run cleanup before it's fully removed
        switch_to_blog( $old_site->blog_id );
        // Run deactivation logic to clear scheduled events
        linkcentral_deactivate();
        // Delete all LinkCentral tables for this site
        LinkCentral_Activator::delete_tables();
        restore_current_blog();
    }

    add_action( 'wp_delete_site', 'linkcentral_site_deleted' );
}