<?php

/**
 * All in One SEO Importer
 *
 * @package ProRank\SEO\Core\Importers
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\Importers;

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


/**
 * AIOSEOImporter class
 *
 * Imports data from All in One SEO plugin
 */


class AIOSEOImporter extends BaseImporter {

    /**
     * AIOSEO meta key mappings (post meta table)
     *
     * @var array
     */
    private array $meta_key_map = [
        '_aioseo_title' => '_prorank_seo_title',
        '_aioseo_description' => '_prorank_seo_description',
        // Focus keywords handled via FocusKeywords::save() in import_from_aioseo_table().
        '_aioseo_canonical_url' => '_prorank_seo_canonical_url',
        '_aioseo_og_title' => '_prorank_og_title',
        '_aioseo_og_description' => '_prorank_og_description',
        '_aioseo_og_image' => '_prorank_og_image_id',
        '_aioseo_twitter_title' => '_prorank_twitter_title',
        '_aioseo_twitter_description' => '_prorank_twitter_description',
        '_aioseo_twitter_image' => '_prorank_twitter_image_id',
    ];

    /**
     * Check if AIOSEO is available
     *
     * @return bool
     */
    public function is_available(): bool {
        return defined('AIOSEO_VERSION') ||
               class_exists('AIOSEO\\Plugin\\AIOSEO') ||
               $this->has_aioseo_data();
    }

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

