<?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 plugin_dir_path( __FILE__ ) . 'utilities.php';
require_once plugin_dir_path( __FILE__ ) . 'handlers/csv.php';
require_once plugin_dir_path( __FILE__ ) . 'handlers/json.php';
require_once plugin_dir_path( __FILE__ ) . 'handlers/thirstyaffiliates.php';
require_once plugin_dir_path( __FILE__ ) . 'handlers/prettylinks.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'));
    }

    /**
     * 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();
    }

    /**
     * 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']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(__('File upload failed.', 'linkcentral'));
        }

        $import_settings = json_decode(stripslashes($_POST['import_settings'] ?? '{}'), true);

        $file_path = $_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']) || $_FILES['json_file']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(__('File upload failed.', 'linkcentral'));
        }

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

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

        $file_path = $_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($_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($_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'));
        }
    }

} 