<?php

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

class SEO_Fury_Core
{

    private $db_version = '1.0.0';

    private $redirects_table;
    private $indexnow_table;
    private $log404_table;

    private $robots;
    private $sitemap;
    private $redirects;
    private $indexnow;
    private $general;
    private $admin;
    private $meta_titles;
    private $breadcrumbs;
    private $local_seo;
    private $log404_monitor;
    private $license;
    private $post_meta;
    private $fingerprint;
    private $integrity;
    private $pro_features;
    private $woocommerce;
    private $ai_content;
    private $ai_keys;
    private $seo_images;
    private $htaccess;
    private $google_indexing;
    private $import_export;
    private $page_speed;
    private $ai_image_generator;
    private $ai_seo_text;
    private $llms_txt;
    private $auto_redirect;
    private $seo_revisions;
    private $frontend_inspector;
    private $seo_audit;
    private $site_verification;
    private $google_search_console;
    private $image_seo_basic;
    private $google_analytics;
    private $yandex_metrika;
    private $bing_uet;
    private $custom_analytics;
    private $ai_search_traffic;
    private $backlink_checker;
    private $rank_tracker;
    private $link_assistant;
    private $content_decay;
    private $broken_link_checker;
    private $broken_links;
    private $schema_templates;
    private $index_tracker;
    private $seo_reports;
    private $hreflang;
    private $updater;
    private $yasr_integration;

