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

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

trait LinkCentral_Import_CSV {

    /**
     * Process the entire CSV file for import
     *
     * @param string $file_path The path to the CSV file
     * @param array $import_settings The import settings
     * @return array|WP_Error Import results or error
     */
    protected function process_csv_import($file_path, $import_settings) {
        // Read the entire file content
        $file_content = file_get_contents($file_path);
        if ($file_content === false) {
            return new WP_Error('file_error', __('Cannot open the uploaded file.', 'linkcentral'));
        }

        // Split into lines
        $lines = explode("\n", trim($file_content));
        if (empty($lines)) {
            return new WP_Error('file_error', __('The uploaded file is empty.', 'linkcentral'));
        }

        // Detect delimiter from the first line
        $first_line = $lines[0];
        $delimiter = $this->detect_csv_delimiter($first_line);

        // Parse all lines as CSV
        $csv_data = array_map(function($line) use ($delimiter) {
            return str_getcsv($line, $delimiter);
        }, $lines);

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

        $current_prefix = get_option('linkcentral_url_prefix', 'go');
        $row_number = 2; // Start at 2 (1 is header)

        // Skip header row and process data rows
        for ($i = 1; $i < count($csv_data); $i++) {
            $row = $csv_data[$i];
            // Skip empty rows
            if (empty(array_filter($row, function($cell) { return trim($cell) !== ''; }))) {
                continue;
            }

            // Map CSV row to LinkCentral fields (fixed order)
            $link_data = $this->map_csv_row_to_link_data_fixed($row);

            // Validate required fields
            $validation_result = LinkCentral_Import_Shared::validate_link_data($link_data);
            if (is_wp_error($validation_result)) {
                $results['errors']++;
                $results['error_details'][] = array(
                    'row' => $row_number,
                    'error' => $validation_result->get_error_message()
                );
                $row_number++;
                continue;
            }

            // Process slug and prefix
            $force_prefix = $import_settings['force_prefix'] ?? false;
            $slug_info = LinkCentral_Import_Shared::process_slug($link_data['slug'], $current_prefix, $force_prefix);
            $link_data['slug'] = $slug_info['slug'];
            $link_data['disable_slug_prefix'] = $slug_info['disable_slug_prefix'];

            // Handle duplicates (check after slug processing)
            $duplicate_action = $import_settings['duplicate_handling'] ?? 'skip';
            $existing_link = LinkCentral_Import_Shared::find_existing_link($link_data['slug']);

            if ($existing_link) {
                if ($duplicate_action === 'skip') {
                    $results['skipped']++;
                    LinkCentral_Import_Shared::add_skipped_link(
                        $results,
                        array(
                            'title' => $link_data['title'],
                            'slug' => $link_data['slug'],
                        ),
                        array(
                            'row' => $row_number,
                            'existing_link' => $existing_link,
                        )
                    );
                    $row_number++;
                    continue;
                }
                // For 'update', we'll proceed with the existing ID
            }

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

            if (is_wp_error($link_result)) {
                $results['errors']++;
                $results['error_details'][] = array(
                    'row' => $row_number,
                    'error' => $link_result->get_error_message()
                );
            } else {
                $results['success']++;

                // Count keywords imported
                if (!empty($link_data['keywords'])) {
                    $keywords_count = LinkCentral_Import_Shared::count_keywords_in_string($link_data['keywords']);
                    $results['keywords_imported'] += $keywords_count;
                }
            }

            $row_number++;
        }

        return $results;
    }

    /**
     * Detect CSV delimiter from a line of text
     *
     * @param string $line The first line of the CSV file
     * @return string The detected delimiter
     */
    private function detect_csv_delimiter($line) {
        $delimiters = array(',', ';', "\t", '|');
        $delimiter_counts = array();

        foreach ($delimiters as $delimiter) {
            $delimiter_counts[$delimiter] = substr_count($line, $delimiter);
        }

        return array_search(max($delimiter_counts), $delimiter_counts);
    }

