<?php
/**
 * LinkCentral JSON Import Handler
 *
 * This trait handles JSON file import functionality for LinkCentral links.
 * It can be used by any class that needs to import links from JSON export files.
 */

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

trait LinkCentral_Import_JSON {

    /**
     * Process JSON import for LinkCentral exports
     *
     * @param string $file_path The path to the JSON file
     * @param string $duplicate_action How to handle duplicates
     * @param string $import_mode The import mode (migration/restore)
     * @return array|WP_Error Import results or error
     */
    protected function process_json_import($file_path, $duplicate_action, $import_mode) {
        $json_content = file_get_contents($file_path);
        if ($json_content === false) {
            return new WP_Error('file_error', __('Cannot read the uploaded file.', 'linkcentral'));
        }

        $data = json_decode($json_content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error('json_error', __('Invalid JSON file.', 'linkcentral'));
        }

        // Validate LinkCentral export format
        if (!isset($data['export_info']) || !isset($data['links']) ||
            !isset($data['export_info']['export_type']) ||
            $data['export_info']['export_type'] !== 'linkcentral_full') {
            return new WP_Error('format_error', __('This is not a valid LinkCentral export file.', 'linkcentral'));
        }

        $results = array(
            'success' => 0,
            'skipped' => 0,
            'errors' => 0,
            'analytics_imported' => 0,
            'keywords_imported' => 0,
            'error_details' => array()
        );

        foreach ($data['links'] as $index => $link_data) {
            $result = $this->import_single_link_with_analytics($link_data, $duplicate_action, $import_mode);

            if (is_wp_error($result)) {
                $results['errors']++;
                $results['error_details'][] = array(
                    'link' => $link_data['title'] ?? 'Unknown',
                    'error' => $result->get_error_message()
                );
            } elseif ($result['action'] === 'skipped') {
                $results['skipped']++;
            } else {
                $results['success']++;
                $results['analytics_imported'] += $result['analytics_count'];
                $results['keywords_imported'] += $result['keywords_count'];
            }
        }

        return $results;
    }

    /**
     * Import a single link with its analytics data
     *
     * @param array $link_data The link data from JSON
     * @param string $duplicate_action How to handle duplicates
     * @param string $import_mode The import mode
     * @return array|WP_Error Import result or error
     */
    protected function import_single_link_with_analytics($link_data, $duplicate_action, $import_mode) {
        // Check for existing link by slug
        $existing_link = LinkCentral_Import_Shared::find_existing_link($link_data['slug']);

        if ($existing_link && $duplicate_action === 'skip') {
            return array('action' => 'skipped', 'analytics_count' => 0);
        }

        // Prepare link data for creation/update
        $post_data = array(
            'post_title' => $link_data['title'],
            'post_name' => $link_data['slug'],
            'post_type' => 'linkcentral_link',
            'post_status' => $link_data['post_status'] ?? 'publish',
            'post_date' => $link_data['post_date'] ?? current_time('mysql')
        );

        // Handle ID preservation in restore mode
        if ($import_mode === 'restore' && isset($link_data['ID']) && !empty($link_data['ID'])) {
            // Check if the original ID is available
            $existing_post = get_post($link_data['ID']);

            if (!$existing_post) {
                // ID is available, we can use it
                $post_data['import_id'] = $link_data['ID'];
            } elseif ($existing_post->post_type === 'linkcentral_link') {
                // Existing post is a LinkCentral link, we can overwrite it with the same ID
                $post_data['import_id'] = $link_data['ID'];
            }
            // If ID conflicts with a non-LinkCentral post, we'll let WordPress auto-generate a new one
        }

        if ($existing_link && $duplicate_action === 'overwrite') {
            $post_data['ID'] = $existing_link->ID;
            $post_id = wp_update_post($post_data);

            // Delete existing analytics and keywords if overwriting
            global $wpdb;
            $wpdb->delete($wpdb->prefix . 'linkcentral_stats', array('link_id' => $existing_link->ID));
            $wpdb->delete($wpdb->prefix . 'linkcentral_keywords', array('link_id' => $existing_link->ID), array('%d'));
        } else {
            $post_id = wp_insert_post($post_data);
        }

        if (is_wp_error($post_id) || !$post_id) {
            return new WP_Error('post_error', __('Failed to create/update link.', 'linkcentral'));
        }

        // Update metadata - "global" values are handled by converting to "default" in parsing functions
        $meta_fields = array(
            '_linkcentral_destination_url' => linkcentral_sanitize_destination_url($link_data['destination_url']),
            '_linkcentral_nofollow' => LinkCentral_Import_Shared::normalize_global_value($link_data['nofollow'] ?? 'default'),
            '_linkcentral_sponsored' => LinkCentral_Import_Shared::normalize_global_value($link_data['sponsored'] ?? 'default'),
            '_linkcentral_redirection_type' => LinkCentral_Import_Shared::normalize_global_value($link_data['redirection_type'] ?? 'default'),
            '_linkcentral_parameter_forwarding' => LinkCentral_Import_Shared::normalize_global_value($link_data['parameter_forwarding'] ?? 'default'),
            '_linkcentral_css_classes_option' => LinkCentral_Import_Shared::normalize_global_value($link_data['css_classes_option'] ?? 'default'),
            '_linkcentral_custom_css_classes' => $link_data['custom_css_classes'] ?? '',
            '_linkcentral_disable_slug_prefix' => $link_data['disable_slug_prefix'] ?? false,
            '_linkcentral_dynamic_rules' => $link_data['dynamic_rules'] ?? array(),
            '_linkcentral_note' => $link_data['note'] ?? ''
        );

        foreach ($meta_fields as $meta_key => $meta_value) {
            update_post_meta($post_id, $meta_key, $meta_value);
        }

        // Store import metadata for reference
        update_post_meta($post_id, '_linkcentral_import_mode', $import_mode);
        if ($import_mode === 'restore' && isset($link_data['ID'])) {
            update_post_meta($post_id, '_linkcentral_original_id', $link_data['ID']);
        }

        // Handle categories
        if (!empty($link_data['categories'])) {
            LinkCentral_Import_Shared::assign_category($post_id, $link_data['categories'], true);
        }

        // Import keywords for auto-keyword linking
        if (!empty($link_data['keywords'])) {
            LinkCentral_Import_Shared::import_keywords_for_link($post_id, $link_data['keywords']);
        }

        // Import analytics data
        $analytics_count = LinkCentral_Import_Shared::import_analytics_data($post_id, $link_data['analytics'] ?? array());

        // Count keywords imported
        $keywords_count = count($link_data['keywords'] ?? array());

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