    private static $instance = null;

public static function get_instance($redirects_table = null, $indexnow_table = null)
{
    if (self::$instance === null) {
        self::$instance = new self($redirects_table, $indexnow_table);
    }
    return self::$instance;
}

private function __construct($redirects_table = null, $indexnow_table = null)
{
    if ($redirects_table) {
        $this->redirects_table = $redirects_table;
    }
    if ($indexnow_table) {
        $this->indexnow_table = $indexnow_table;
    }

    if (!$this->redirects_table || !$this->indexnow_table || !$this->log404_table) {
        $this->setup_database_tables();
    }

    $this->load_dependencies();
    $this->init_modules();

    if (!is_admin()) {
        $this->remove_wp_default_tags();
    }

    if (is_admin()) {
        $stored_version = get_option('seo_fury_installed_version', '');

        if ($stored_version !== SEO_FURY_VERSION) {
            update_option('seo_fury_installed_version', SEO_FURY_VERSION);
            // Ensure all database tables exist after update (activation hook doesn't run on zip update).
            $this->create_database_tables();
        }
    }

    add_action('woocommerce_loaded', array($this, 'init_woocommerce_module'));
}

public function init_woocommerce_module() {
    if (!$this->woocommerce) {
        if (!class_exists('SEO_Fury_WooCommerce')) {
            require_once SEO_FURY_PATH . 'includes/class-woocommerce.php';
        }
        $this->woocommerce = new SEO_Fury_WooCommerce();
    }
}

private function remove_wp_default_tags() {
    // rel_canonical is removed in class-post-meta.php → remove_default_meta_tags() for singular pages
    remove_action('wp_head', 'rel_canonical');
    remove_action('wp_head', 'wp_generator');
    remove_action('wp_head', 'wlwmanifest_link');
    remove_action('wp_head', 'rsd_link');
    remove_action('wp_head', 'wp_shortlink_wp_head');
    remove_action('wp_head', 'rest_output_link_wp_head');
    remove_action('wp_head', 'wp_oembed_add_discovery_links');
}

private function setup_database_tables()
{
    global $wpdb;

    if (!$this->redirects_table) {
        $this->redirects_table = $wpdb->prefix . 'seo_redirects';
    }
    if (!$this->indexnow_table) {
        $this->indexnow_table = $wpdb->prefix . 'seo_indexnow_log';
    }

    if (!$this->log404_table) {
        $this->log404_table = $wpdb->prefix . 'seo_404_log';
    }
}

private function load_dependencies()
{
    require_once SEO_FURY_PATH . 'includes/class-robots.php';
    require_once SEO_FURY_PATH . 'includes/class-sitemap.php';
    require_once SEO_FURY_PATH . 'includes/class-redirects.php';
    require_once SEO_FURY_PATH . 'includes/class-indexnow.php';
    require_once SEO_FURY_PATH . 'includes/class-general.php';
    require_once SEO_FURY_PATH . 'includes/class-meta-titles.php';
    require_once SEO_FURY_PATH . 'includes/class-breadcrumbs.php';
    require_once SEO_FURY_PATH . 'includes/class-local-seo.php';
    require_once SEO_FURY_PATH . 'includes/class-404-monitor.php';
    require_once SEO_FURY_PATH . 'includes/class-admin.php';
    require_once SEO_FURY_PATH . 'includes/class-post-meta.php';
    require_once SEO_FURY_PATH . 'includes/class-migration.php';
    require_once SEO_FURY_PATH . 'includes/class-migration-wizard.php';
    require_once SEO_FURY_PATH . 'includes/class-pro-features.php';
    require_once SEO_FURY_PATH . 'includes/class-elementor-integration.php';
    require_once SEO_FURY_PATH . 'includes/class-post-meta-internal-links.php';
    require_once SEO_FURY_PATH . 'includes/class-shortcode-variables.php';
    require_once SEO_FURY_PATH . 'includes/class-tickets.php';

    if (class_exists('WooCommerce')) {
        require_once SEO_FURY_PATH . 'includes/class-woocommerce.php';
    }

    // Encryption utility (standalone, no WooCommerce dependency)
    require_once SEO_FURY_PATH . 'includes/class-encryption.php';

    // Htaccess module
    require_once SEO_FURY_PATH . 'includes/class-htaccess.php';

    // Import/Export module
    require_once SEO_FURY_PATH . 'includes/class-import-export.php';

    // Page Speed module
    require_once SEO_FURY_PATH . 'includes/class-page-speed.php';

    // LLMs.txt module
    require_once SEO_FURY_PATH . 'includes/class-llms-txt.php';

    // Auto-redirect on slug change
    require_once SEO_FURY_PATH . 'includes/class-auto-redirect.php';

    // SEO Revisions tracking
    require_once SEO_FURY_PATH . 'includes/class-seo-revisions.php';

    // Frontend SEO Inspector
    require_once SEO_FURY_PATH . 'includes/class-frontend-inspector.php';

    // Site Verification module
    require_once SEO_FURY_PATH . 'includes/class-site-verification.php';

    // Hreflang / Multilingual SEO
    require_once SEO_FURY_PATH . 'includes/class-hreflang.php';

    // Schema Templates
    require_once SEO_FURY_PATH . 'includes/class-schema-templates.php';

    // Google Search Console
    require_once SEO_FURY_PATH . 'includes/class-google-search-console.php';

    // Basic Image SEO
    require_once SEO_FURY_PATH . 'includes/class-image-seo.php';

    // YASR (Yet Another Stars Rating) integration
    require_once SEO_FURY_PATH . 'includes/class-yasr-integration.php';

    // SEO score column on the posts list
    require_once SEO_FURY_PATH . 'includes/class-posts-column.php';
}

private function init_modules()
{
    do_action('seo_fury_before_init_modules');

    $this->robots = new SEO_Fury_Robots();
    $this->sitemap = new SEO_Fury_Sitemap();
    $this->redirects = new SEO_Fury_Redirects($this->redirects_table);
    $this->indexnow = new SEO_Fury_Indexnow($this->indexnow_table);
    $this->general = new SEO_Fury_General();
    $this->meta_titles = new SEO_Fury_Meta_Titles();
    $this->breadcrumbs = new SEO_Fury_Breadcrumbs();
    $this->local_seo = new SEO_Fury_Local_SEO();
    $this->pro_features = new SEO_Fury_Pro_Features();

    $this->log404_monitor = new SEO_Fury_404_Monitor($this->log404_table, $this->redirects_table);
    $this->post_meta = new SEO_Fury_Post_Meta();

    // Support tickets (singleton, registers AJAX hooks)
    SEO_Fury_Tickets::get_instance();

    // WooCommerce module (initialized via woocommerce_loaded hook or immediately if already loaded)
    if (class_exists('WooCommerce') && !$this->woocommerce) {
        $this->init_woocommerce_module();
    }

    // Htaccess module
    $this->htaccess = new SEO_Fury_Htaccess();

    // Import/Export module
    $this->import_export = new SEO_Fury_Import_Export();

    // Page Speed module
    $this->page_speed = new SEO_Fury_Page_Speed();

    // LLMs.txt module
    $this->llms_txt = new SEO_Fury_LLMS_Txt();

    // Auto-redirect on slug change
    $this->auto_redirect = new SEO_Fury_Auto_Redirect($this->redirects_table);

    // SEO Revisions tracking
    $this->seo_revisions = new SEO_Fury_Revisions();

    // Frontend SEO Inspector (frontend only)
    $this->frontend_inspector = SEO_Fury_Frontend_Inspector::get_instance();

    // Site Verification module
    $this->site_verification = SEO_Fury_Site_Verification::get_instance();

    // Hreflang / Multilingual SEO
    $this->hreflang = SEO_Fury_Hreflang::get_instance();

    // Schema Templates
    $this->schema_templates = new SEO_Fury_Schema_Templates();

    // Google Search Console
    $this->google_search_console = new SEO_Fury_Google_Search_Console();

    // Basic Image SEO
    $this->image_seo_basic = new SEO_Fury_Image_SEO_Basic();

    // YASR integration (always init; hooks fire only when YASR is active)
    $this->yasr_integration = new SEO_Fury_YASR_Integration();

    // SEO score column on the posts list (admin only)
    if (is_admin()) {
        new SEO_Fury_Posts_Column();
    }

    $this->admin = new SEO_Fury_Admin($this);

    // Migration Wizard (admin only)
    if (is_admin()) {
        new SEO_Fury_Migration_Wizard();
    }

    // Elementor integration (loads only when Elementor editor is active)
    if (did_action('elementor/loaded') || class_exists('\Elementor\Plugin')) {
        SEO_Fury_Elementor_Integration::get_instance();
    }

    do_action('seo_fury_after_init_modules', $this);
}

/**
 * Set a module instance (used by PRO addon to register modules).
 *
 * @param string $name     Module property name.
 * @param object $instance Module instance.
 */
public function set_module($name, $instance) {
    if (property_exists($this, $name)) {
        $this->$name = $instance;
    }
}

public function get_integrity() {
    return $this->integrity;
}

public function get_404_monitor()
{
    return $this->log404_monitor;
}