    /**
     * Get field mapping suggestions based on CSV headers
     *
     * @param array $headers The CSV headers
     * @return array The field mapping suggestions
     */
    private function get_field_mapping_suggestions($headers) {
        $linkcentral_fields = array(
            'title' => __('Title', 'linkcentral'),
            'destination_url' => __('Destination URL', 'linkcentral'),
            'slug' => __('Slug', 'linkcentral'),
            'category' => __('Category', 'linkcentral'),
            'nofollow' => __('NoFollow', 'linkcentral'),
            'sponsored' => __('Sponsored', 'linkcentral'),
            'parameter_forwarding' => __('Parameter Forwarding', 'linkcentral'),
            'redirect_type' => __('Redirect Type', 'linkcentral'),
            'note' => __('Note', 'linkcentral'),
            'keywords' => __('Keywords', 'linkcentral'),
            'skip' => __('Skip this column', 'linkcentral')
        );

        $suggestions = array();

        foreach ($headers as $index => $header) {
            $header_lower = strtolower(trim($header));
            $suggested_field = 'skip';

            // Skip mapping suggestions for empty headers
            if (empty($header_lower)) {
                $suggested_field = 'skip';
            }
            // Title field mapping
            elseif (in_array($header_lower, array('title', 'name', 'link_title', 'link_name'))) {
                $suggested_field = 'title';
            }
            // Destination URL mapping
            elseif (in_array($header_lower, array('url', 'destination_url', 'target_url', 'destination url'))) {
                $suggested_field = 'destination_url';
            }
            // Slug mapping
            elseif (in_array($header_lower, array('slug', 'link_slug', 'short_url', 'permalink'))) {
                $suggested_field = 'slug';
            }
            // Category mapping
            elseif (in_array($header_lower, array('category', 'categories', 'group', 'group_id'))) {
                $suggested_field = 'category';
            }
            // NoFollow mapping
            elseif (in_array($header_lower, array('nofollow', 'no_follow', 'rel_nofollow'))) {
                $suggested_field = 'nofollow';
            }
            // Sponsored mapping
            elseif (in_array($header_lower, array('sponsored', 'rel_sponsored'))) {
                $suggested_field = 'sponsored';
            }
            // Parameter forwarding mapping
            elseif (in_array($header_lower, array('parameter_forwarding', 'param_forwarding', 'forward_parameters', 'parameters'))) {
                $suggested_field = 'parameter_forwarding';
            }
            // Redirect type mapping
            elseif (in_array($header_lower, array('redirect_type', 'redirection_type', 'redirect'))) {
                $suggested_field = 'redirect_type';
            }
            // Note mapping
            elseif (in_array($header_lower, array('note', 'notes', 'description', 'link_note'))) {
                $suggested_field = 'note';
            }
            // Keywords mapping
            elseif (in_array($header_lower, array('keywords', 'keyword', 'auto_keywords', 'auto_keyword'))) {
                $suggested_field = 'keywords';
            }

            $suggestions[$index] = array(
                'header' => $header,
                'suggested_field' => $suggested_field,
                'available_fields' => $linkcentral_fields
            );
        }

        return $suggestions;
    }

    /**
     * Map CSV row data to LinkCentral link data (fixed column order)
     *
     * Expected CSV columns in order:
     * 0: Title (required)
     * 1: Slug (required)
     * 2: Destination URL (required)
     * 3: Category (optional)
     * 4: Nofollow (optional)
     * 5: Sponsored (optional)
     * 6: Parameter Forwarding (optional)
     * 7: Redirect Type (optional)
     * 8: Note (optional)
     *
     * @param array $row The CSV row data
     * @return array The mapped link data
     */
    private function map_csv_row_to_link_data_fixed($row) {
        // Ensure we have at least the required columns
        if (count($row) < 3) {
            return array(
                'title' => '',
                'destination_url' => '',
                'slug' => '',
                'category' => '',
                'nofollow' => 'default',
                'sponsored' => 'default',
                'parameter_forwarding' => 'default',
                'redirect_type' => 'default',
                'note' => '',
                'keywords' => ''
            );
        }

        return array(
            'title' => trim($row[0] ?? ''),
            'slug' => trim($row[1] ?? ''),
            'destination_url' => trim($row[2] ?? ''),
            'category' => trim($row[3] ?? ''),
            'nofollow' => isset($row[4]) ? LinkCentral_Import_Shared::parse_boolean_value(trim($row[4])) : 'default',
            'sponsored' => isset($row[5]) ? LinkCentral_Import_Shared::parse_boolean_value(trim($row[5])) : 'default',
            'parameter_forwarding' => isset($row[6]) ? LinkCentral_Import_Shared::parse_boolean_value(trim($row[6])) : 'default',
            'redirect_type' => isset($row[7]) ? LinkCentral_Import_Shared::parse_redirect_type(trim($row[7])) : 'default',
            'note' => trim($row[8] ?? ''),
            'keywords' => ''
        );
    }
}
