<?php
/**
 * LinkCentral MyThemeShop URL Shortener Import Handler
 *
 * This trait handles MyThemeShop URL Shortener database import functionality for LinkCentral links.
 * It can be used by any class that needs to import links from MyThemeShop URL Shortener database.
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Utility class for MyThemeShop URL Shortener plugin detection and configuration
 */
class LinkCentral_MTSUrlShortener_Utils {

    /**
     * Import configuration constants
     */
    const DEFAULT_BATCH_SIZE = 50;
    const STATS_BATCH_SIZE = 1000;
    const MAX_LINKS_PER_IMPORT = 1000;
    const MAX_CLICKS_PER_LINK = 50000;

    /**
     * Check if MyThemeShop URL Shortener plugin is active
     *
     * @return bool True if MyThemeShop URL Shortener is active
     */
    private static function is_plugin_active() {
        if (!function_exists('is_plugin_active')) {
            return false;
        }

        // Check for both regular and Pro versions
        $regular_version = 'mts-url-shortener/mts-url-shortener.php';
        $pro_version = 'mts-url-shortener-pro/mts-url-shortener-pro.php';

        return is_plugin_active($regular_version) || is_plugin_active($pro_version);
    }

    /**
     * Check if MyThemeShop URL Shortener is available (active and has data)
     *
     * @return bool True if MyThemeShop URL Shortener is active and has data
     */
    public static function is_available() {
        // Check if MyThemeShop URL Shortener plugin is active first (cheapest check)
        if (!self::is_plugin_active()) {
            return false;
        }

        // Quick check if any MyThemeShop URL Shortener links exist
        // MTS URL Shortener uses custom table 'wp_short_links'
        global $wpdb;

        // Check if the short_links table exists
        $table_name = esc_sql($wpdb->prefix . 'short_links');
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) !== $table_name) {
            return false;
        }

        $count = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}short_links` WHERE link_status = 'publish'");
        return $count > 0;
    }

    /**
     * Get MyThemeShop URL Shortener statistics
     *
     * @return array Statistics about MyThemeShop URL Shortener data
     */
    public static function get_stats() {
        // Check if MyThemeShop URL Shortener plugin is active first
        if (!self::is_plugin_active()) {
            return array('links' => 0, 'categories' => 0, 'stats' => 0);
        }

        global $wpdb;

        // Check if short_links table exists
        $links_table = esc_sql($wpdb->prefix . 'short_links');
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $links_table)) !== $links_table) {
            return array('links' => 0, 'categories' => 0, 'stats' => 0);
        }

        // Get published links count
        $published_links = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}short_links` WHERE link_status = 'publish'");

        // Count categories (MTS URL Shortener uses 'short_link_category' taxonomy)
        $categories_count = $wpdb->get_var("
            SELECT COUNT(DISTINCT t.term_id)
            FROM {$wpdb->prefix}terms t
            INNER JOIN {$wpdb->prefix}term_taxonomy tt ON t.term_id = tt.term_id
            WHERE tt.taxonomy = 'short_link_category'
        ");

        // Count stats (check if short_link_clicks table exists)
        $stats_count = 0;
        $stats_table = esc_sql($wpdb->prefix . 'short_link_clicks');
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $stats_table)) === $stats_table) {
            $stats_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->prefix}short_link_clicks`");
        }

        return array(
            'links' => (int) $published_links,
            'categories' => (int) $categories_count,
            'stats' => (int) $stats_count
        );
    }
}

class LinkCentral_MTSUrlShortener_Importer {

    /**
     * Check if MyThemeShop URL Shortener plugin is installed
     *
     * @return bool True if MyThemeShop URL Shortener is installed
     */
    public function is_available() {
        return LinkCentral_MTSUrlShortener_Utils::is_available();
    }

    /**
     * Get MyThemeShop URL Shortener statistics
     *
     * @return array Statistics about MyThemeShop URL Shortener data
     */
    public function get_stats() {
        return LinkCentral_MTSUrlShortener_Utils::get_stats();
    }

    /**
     * Process MyThemeShop URL Shortener import
     *
     * @param array $import_options Import options
     * @return array|WP_Error Import results or error
     */
    public function process_import($import_options = array()) {
        global $wpdb;

        if (!$this->is_available()) {
            return new WP_Error('no_data', __('No MyThemeShop URL Shortener data found.', 'linkcentral'));
        }

        $defaults = array(
            'import_categories' => false,
            'import_stats' => false,
            'duplicate_handling' => 'skip',
            'batch_size' => LinkCentral_MTSUrlShortener_Utils::DEFAULT_BATCH_SIZE,
            'offset' => 0
        );

        $import_options = wp_parse_args($import_options, $defaults);

        // Map MyThemeShop URL Shortener-specific options to generic import options
        $import_options['create_categories'] = $import_options['import_categories'];

        $results = array(
            'success' => 0,
            'skipped' => 0,
            'errors' => 0,
            'categories_imported' => 0,
            'stats_imported' => 0,
            'skipped_links' => array(),
            'error_details' => array()
        );

        // Import categories first if requested
        if ($import_options['import_categories']) {
            $category_result = $this->import_categories();
            $results['categories_imported'] = $category_result;
        }

        // Import links in batches
        $batch_size = $import_options['batch_size'];
        $offset = $import_options['offset'];
        $processed = 0;

        while (true) {
            $links = $this->get_links($batch_size, $offset);

            if (empty($links)) {
                break; // No more links to process
            }

            foreach ($links as $mts_link) {
                $link_result = $this->import_single_link($mts_link, $import_options);

                if (is_wp_error($link_result)) {
                    $results['errors']++;
                    $results['error_details'][] = array(
                        'link' => $mts_link['title'],
                        'error' => $link_result->get_error_message()
                    );
                } elseif ($link_result['action'] === 'skipped') {
                    $results['skipped']++;
                    LinkCentral_Import_Shared::add_skipped_link($results, $mts_link, array(
                        'existing_link' => $link_result['existing_link'] ?? null,
                    ));
                } else {
                    $results['success']++;

                    // Import stats if requested
                    if ($import_options['import_stats'] && isset($link_result['link_id'])) {
                        $stats_imported = $this->import_stats($mts_link['ID'], $link_result['link_id']);
                        $results['stats_imported'] += $stats_imported;
                    }
                }

                $processed++;
            }

            $offset += count($links);

            // Optional: Add progress tracking
            $results['processed'] = $processed;
            $results['current_offset'] = $offset;

            // Prevent infinite loops and timeouts
            if ($processed >= LinkCentral_MTSUrlShortener_Utils::MAX_LINKS_PER_IMPORT) {
                $results['batch_complete'] = false;
                $results['resume_offset'] = $offset;
                break;
            }
        }


        $results['batch_complete'] = true;
        return $results;
    }

    /**
     * Get MyThemeShop URL Shortener links from database
     *
     * @param int $batch_size Number of links to retrieve
     * @param int $offset Offset for pagination
     * @return array Array of MyThemeShop URL Shortener links
     */
    private function get_links($batch_size = null, $offset = 0) {
        global $wpdb;

        if ($batch_size) {
            $links = $wpdb->get_results(
                $wpdb->prepare(
                    "
            SELECT
                link_id as ID,
                link_title as title,
                link_name as slug,
                link_url as destination_url,
                link_description as content,
                link_notes as notes,
                link_created as post_date,
                link_redirection_method as redirect_type,
                link_forward_parameters as pass_query_str,
                link_attr_rel as rel_tags
            FROM `{$wpdb->prefix}short_links`
            WHERE link_status = 'publish'
            ORDER BY link_created ASC
            LIMIT %d OFFSET %d",
                    $batch_size,
                    $offset
                ),
                ARRAY_A
            );
        } else {
            $links = $wpdb->get_results(
                "
            SELECT
                link_id as ID,
                link_title as title,
                link_name as slug,
                link_url as destination_url,
                link_description as content,
                link_notes as notes,
                link_created as post_date,
                link_redirection_method as redirect_type,
                link_forward_parameters as pass_query_str,
                link_attr_rel as rel_tags
            FROM `{$wpdb->prefix}short_links`
            WHERE link_status = 'publish'
            ORDER BY link_created ASC",
                ARRAY_A
            );
        }

        // Prefer link_title when available, fallback to link_name (slug)
        foreach ($links as &$link) {
            if (empty($link['title'])) {
                $link['title'] = $link['slug'];
            }
        }

        // Process each link to match the expected format
        foreach ($links as &$link) {
            // Parse redirect type (format is like "302;0" where first part is the code)
            if (!empty($link['redirect_type'])) {
                $redirect_parts = explode(';', $link['redirect_type']);
                $link['redirect_type'] = $redirect_parts[0];
            } else {
                $link['redirect_type'] = '302'; // default
            }

            // Convert pass_query_str to boolean-like value
            $link['pass_query_str'] = !empty($link['pass_query_str']) ? 'yes' : 'no';

            // Parse rel tags for nofollow/sponsored
            $link['nofollow'] = strpos($link['rel_tags'], 'nofollow') !== false ? 'yes' : 'default';
            $link['sponsored'] = strpos($link['rel_tags'], 'sponsored') !== false ? 'yes' : 'default';

            // Get categories using the correct taxonomy (MTS doesn't have hierarchical categories)
            $categories = wp_get_post_terms($link['ID'], 'short_link_category', array('fields' => 'names'));
            $link['categories'] = is_array($categories) ? $categories : array();
        }

        return $links;
    }


    /**
     * Import MyThemeShop URL Shortener categories
     *
     * @return int Number of categories imported
     */
    private function import_categories() {
        $mts_categories = get_terms(array(
            'taxonomy' => 'short_link_category',
            'hide_empty' => false,
        ));

        if (is_wp_error($mts_categories)) {
            return 0;
        }

        $imported_count = 0;

        // MTS doesn't have hierarchical categories, so just import them directly
        foreach ($mts_categories as $mts_category) {
            // Use the import utilities to handle simple category creation
            $term_id = LinkCentral_Import_Shared::get_or_create_category($mts_category->name, true);

            if ($term_id) {
                $imported_count++;
            }
        }

        return $imported_count;
    }


    /**
     * Import a single MyThemeShop URL Shortener link
     *
     * @param array $mts_link MyThemeShop URL Shortener link data
     * @param array $import_options Import options
     * @return array|WP_Error Import result or error
     */
    private function import_single_link($mts_link, $import_options) {
        $keywords = $this->get_keywords_for_link($mts_link['ID']);

        // Process slug and prefix first to determine the final slug
        // This fixes duplicate detection when MyThemeShop URL Shortener slug matches LinkCentral prefix
        $current_prefix = get_option('linkcentral_url_prefix', 'go');
        $slug_info = LinkCentral_Import_Shared::process_slug($mts_link['slug'], $current_prefix, false);

        // Check for existing link by the processed slug (what the final slug will be)
        $existing_link = LinkCentral_Import_Shared::find_existing_link($slug_info['slug']);

        if ($existing_link && $import_options['duplicate_handling'] === 'skip') {
            return array(
                'action' => 'skipped',
                'existing_link' => $existing_link,
            );
        }

        // Prepare link data
        $category_data = $import_options['import_categories'] ? $mts_link['categories'] : array();

        $link_data = array(
            'title' => $mts_link['title'],
            'destination_url' => $mts_link['destination_url'],
            'slug' => $slug_info['slug'],
            'disable_slug_prefix' => $slug_info['disable_slug_prefix'],
            'category' => $category_data,
            'nofollow' => $mts_link['nofollow'],
            'sponsored' => $mts_link['sponsored'],
            'parameter_forwarding' => $this->convert_mts_parameter_forwarding($mts_link['pass_query_str']),
            'redirect_type' => $this->convert_mts_redirect_type($mts_link['redirect_type']),
            'note' => $mts_link['notes'],
            'keywords' => ''
        );

        // Validate required fields
        $validation_result = LinkCentral_Import_Shared::validate_link_data($link_data);
        if (is_wp_error($validation_result)) {
            return $validation_result;
        }

        // Create or update the link
        $link_result = LinkCentral_Import_Shared::create_or_update_link($link_data, $existing_link, $import_options);

        if (is_wp_error($link_result)) {
            return $link_result;
        }

        // Import MyThemeShop keyword replacements as LinkCentral keywords.
        if (!empty($keywords)) {
            $keywords_data = array();
            foreach ($keywords as $keyword) {
                $keywords_data[] = array(
                    'keyword' => $keyword,
                    'density' => 'medium'
                );
            }
            LinkCentral_Import_Shared::import_keywords_for_link($link_result, $keywords_data);
        }

        return array(
            'action' => $existing_link ? 'updated' : 'created',
            'link_id' => $link_result
        );
    }

    /**
     * Get keyword replacements for a MyThemeShop URL Shortener link.
     *
     * @param int $mts_link_id MyThemeShop URL Shortener link ID
     * @return array Array of keyword strings
     */
    private function get_keywords_for_link($mts_link_id) {
        global $wpdb;

        $table_name = esc_sql($wpdb->prefix . 'short_link_replacements');
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) !== $table_name) {
            return array();
        }

        $keywords = $wpdb->get_col($wpdb->prepare(
            "SELECT replace_key
             FROM `{$wpdb->prefix}short_link_replacements`
             WHERE link_id = %d AND type = %s",
            $mts_link_id,
            'keyword'
        ));

        if (empty($keywords) || !is_array($keywords)) {
            return array();
        }

        $keywords = array_values(array_unique(array_filter(array_map('trim', $keywords))));
        return $keywords;
    }

    /**
     * Import MyThemeShop URL Shortener stats for a link
     *
     * @param int $mts_link_id MyThemeShop URL Shortener link ID
     * @param int $lc_link_id LinkCentral link ID
     * @return int Number of stats imported
     */
    private function import_stats($mts_link_id, $lc_link_id) {
        global $wpdb;

        $stats_table = esc_sql($wpdb->prefix . 'short_link_clicks');

        // Check if stats table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $stats_table)) != $stats_table) {
            return 0;
        }

        // Get stats for this link (batched for performance)
        $batch_size = LinkCentral_MTSUrlShortener_Utils::STATS_BATCH_SIZE;
        $offset = 0;
        $total_imported = 0;

        while (true) {
            $clicks = $wpdb->get_results($wpdb->prepare("
                SELECT
                    click_id as id,
                    click_date,
                    click_referrer as referring_url,
                    click_useragent as user_agent,
                    click_ip as ip_address
                FROM `{$wpdb->prefix}short_link_clicks`
                WHERE link_id = %d
                ORDER BY click_date ASC
                LIMIT %d OFFSET %d
            ", $mts_link_id, $batch_size, $offset), ARRAY_A);

            if (empty($clicks)) {
                break; // No more stats for this link
            }

            // Convert clicks to LinkCentral format
            $stats = array();
            foreach ($clicks as $click) {
                $stats[] = array(
                    'click_date' => $click['click_date'],
                    'referring_url' => $click['referring_url'] ?? '',
                    'user_agent' => $click['user_agent'] ?? '',
                    'destination_url' => '', // MTS URL Shortener doesn't store destination URL in clicks
                    'visitor_id' => '', // MTS URL Shortener doesn't have visitor tracking like this
                    'first_click' => 0, // MTS URL Shortener doesn't track first clicks
                );
            }

            $batch_imported = $this->import_stats_batch($stats, $lc_link_id);
            $total_imported += $batch_imported;
            $offset += $batch_size;

            // Safety check to prevent infinite loops
            if ($offset > LinkCentral_MTSUrlShortener_Utils::MAX_CLICKS_PER_LINK) {
                break;
            }
        }

        return $total_imported;
    }

    /**
     * Import a batch of stats for a link
     *
     * @param array $stats Array of stat data
     * @param int $lc_link_id LinkCentral link ID
     * @return int Number of stats imported in this batch
     */
    private function import_stats_batch($stats, $lc_link_id) {
        global $wpdb;

        if (empty($stats)) {
            return 0;
        }

        $imported_count = 0;

        foreach ($stats as $stat) {
            $result = $wpdb->query(
                $wpdb->prepare(
                    "INSERT INTO `{$wpdb->prefix}linkcentral_stats` (link_id, click_date, referring_url, user_agent, destination_url, country, visitor_id, first_click) VALUES (%d, %s, %s, %s, %s, %s, %s, %d)",
                    $lc_link_id,
                    $stat['click_date'],
                    $stat['referring_url'] ?: '',
                    $stat['user_agent'] ?: '',
                    $stat['destination_url'] ?: '',
                    '', // country - MyThemeShop URL Shortener may not store this
                    $stat['visitor_id'] ?: '', // visitor_id if available
                    $stat['first_click'] ?: 0 // first_click flag
                )
            );

            if ($result !== false) {
                $imported_count++;
            }
        }

        return $imported_count;
    }


    /**
     * Convert MyThemeShop URL Shortener parameter forwarding to LinkCentral format
     *
     * @param string $pass_query_str MyThemeShop URL Shortener pass query string setting
     * @return string LinkCentral parameter forwarding setting
     */
    private function convert_mts_parameter_forwarding($pass_query_str) {
        if ($pass_query_str === '1' || $pass_query_str === 1 || $pass_query_str === 'yes') {
            return 'yes';
        } elseif ($pass_query_str === '0' || $pass_query_str === 0 || $pass_query_str === 'no') {
            return 'no';
        }
        return 'default';
    }

    /**
     * Convert MyThemeShop URL Shortener redirect type to LinkCentral format
     *
     * @param string $redirect_type MyThemeShop URL Shortener redirect type
     * @return string LinkCentral redirect type
     */
    private function convert_mts_redirect_type($redirect_type) {
        switch ($redirect_type) {
            case '301':
                return '301';
            case '302':
                return '302';
            case '307':
                return '307';
            default:
                return 'default';
        }
    }
}