    public function get_general()
    {
        return $this->general;
    }

    public function get_robots()
    {
        return $this->robots;
    }

    public function get_sitemap()
    {
        return $this->sitemap;
    }

    public function get_redirects()
    {
        return $this->redirects;
    }

    public function get_indexnow()
    {
        return $this->indexnow;
    }

public function get_meta_titles()
{
    return $this->meta_titles;
}

public function get_breadcrumbs()
{
    return $this->breadcrumbs;
}

public function get_local_seo()
{
    return $this->local_seo;
}

public function get_fingerprint() {
    return $this->fingerprint;
}

public function get_license()
{
    return $this->license;
}

public function get_post_meta() {
    return $this->post_meta;
}

public function get_pro_features() {
    return $this->pro_features;
}

public function get_woocommerce() {
    return $this->woocommerce;
}

public function get_ai_content() {
    return $this->ai_content;
}

public function get_seo_images() {
    return $this->seo_images;
}

public function get_htaccess() {
    return $this->htaccess;
}

public function get_ai_keys() {
    return $this->ai_keys;
}

public function get_google_indexing() {
    return $this->google_indexing;
}

public function get_import_export() {
    return $this->import_export;
}

public function get_page_speed() {
    return $this->page_speed;
}

public function get_ai_image_generator() {
    return $this->ai_image_generator;
}

public function get_ai_seo_text() {
    return $this->ai_seo_text;
}

public function get_llms_txt() {
    return $this->llms_txt;
}

public function get_auto_redirect() {
    return $this->auto_redirect;
}

public function get_seo_revisions() {
    return $this->seo_revisions;
}

public function get_frontend_inspector() {
    return $this->frontend_inspector;
}

public function get_seo_audit() {
    return $this->seo_audit;
}

public function get_site_verification() {
    return $this->site_verification;
}


public function get_ai_search_traffic() {
    return $this->ai_search_traffic;
}

public function get_backlink_checker() {
    return $this->backlink_checker;
}

public function get_google_search_console() {
    return $this->google_search_console;
}

public function get_image_seo_basic() {
    return $this->image_seo_basic;
}

public function get_yasr_integration() {
    return $this->yasr_integration;
}

public function get_google_analytics() {
    return $this->google_analytics;
}

public function get_yandex_metrika() {
    return $this->yandex_metrika;
}

public function get_bing_uet() {
    return $this->bing_uet;
}

public function get_index_tracker() {
    return $this->index_tracker;
}

public function get_seo_reports() {
    return $this->seo_reports;
}

public function get_hreflang() {
    return $this->hreflang;
}

public function get_custom_analytics() {
    return $this->custom_analytics;
}

public function get_rank_tracker() {
    return $this->rank_tracker;
}

public function get_link_assistant() {
    return $this->link_assistant;
}

public function get_content_decay() {
    return $this->content_decay;
}

public function get_broken_link_checker() {
    return $this->broken_link_checker;
}

public function get_broken_links() {
    return $this->broken_links;
}

    public static function activate()
    {
        $instance = new self();
        $migration = new SEO_Fury_Migration();
        $migration->run_migration();
        $instance->create_database_tables();
        $instance->set_default_options();

        $instance->sitemap->register_sitemap_rewrite();
        $instance->sitemap->register_xsl_rewrite();
        $instance->sitemap->disable_wp_native_sitemap();

        // Set flag to show migration wizard on first activation
        if (!get_option('seo_fury_migration_wizard_dismissed', 0)) {
            update_option('seo_fury_show_migration_wizard', 1);
        }

        flush_rewrite_rules();
    }

