<?php

/**
 * SEOPress Importer
 *
 * @package ProRank\SEO\Core\Importers
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\Importers;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * SEOPressImporter class
 *
 * Imports data from SEOPress plugin
 */


class SEOPressImporter extends BaseImporter {

    /**
     * SEOPress meta key mappings
     *
     * @var array
     */
    private array $meta_key_map = [
        '_seopress_titles_title' => '_prorank_seo_title',
        '_seopress_titles_desc' => '_prorank_seo_description',
        // Focus keywords handled in import_single_post_meta() via FocusKeywords::save().
        '_seopress_robots_canonical' => '_prorank_seo_canonical_url',
        '_seopress_social_fb_title' => '_prorank_og_title',
        '_seopress_social_fb_desc' => '_prorank_og_description',
        '_seopress_social_fb_img' => '_prorank_og_image_id',
        '_seopress_social_twitter_title' => '_prorank_twitter_title',
        '_seopress_social_twitter_desc' => '_prorank_twitter_description',
        '_seopress_social_twitter_img' => '_prorank_twitter_image_id',
        '_seopress_titles_primary_cat' => '_prorank_seo_primary_category',
    ];

    /**
     * Check if SEOPress is available
     *
     * @return bool
     */
    public function is_available(): bool {
        return defined('SEOPRESS_VERSION') ||
               function_exists('seopress_init') ||
               $this->has_seopress_data();
    }