        // Check for AIOSEO posts table
        $table = $wpdb->prefix . 'aioseo_posts';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) === $table) {
            return true;
        }

        // Check for legacy meta keys
        $result = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->postmeta}
             WHERE meta_key LIKE '_aioseo_%' OR meta_key LIKE '_aioseop_%'
             LIMIT 1"
        );

        return (int) $result > 0;
    }

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

        try {
            // Import from AIOSEO posts table (newer versions)
            $this->import_from_aioseo_table();

            // Import post/page meta (legacy)
            $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 AIOSEO unless extended)
            $this->import_locations();

            return [
                'success' => true,
                'message' => __('All in One SEO 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 from AIOSEO posts table (v4+)
     *
     * @return void
     */
    private function import_from_aioseo_table(): void {
        global $wpdb;

        $table = $wpdb->prefix . 'aioseo_posts';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
            return;
        }

        $posts = $wpdb->get_results("SELECT * FROM {$table}");

        foreach ($posts as $post) {
            $post_id = intval($post->post_id);

            if (!empty($post->title)) {
                update_post_meta($post_id, '_prorank_seo_title', sanitize_text_field($post->title));
            }
            if (!empty($post->description)) {
                update_post_meta($post_id, '_prorank_seo_description', sanitize_textarea_field($post->description));
            }
            if (!empty($post->keyphrases)) {
                $keyphrases = json_decode($post->keyphrases, true);
                $kw_input = [];
                if (isset($keyphrases['focus']['keyphrase'])) {
                    $kw_input[] = ['keyword' => $keyphrases['focus']['keyphrase'], 'primary' => true];
                }
                if (!empty($keyphrases['additional']) && is_array($keyphrases['additional'])) {
                    foreach ($keyphrases['additional'] as $extra) {
                        if (!empty($extra['keyphrase'])) {
                            $kw_input[] = ['keyword' => $extra['keyphrase'], 'primary' => false];
                        }
                    }
                }
                if (!empty($kw_input)) {
                    \ProRank\SEO\Core\FocusKeywords::save($post_id, $kw_input);
                }
            }
            if (!empty($post->canonical_url)) {
                update_post_meta($post_id, '_prorank_seo_canonical_url', esc_url_raw($post->canonical_url));
            }
            if (!empty($post->og_title)) {
                update_post_meta($post_id, '_prorank_og_title', sanitize_text_field($post->og_title));
            }
            if (!empty($post->og_description)) {
                update_post_meta($post_id, '_prorank_og_description', sanitize_textarea_field($post->og_description));
            }
            if (!empty($post->twitter_title)) {
                update_post_meta($post_id, '_prorank_twitter_title', sanitize_text_field($post->twitter_title));
            }
            if (!empty($post->twitter_description)) {
                update_post_meta($post_id, '_prorank_twitter_description', sanitize_textarea_field($post->twitter_description));
            }

            // Handle robots meta → _prorank_meta_robots array
            if (!empty($post->robots_default) && $post->robots_default == 0) {
                $robots = [];
                if (!empty($post->robots_noindex) && $post->robots_noindex == 1) {
                    $robots[] = 'noindex';
                }
                if (!empty($post->robots_nofollow) && $post->robots_nofollow == 1) {
                    $robots[] = 'nofollow';
                }
                if (!empty($robots)) {
                    update_post_meta($post_id, '_prorank_meta_robots', $robots);
                }
            }

            $this->stats['posts']++;
        }
    }

    /**
     * Import single post meta (legacy AIOSEO)
     *
     * @param int $post_id Post ID
     * @return void
     */
    protected function import_single_post_meta(int $post_id): void {
        // Legacy AIOSEO Pack meta keys
        $legacy_keys = [
            '_aioseop_title' => '_prorank_seo_title',
            '_aioseop_description' => '_prorank_seo_description',
            '_aioseop_keywords' => '_prorank_seo_focus_keyword',
            '_aioseop_custom_link' => '_prorank_seo_canonical_url',
        ];

        foreach ($legacy_keys as $aio_key => $prorank_key) {
            $value = get_post_meta($post_id, $aio_key, true);

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

        // Legacy robots → _prorank_meta_robots array
        $robots = [];
        $noindex = get_post_meta($post_id, '_aioseop_noindex', true);
        if ($noindex === 'on' || $noindex === '1') {
            $robots[] = 'noindex';
        }
        $nofollow = get_post_meta($post_id, '_aioseop_nofollow', true);
        if ($nofollow === 'on' || $nofollow === '1') {
            $robots[] = 'nofollow';
        }
        if (!empty($robots)) {
            update_post_meta($post_id, '_prorank_meta_robots', $robots);
        }

        // Also check new meta keys
        foreach ($this->meta_key_map as $aio_key => $prorank_key) {
            $value = get_post_meta($post_id, $aio_key, true);

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

    /**
     * Import single term meta
     *
     * @param int $term_id Term ID
     * @return void
     */
    protected function import_single_term_meta(int $term_id): void {
        global $wpdb;

        // Check for AIOSEO terms table
        $table = $wpdb->prefix . 'aioseo_terms';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
            return;
        }

        $term_data = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE term_id = %d",
            $term_id
        ));

        if (!$term_data) {
            return;
        }

        if (!empty($term_data->title)) {
            update_term_meta($term_id, '_prorank_seo_title', sanitize_text_field($term_data->title));
        }
        if (!empty($term_data->description)) {
            update_term_meta($term_id, '_prorank_seo_description', sanitize_textarea_field($term_data->description));
        }
        if (!empty($term_data->canonical_url)) {
            update_term_meta($term_id, '_prorank_seo_canonical', esc_url_raw($term_data->canonical_url));
        }
        if (!empty($term_data->og_title)) {
            update_term_meta($term_id, '_prorank_seo_og_title', sanitize_text_field($term_data->og_title));
        }
        if (!empty($term_data->og_description)) {
            update_term_meta($term_id, '_prorank_seo_og_description', sanitize_textarea_field($term_data->og_description));
        }
    }

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

        // Try new AIOSEO options format first
        $aioseo_options = get_option('aioseo_options');

        if ($aioseo_options) {
            $options = is_string($aioseo_options) ? json_decode($aioseo_options, true) : $aioseo_options;

            if (is_array($options)) {
                $settings = [];

                // Separator
                if (isset($options['searchAppearance']['global']['separator'])) {
                    $settings['title_separator'] = $options['searchAppearance']['global']['separator'];
                    $site_basics['title_separator'] = $options['searchAppearance']['global']['separator'];
                }

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

                // Social settings
                if (isset($options['social'])) {
                    $social_settings = [];

                    if (isset($options['social']['facebook']['general']['facebookUrl'])) {
                        $social_settings['facebook_page_url'] = $options['social']['facebook']['general']['facebookUrl'];
                    }
                    if (isset($options['social']['twitter']['general']['twitterUsername'])) {
                        $social_settings['twitter_username'] = str_replace('@', '', $options['social']['twitter']['general']['twitterUsername']);
                    }

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

                if (isset($options['social']['facebook']['general']['facebookPageUrl'])) {
                    $site_basics['facebook_page_url'] = $options['social']['facebook']['general']['facebookPageUrl'];
                }
                if (isset($options['social']['twitter']['general']['twitterCard'])) {
                    $site_basics['twitter_username'] = str_replace('@', '', (string) $options['social']['twitter']['general']['twitterCard']);
                }
            }
        }

        // Legacy AIOSEO Pack options
        $legacy = get_option('aioseop_options');
        if ($legacy && is_array($legacy)) {
            $settings = get_option('prorank_seo_settings', []);

            if (isset($legacy['aiosp_title_separator'])) {
                $settings['title_separator'] = $legacy['aiosp_title_separator'];
            }

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

        $this->merge_site_basics($site_basics);
    }

    /**
     * Import AIOSEO redirects
     *
     * @return void
     */
    protected function import_redirects(): void {
        global $wpdb;

        // AIOSEO Pro stores redirects in aioseo_redirects table
        $table = $wpdb->prefix . 'aioseo_redirects';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
            return;
        }

        $redirects = $wpdb->get_results(
            "SELECT * FROM {$table} WHERE enabled = 1"
        );

        foreach ($redirects as $redirect) {
            $source_urls = json_decode($redirect->source_url, true);
            $from_url = is_array($source_urls) && isset($source_urls[0]['url'])
                ? $source_urls[0]['url']
                : $redirect->source_url;

            $prorank_redirect = [
                'from' => sanitize_text_field($from_url),
                'to' => esc_url_raw($redirect->target_url),
                'type' => intval($redirect->type),
                'created' => current_time('mysql'),
            ];

            if ($this->save_redirect($prorank_redirect)) {
                $this->stats['redirects']++;
            }
        }
    }

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

        if ($aioseo_options) {
            $options = is_string($aioseo_options) ? json_decode($aioseo_options, true) : $aioseo_options;

            if (is_array($options) && isset($options['searchAppearance']['global']['schema'])) {
                $schema = $options['searchAppearance']['global']['schema'];
                $prorank_schema = [];

                if (isset($schema['siteRepresents'])) {
                    $prorank_schema['site_representation'] = $schema['siteRepresents'];
                }

                if (isset($schema['organizationName'])) {
                    $prorank_schema['organization_name'] = $schema['organizationName'];
                }

                if (isset($schema['organizationLogo'])) {
                    $prorank_schema['organization_logo'] = $schema['organizationLogo'];
                }

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

    /**
     * Map meta key
     *
     * @param string $competitor_key AIOSEO 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);
    }
}