    public static function deactivate()
    {
        flush_rewrite_rules();
    }

private function create_database_tables()
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    $sql_redirects = "CREATE TABLE IF NOT EXISTS {$this->redirects_table} (
        id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        source_url varchar(500) NOT NULL,
        target_url varchar(500) NOT NULL,
        redirect_type int(3) NOT NULL DEFAULT 301,
        is_regex tinyint(1) NOT NULL DEFAULT 0,
        hits bigint(20) UNSIGNED NOT NULL DEFAULT 0,
        active tinyint(1) NOT NULL DEFAULT 1,
        created datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY source_url (source_url(191)),
        KEY active (active),
        KEY active_source (active, source_url(191))
    ) $charset_collate;";

    $sql_indexnow = "CREATE TABLE IF NOT EXISTS {$this->indexnow_table} (
        id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        url varchar(500) NOT NULL,
        response_code int(3) DEFAULT NULL,
        response_message text DEFAULT NULL,
        submitted_at datetime DEFAULT CURRENT_TIMESTAMP,
        method varchar(50) DEFAULT 'manual',
        PRIMARY KEY (id),
        KEY url (url(191)),
        KEY submitted_at (submitted_at)
    ) $charset_collate;";

    $sql_404 = "CREATE TABLE IF NOT EXISTS {$this->log404_table} (
    id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    url varchar(500) NOT NULL,
    referer varchar(500) DEFAULT NULL,
    user_agent varchar(255) DEFAULT NULL,
    ip_address varchar(45) DEFAULT NULL,
    hits bigint(20) UNSIGNED NOT NULL DEFAULT 1,
    first_seen datetime DEFAULT CURRENT_TIMESTAMP,
    last_seen datetime DEFAULT CURRENT_TIMESTAMP,
    resolved tinyint(1) NOT NULL DEFAULT 0,
    PRIMARY KEY (id),
    KEY url (url(191)),
    KEY last_seen (last_seen)
) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql_redirects);
    dbDelta($sql_indexnow);
    dbDelta($sql_404);

    update_option('seo_fury_db_version', $this->db_version);
}

    private function set_default_options()
    {
        if (get_option('seo_fury_robots_enabled') === false) {
            update_option('seo_fury_robots_enabled', 1);
        }

        if (get_option('seo_fury_robots_use_dynamic_vars') === false) {
            update_option('seo_fury_robots_use_dynamic_vars', 1);
        }

        if (get_option('seo_fury_sitemap_enabled') === false) {
            update_option('seo_fury_sitemap_enabled', 0);
        }

        if (get_option('seo_fury_sitemap_post_types') === false) {
            update_option('seo_fury_sitemap_post_types', array('post', 'page'));
        }

        if (get_option('seo_fury_sitemap_include_images') === false) {
            update_option('seo_fury_sitemap_include_images', 0);
        }

        if (get_option('seo_fury_indexnow_auto_submit') === false) {
            update_option('seo_fury_indexnow_auto_submit', 0);
        }

        if (get_option('seo_fury_indexnow_auto_delete') === false) {
            update_option('seo_fury_indexnow_auto_delete', 0);
        }

        if (get_option('seo_fury_indexnow_search_engine') === false) {
            update_option('seo_fury_indexnow_search_engine', 'api.indexnow.org');
        }

        if (get_option('seo_fury_robots_meta_index') === false) {
            update_option('seo_fury_robots_meta_index', 1);
        }

        if (get_option('seo_fury_robots_meta_max_snippet') === false) {
            update_option('seo_fury_robots_meta_max_snippet', -1);
        }
        if (get_option('seo_fury_robots_meta_max_video_preview') === false) {
            update_option('seo_fury_robots_meta_max_video_preview', -1);
        }
        if (get_option('seo_fury_robots_meta_max_image_preview') === false) {
            update_option('seo_fury_robots_meta_max_image_preview', 'standard');
        }
        if (get_option('seo_fury_title_separator') === false) {
            update_option('seo_fury_title_separator', '-');
        }
        if (get_option('seo_fury_twitter_card_type') === false) {
            update_option('seo_fury_twitter_card_type', 'summary_large_image');
        }

        if (get_option('seo_fury_404_monitoring_enabled') === false) {
            update_option('seo_fury_404_monitoring_enabled', 1);
        }
        if (get_option('seo_fury_404_ignore_bots') === false) {
            update_option('seo_fury_404_ignore_bots', 1);
        }
        if (get_option('seo_fury_404_auto_cleanup_days') === false) {
            update_option('seo_fury_404_auto_cleanup_days', 30);
        }

        // URL transliteration — enabled by default
        if (get_option('seo_fury_transliterate_urls') === false) {
            update_option('seo_fury_transliterate_urls', 1);
        }

        // Broken links scanner — enabled by default
        if (get_option('seo_fury_broken_links_enabled') === false) {
            update_option('seo_fury_broken_links_enabled', 1);
        }
    }
}