    /**
     * Check if SEOPress data exists in database
     *
     * @return bool
     */
    private function has_seopress_data(): bool {
        global $wpdb;

        $result = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->postmeta}
             WHERE meta_key LIKE '_seopress_%'
             LIMIT 1"
        );

        return (int) $result > 0;
    }

    /**
     * Run the import
     *
     * @return array
     */
    public function import(): array {
        if (!$this->is_available()) {
            return [
                'success' => false,
                'message' => __('SEOPress data not found', 'prorank-seo'),
                'stats' => $this->stats,
            ];
        }

        try {
            // Import post/page meta
            $this->import_post_meta();

            // Import term meta
            $this->import_term_meta();

            // Import settings
            $this->import_settings();

            // Import redirects
            $this->import_redirects();

            // Import schema settings
            $this->import_schema();

            // Import locations (currently no-op for SEOPress unless extended)
            $this->import_locations();

            return [
                'success' => true,
                'message' => __('SEOPress data imported successfully', 'prorank-seo'),
                'stats' => $this->stats,
            ];

        } catch (\Exception $e) {
            $this->log_error('Import failed: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => $e->getMessage(),
                'stats' => $this->stats,
            ];
        }
    }

    /**
     * Import single post meta
     *
     * @param int $post_id Post ID
     * @return void
     */
    protected function import_single_post_meta(int $post_id): void {
        foreach ($this->meta_key_map as $sp_key => $prorank_key) {
            $value = get_post_meta($post_id, $sp_key, true);

            if (!empty($value)) {
                update_post_meta($post_id, $prorank_key, $this->sanitize_meta_value($value));
            }
        }

        // Import focus keywords via multi-keyword model.
        // SEOPress stores target keywords as a comma-separated string.
        $target_kw = trim((string) get_post_meta($post_id, '_seopress_analysis_target_kw', true));
        if ($target_kw !== '') {
            $parts = array_filter(array_map('trim', explode(',', $target_kw)));
            if (!empty($parts)) {
                $kw_input = [];
                foreach ($parts as $i => $part) {
                    $kw_input[] = ['keyword' => $part, 'primary' => $i === 0];
                }
                \ProRank\SEO\Core\FocusKeywords::save($post_id, $kw_input);
            }
        }

        // Handle robots meta → _prorank_meta_robots array
        $robots = [];
        $robots_noindex = get_post_meta($post_id, '_seopress_robots_index', true);
        if ($robots_noindex === 'yes') {
            $robots[] = 'noindex';
        }
        $robots_nofollow = get_post_meta($post_id, '_seopress_robots_follow', true);
        if ($robots_nofollow === 'yes') {
            $robots[] = 'nofollow';
        }
        if (!empty($robots)) {
            update_post_meta($post_id, '_prorank_meta_robots', $robots);
        }

        // Import redirect data if exists
        $redirect_enabled = get_post_meta($post_id, '_seopress_redirections_enabled', true);
        if ($redirect_enabled === 'yes') {
            $redirect_url = get_post_meta($post_id, '_seopress_redirections_value', true);
            $redirect_type = get_post_meta($post_id, '_seopress_redirections_type', true);

            if (!empty($redirect_url)) {
                if ($this->save_redirect([
                    'from' => get_permalink($post_id),
                    'to' => esc_url_raw($redirect_url),
                    'type' => intval($redirect_type) ?: 301,
                    'status' => 'active',
                    'notes' => 'Imported from SEOPress',
                ])) {
                    $this->stats['redirects']++;
                }
            }
        }

        // Import content analysis score
        $score = get_post_meta($post_id, '_seopress_analysis_score', true);
        if ($score) {
            update_post_meta($post_id, '_prorank_seo_score', intval($score));
        }
    }

    /**
     * Import single term meta
     *
     * @param int $term_id Term ID
     * @return void
     */
    protected function import_single_term_meta(int $term_id): void {
        $term_meta_keys = [
            '_seopress_titles_title' => '_prorank_seo_title',
            '_seopress_titles_desc' => '_prorank_seo_description',
            '_seopress_robots_canonical' => '_prorank_seo_canonical',
            '_seopress_social_fb_title' => '_prorank_seo_og_title',
            '_seopress_social_fb_desc' => '_prorank_seo_og_description',
            '_seopress_social_fb_img' => '_prorank_seo_og_image',
        ];

        foreach ($term_meta_keys as $sp_key => $prorank_key) {
            $value = get_term_meta($term_id, $sp_key, true);

            if (!empty($value)) {
                update_term_meta($term_id, $prorank_key, $this->sanitize_meta_value($value));
            }
        }

        // Handle robots meta for terms
        $robots_noindex = get_term_meta($term_id, '_seopress_robots_index', true);
        if ($robots_noindex === 'yes') {
            update_term_meta($term_id, '_prorank_seo_noindex', 'noindex');
        }
    }

    /**
     * Import SEOPress settings
     *
     * @return void
     */
    protected function import_settings(): void {
        $site_basics = [];

        // Titles settings
        $titles = get_option('seopress_titles_option_name');
        if ($titles && is_array($titles)) {
            $settings = [];
            $title_settings = [];

            // Title separator
            if (isset($titles['seopress_titles_sep'])) {
                $settings['title_separator'] = $titles['seopress_titles_sep'];
                $site_basics['title_separator'] = $titles['seopress_titles_sep'];
            }

            // Home title/description
            if (isset($titles['seopress_titles_home_site_title'])) {
                $title_settings['homepage_title'] = $titles['seopress_titles_home_site_title'];
            }
            if (isset($titles['seopress_titles_home_site_desc'])) {
                $title_settings['homepage_description'] = $titles['seopress_titles_home_site_desc'];
            }

            if (!empty($settings)) {
                $this->merge_option_array('prorank_seo_settings', $settings);
                $this->stats['settings']++;
            }

            if (!empty($title_settings)) {
                $this->merge_option_array('prorank_seo_titles_meta', $title_settings);
                $this->stats['settings']++;
            }
        }

        // Social settings
        $social = get_option('seopress_social_option_name');
        if ($social && is_array($social)) {
            $social_settings = [];

            if (isset($social['seopress_social_accounts_facebook'])) {
                $social_settings['facebook_page_url'] = $social['seopress_social_accounts_facebook'];
            }
            if (isset($social['seopress_social_accounts_twitter'])) {
                $social_settings['twitter_username'] = str_replace('@', '', $social['seopress_social_accounts_twitter']);
            }
            if (isset($social['seopress_social_accounts_instagram'])) {
                $social_settings['instagram_url'] = $social['seopress_social_accounts_instagram'];
            }
            if (isset($social['seopress_social_accounts_linkedin'])) {
                $social_settings['linkedin_url'] = $social['seopress_social_accounts_linkedin'];
            }
            if (isset($social['seopress_social_accounts_youtube'])) {
                $social_settings['youtube_url'] = $social['seopress_social_accounts_youtube'];
            }
            if (isset($social['seopress_social_accounts_pinterest'])) {
                $social_settings['pinterest_url'] = $social['seopress_social_accounts_pinterest'];
            }

            if (!empty($social_settings)) {
                $this->merge_option_array('prorank_seo_social', $social_settings);
                $this->merge_site_basics($social_settings);
                $this->stats['settings']++;
            }

            if (isset($social['seopress_social_knowledge_type'])) {
                $site_basics['site_representation'] = $social['seopress_social_knowledge_type'];
            }
            if (isset($social['seopress_social_knowledge_name'])) {
                $site_basics['organization_name'] = $social['seopress_social_knowledge_name'];
            }
            if (isset($social['seopress_social_knowledge_img'])) {
                $site_basics['organization_logo'] = $social['seopress_social_knowledge_img'];
            }
        }

        // XML Sitemap settings
        $sitemap = get_option('seopress_xml_sitemap_option_name');
        if ($sitemap && is_array($sitemap)) {
            $sitemap_settings = get_option('prorank_seo_sitemap', []);

            if (isset($sitemap['seopress_xml_sitemap_general_enable'])) {
                $sitemap_settings['enable_sitemap'] = $sitemap['seopress_xml_sitemap_general_enable'] === '1';
            }

            if (!empty($sitemap_settings)) {
                $this->merge_option_array('prorank_seo_sitemap', $sitemap_settings);
                $this->stats['settings']++;
            }
        }

        // Advanced settings
        $advanced = get_option('seopress_advanced_option_name');
        if ($advanced && is_array($advanced)) {
            $advanced_settings = get_option('prorank_seo_advanced_settings', []);

            if (isset($advanced['seopress_advanced_advanced_clean_filename'])) {
                $advanced_settings['clean_image_filenames'] = $advanced['seopress_advanced_advanced_clean_filename'] === '1';
            }

            if (!empty($advanced_settings)) {
                $this->merge_option_array('prorank_seo_advanced_settings', $advanced_settings);
                $this->stats['settings']++;
            }
        }

        $this->merge_site_basics($site_basics);
    }

    /**
     * Import SEOPress Pro redirects
     *
     * @return void
     */
    protected function import_redirects(): void {
        // SEOPress Pro stores redirects as a custom post type
        $redirects = get_posts([
            'post_type' => 'seopress_404',
            'posts_per_page' => -1,
            'post_status' => 'publish',
        ]);

        foreach ($redirects as $redirect_post) {
            $redirect_enabled = get_post_meta($redirect_post->ID, '_seopress_redirections_enabled', true);

            if ($redirect_enabled !== 'yes') {
                continue;
            }

            $from_url = get_post_meta($redirect_post->ID, '_seopress_redirections_logged_url', true);
            $to_url = get_post_meta($redirect_post->ID, '_seopress_redirections_value', true);
            $type = get_post_meta($redirect_post->ID, '_seopress_redirections_type', true);

            if (!empty($from_url) && !empty($to_url)) {
                if ($this->save_redirect([
                    'from' => sanitize_text_field($from_url),
                    'to' => esc_url_raw($to_url),
                    'type' => intval($type) ?: 301,
                    'status' => 'active',
                    'notes' => 'Imported from SEOPress',
                ])) {
                    $this->stats['redirects']++;
                }
            }
        }
    }

    /**
     * Import schema settings
     *
     * @return void
     */
    protected function import_schema(): void {
        $schema = get_option('seopress_pro_option_name');

        if ($schema && is_array($schema)) {
            $prorank_schema = [];

            // Local Business schema
            if (isset($schema['seopress_local_business_type'])) {
                $prorank_schema['local_business_type'] = $schema['seopress_local_business_type'];
            }

            if (isset($schema['seopress_local_business_street_address'])) {
                $prorank_schema['address_street'] = $schema['seopress_local_business_street_address'];
            }

            if (isset($schema['seopress_local_business_city'])) {
                $prorank_schema['address_city'] = $schema['seopress_local_business_city'];
            }

            if (isset($schema['seopress_local_business_state'])) {
                $prorank_schema['address_state'] = $schema['seopress_local_business_state'];
            }

            if (isset($schema['seopress_local_business_postal_code'])) {
                $prorank_schema['address_postal_code'] = $schema['seopress_local_business_postal_code'];
            }

            if (isset($schema['seopress_local_business_country'])) {
                $prorank_schema['address_country'] = $schema['seopress_local_business_country'];
            }

            if (isset($schema['seopress_local_business_phone'])) {
                $prorank_schema['phone'] = $schema['seopress_local_business_phone'];
            }

            if (!empty($prorank_schema)) {
                $this->merge_option_array('prorank_seo_schema', $prorank_schema);
                $this->stats['settings']++;
            }
        }

        // Social schema settings
        $social = get_option('seopress_social_option_name');
        if ($social && is_array($social)) {
            $schema_settings = get_option('prorank_seo_schema', []);

            if (isset($social['seopress_social_knowledge_type'])) {
                $schema_settings['site_representation'] = $social['seopress_social_knowledge_type'];
            }

            if (isset($social['seopress_social_knowledge_name'])) {
                $schema_settings['organization_name'] = $social['seopress_social_knowledge_name'];
            }

            if (isset($social['seopress_social_knowledge_img'])) {
                $schema_settings['organization_logo'] = $social['seopress_social_knowledge_img'];
            }

            if (!empty($schema_settings)) {
                $this->merge_option_array('prorank_seo_schema', $schema_settings);
                $this->merge_site_basics($schema_settings);
                $this->stats['settings']++;
            }
        }
    }

    /**
     * Map meta key
     *
     * @param string $competitor_key SEOPress meta key
     * @return string ProRank meta key
     */
    protected function map_meta_key(string $competitor_key): string {
        return $this->meta_key_map[$competitor_key] ?? $competitor_key;
    }

    /**
     * Save redirect
     *
     * @param array $redirect Redirect data
     * @return bool
     */
    protected function save_redirect(array $redirect): bool {
        return parent::save_redirect($redirect);
    }
}
