<?php
/**
 * LinkCentral Import Class
 *
 * This class handles the import functionality for LinkCentral links.
 * It uses modular traits for different import types and shared utilities.
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Include import utilities and handlers
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/utilities.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/handlers/csv.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/handlers/json.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/handlers/thirstyaffiliates.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/handlers/prettylinks.php';
require_once LINKCENTRAL_PLUGIN_DIR . 'includes/import/handlers/mtsurlshortener.php';

class LinkCentral_Import {

    // Use import traits for modular functionality
    use LinkCentral_Import_CSV;
    use LinkCentral_Import_JSON;
    
    /**
     * Initialize the import functionality
     */
    public function init() {
        add_action('wp_ajax_linkcentral_import_csv', array($this, 'ajax_import_csv'));
        add_action('wp_ajax_linkcentral_import_json', array($this, 'ajax_import_json'));
        add_action('wp_ajax_linkcentral_import_thirstyaffiliates', array($this, 'ajax_import_thirstyaffiliates'));
        add_action('wp_ajax_linkcentral_get_thirstyaffiliates_stats', array($this, 'ajax_get_thirstyaffiliates_stats'));
        add_action('wp_ajax_linkcentral_disable_thirstyaffiliates', array($this, 'ajax_disable_thirstyaffiliates'));
        add_action('wp_ajax_linkcentral_import_prettylinks', array($this, 'ajax_import_prettylinks'));
        add_action('wp_ajax_linkcentral_get_prettylinks_stats', array($this, 'ajax_get_prettylinks_stats'));
        add_action('wp_ajax_linkcentral_disable_prettylinks', array($this, 'ajax_disable_prettylinks'));
        add_action('wp_ajax_linkcentral_import_mtsurlshortener', array($this, 'ajax_import_mtsurlshortener'));
        add_action('wp_ajax_linkcentral_get_mtsurlshortener_stats', array($this, 'ajax_get_mtsurlshortener_stats'));
        add_action('wp_ajax_linkcentral_disable_mtsurlshortener', array($this, 'ajax_disable_mtsurlshortener'));
    }

    /**
     * Get ThirstyAffiliates importer instance
     *
     * @return LinkCentral_ThirstyAffiliates_Importer
     */
    public function get_thirstyaffiliates_importer() {
        return new LinkCentral_ThirstyAffiliates_Importer();
    }

    /**
     * Get Pretty Links importer instance
     *
     * @return LinkCentral_PrettyLinks_Importer
     */
    public function get_prettylinks_importer() {
        return new LinkCentral_PrettyLinks_Importer();
    }

    /**
     * Get MyThemeShop URL Shortener importer instance
     *
     * @return LinkCentral_MTSUrlShortener_Importer
     */
    public function get_mtsurlshortener_importer() {
        return new LinkCentral_MTSUrlShortener_Importer();
    }

    /**
     * Process the entire CSV file for import
     */
    public function ajax_import_csv() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');
        
        if (!current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        if (!isset($_FILES['csv_file']) || !isset($_FILES['csv_file']['error']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(__('File upload failed.', 'linkcentral'));
        }

        $import_settings_raw = isset($_POST['import_settings']) ? sanitize_text_field(wp_unslash($_POST['import_settings'])) : '{}';
        $import_settings = json_decode($import_settings_raw, true);

        $file_path = isset($_FILES['csv_file']['tmp_name']) ? sanitize_text_field($_FILES['csv_file']['tmp_name']) : '';
        $result = $this->process_csv_import($file_path, $import_settings);
        
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for importing LinkCentral JSON exports
     */
    public function ajax_import_json() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');
        
        if (!current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        if (!isset($_FILES['json_file']) || !isset($_FILES['json_file']['error']) || $_FILES['json_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(__('File upload failed.', 'linkcentral'));
        }

        $duplicate_action = isset($_POST['duplicate_action']) ? sanitize_text_field(wp_unslash($_POST['duplicate_action'])) : 'skip';
        $import_mode = isset($_POST['import_mode']) ? sanitize_text_field(wp_unslash($_POST['import_mode'])) : 'migration';

        // Validate import mode
        if (!in_array($import_mode, array('migration', 'restore'))) {
            $import_mode = 'migration';
        }

        $file_path = isset($_FILES['json_file']['tmp_name']) ? sanitize_text_field($_FILES['json_file']['tmp_name']) : '';
        $result = $this->process_json_import($file_path, $duplicate_action, $import_mode);
        
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for getting ThirstyAffiliates statistics
     */
    public function ajax_get_thirstyaffiliates_stats() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_thirstyaffiliates_importer();
        $stats = $importer->get_stats();
        wp_send_json_success($stats);
    }

    /**
     * AJAX handler for importing ThirstyAffiliates data
     */
    public function ajax_import_thirstyaffiliates() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_thirstyaffiliates_importer();
        $import_options = array(
            'update_url_prefix' => isset($_POST['update_url_prefix']) && $_POST['update_url_prefix'] === 'true',
            'import_categories' => isset($_POST['import_categories']) && $_POST['import_categories'] === 'true',
            'import_stats' => isset($_POST['import_stats']) && $_POST['import_stats'] === 'true',
            'duplicate_handling' => isset($_POST['duplicate_handling']) ? sanitize_text_field(wp_unslash($_POST['duplicate_handling'])) : 'skip'
        );

        $result = $importer->process_import($import_options);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        // Mark the ThirstyAffiliates migration notice as dismissed since import completed successfully
        update_option('linkcentral_dismissed_thirstyaffiliates_notice', '1');

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for disabling ThirstyAffiliates plugin
     */
    public function ajax_disable_thirstyaffiliates() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(__('Insufficient permissions to deactivate plugins.', 'linkcentral'));
        }

        // Check if ThirstyAffiliates is still active
        if (!function_exists('is_plugin_active') || !is_plugin_active('thirstyaffiliates/thirstyaffiliates.php')) {
            wp_send_json_error(__('ThirstyAffiliates plugin is not currently active.', 'linkcentral'));
        }

        // Attempt to deactivate the plugin
        if (function_exists('deactivate_plugins')) {
            deactivate_plugins('thirstyaffiliates/thirstyaffiliates.php');

            // Verify deactivation
            if (!is_plugin_active('thirstyaffiliates/thirstyaffiliates.php')) {
                wp_send_json_success(__('ThirstyAffiliates plugin has been successfully disabled.', 'linkcentral'));
            } else {
                wp_send_json_error(__('Failed to disable ThirstyAffiliates plugin. Please try manually.', 'linkcentral'));
            }
        } else {
            wp_send_json_error(__('Plugin deactivation function not available.', 'linkcentral'));
        }
    }

    /**
     * AJAX handler for getting Pretty Links statistics
     */
    public function ajax_get_prettylinks_stats() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_prettylinks_importer();
        $stats = $importer->get_stats();
        wp_send_json_success($stats);
    }

    /**
     * AJAX handler for importing Pretty Links data
     */
    public function ajax_import_prettylinks() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_prettylinks_importer();
        $import_options = array(
            'import_categories' => isset($_POST['import_categories']) && $_POST['import_categories'] === 'true',
            'import_stats' => isset($_POST['import_stats']) && $_POST['import_stats'] === 'true',
            'duplicate_handling' => isset($_POST['duplicate_handling']) ? sanitize_text_field(wp_unslash($_POST['duplicate_handling'])) : 'skip'
        );

        $result = $importer->process_import($import_options);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for disabling Pretty Links plugin
     */
    public function ajax_disable_prettylinks() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(__('Insufficient permissions to deactivate plugins.', 'linkcentral'));
        }

        // Check if Pretty Links is still active
        if (!function_exists('is_plugin_active') ||
            (!is_plugin_active('pretty-link/pretty-link.php') && !is_plugin_active('pretty-links/pretty-links.php'))) {
            wp_send_json_error(__('Pretty Links plugin is not currently active.', 'linkcentral'));
        }

        // Attempt to deactivate the plugin (try both possible paths)
        if (function_exists('deactivate_plugins')) {
            if (is_plugin_active('pretty-link/pretty-link.php')) {
                deactivate_plugins('pretty-link/pretty-link.php');
            } elseif (is_plugin_active('pretty-links/pretty-links.php')) {
                deactivate_plugins('pretty-links/pretty-links.php');
            }

            // Verify deactivation
            if (!is_plugin_active('pretty-link/pretty-link.php') && !is_plugin_active('pretty-links/pretty-links.php')) {
                wp_send_json_success(__('Pretty Links plugin has been successfully disabled.', 'linkcentral'));
            } else {
                wp_send_json_error(__('Failed to disable Pretty Links plugin. Please try manually.', 'linkcentral'));
            }
        } else {
            wp_send_json_error(__('Plugin deactivation function not available.', 'linkcentral'));
        }
    }

    /**
     * AJAX handler for getting MyThemeShop URL Shortener statistics
     */
    public function ajax_get_mtsurlshortener_stats() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_mtsurlshortener_importer();
        $stats = $importer->get_stats();
        wp_send_json_success($stats);
    }

    /**
     * AJAX handler for importing MyThemeShop URL Shortener data
     */
    public function ajax_import_mtsurlshortener() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('linkcentral_manage_settings') && !current_user_can('linkcentral_create_edit_links')) {
            wp_send_json_error(__('Insufficient permissions.', 'linkcentral'));
        }

        $importer = $this->get_mtsurlshortener_importer();
        $import_options = array(
            'import_categories' => isset($_POST['import_categories']) && $_POST['import_categories'] === 'true',
            'import_stats' => isset($_POST['import_stats']) && $_POST['import_stats'] === 'true',
            'duplicate_handling' => isset($_POST['duplicate_handling']) ? sanitize_text_field(wp_unslash($_POST['duplicate_handling'])) : 'skip'
        );

        $result = $importer->process_import($import_options);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for disabling MyThemeShop URL Shortener plugin
     */
    public function ajax_disable_mtsurlshortener() {
        check_ajax_referer('linkcentral_import_nonce', 'nonce');

        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(__('Insufficient permissions to deactivate plugins.', 'linkcentral'));
        }

        // Check if MTS URL Shortener (regular or Pro) is still active
        $regular_version = 'mts-url-shortener/mts-url-shortener.php';
        $pro_version = 'mts-url-shortener-pro/mts-url-shortener-pro.php';

        $is_regular_active = function_exists('is_plugin_active') && is_plugin_active($regular_version);
        $is_pro_active = function_exists('is_plugin_active') && is_plugin_active($pro_version);

        if (!$is_regular_active && !$is_pro_active) {
            wp_send_json_error(__('MyThemeShop URL Shortener plugin is not currently active.', 'linkcentral'));
        }

        // Attempt to deactivate the active plugin(s)
        if (function_exists('deactivate_plugins')) {
            $plugins_to_deactivate = array();
            if ($is_regular_active) {
                $plugins_to_deactivate[] = $regular_version;
            }
            if ($is_pro_active) {
                $plugins_to_deactivate[] = $pro_version;
            }

            deactivate_plugins($plugins_to_deactivate);

            // Verify deactivation
            $still_active = false;
            if ($is_regular_active && is_plugin_active($regular_version)) {
                $still_active = true;
            }
            if ($is_pro_active && is_plugin_active($pro_version)) {
                $still_active = true;
            }

            if (!$still_active) {
                wp_send_json_success(__('MyThemeShop URL Shortener plugin has been successfully disabled.', 'linkcentral'));
            } else {
                wp_send_json_error(__('Failed to disable MyThemeShop URL Shortener plugin. Please try manually.', 'linkcentral'));
            }
        } else {
            wp_send_json_error(__('Plugin deactivation function not available.', 'linkcentral'));
        }
    }

} 