<?php
/**
 * All in One SEO migration adapter.
 *
 * Modern AIOSEO (4.x) stores per-post meta in `wp_aioseo_posts` and redirects
 * in `wp_aioseo_redirects`. Older versions used `_aioseop_*` postmeta keys —
 * we read both shapes for safety.
 *
 * @package Brainwerk SEO Suite
 */

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

class Seoforge_Migrate_AIOSEO {

    public static function source_label() {
        return 'All in One SEO';
    }

    public static function is_available() {
        global $wpdb;
        return defined( 'AIOSEO_VERSION' )
            || (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'aioseo_posts' ) );
    }

    private static function table() {
        global $wpdb;
        return $wpdb->prefix . 'aioseo_posts';
    }

    public static function count_posts() {
        global $wpdb;
        $tbl = self::table();
        if ( ! $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tbl ) ) ) {
            return (int) $wpdb->get_var( "SELECT COUNT(DISTINCT post_id) FROM {$wpdb->postmeta} WHERE meta_key LIKE '_aioseop_%'" );
        }
        return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $tbl ) );
    }

    public static function count_redirects() {
        return count( self::list_redirects() );
    }

    public static function map_post_meta( $post_id ) {
        global $wpdb;
        $tbl = self::table();
        $row = array();

        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tbl ) ) ) {
            $r = $wpdb->get_row( $wpdb->prepare(
                "SELECT title, description, keyphrases, og_title, og_description, og_image_custom_url, canonical_url, robots_noindex, robots_nofollow
                 FROM %i WHERE post_id = %d LIMIT 1",
                $tbl,
                (int) $post_id
            ), ARRAY_A );
            if ( $r ) {
                if ( ! empty( $r['title'] ) )           { $row['seo_title']       = self::expand_aioseo_vars( $r['title'] ); }
                if ( ! empty( $r['description'] ) )     { $row['seo_description'] = self::expand_aioseo_vars( $r['description'] ); }
                if ( ! empty( $r['keyphrases'] ) ) {
                    $kp = json_decode( $r['keyphrases'], true );
                    if ( is_array( $kp ) && ! empty( $kp['focus']['keyphrase'] ) ) {
                        $row['focus_keyword'] = (string) $kp['focus']['keyphrase'];
                    }
                }
                if ( ! empty( $r['og_title'] ) )        { $row['og_title']       = self::expand_aioseo_vars( $r['og_title'] ); }
                if ( ! empty( $r['og_description'] ) )  { $row['og_description'] = self::expand_aioseo_vars( $r['og_description'] ); }
                if ( ! empty( $r['og_image_custom_url'] ) ) { $row['og_image']   = $r['og_image_custom_url']; }
                if ( ! empty( $r['canonical_url'] ) )   { $row['canonical']      = $r['canonical_url']; }
                if ( (int) $r['robots_noindex'] === 1 ) { $row['robots_noindex']  = 1; }
                if ( (int) $r['robots_nofollow'] === 1 ){ $row['robots_nofollow'] = 1; }
                return $row;
            }
        }

        // Fallback: legacy postmeta keys
        $title = get_post_meta( $post_id, '_aioseop_title', true );
        $desc  = get_post_meta( $post_id, '_aioseop_description', true );
        $kw    = get_post_meta( $post_id, '_aioseop_keywords', true );
        $noindex = get_post_meta( $post_id, '_aioseop_noindex', true );
        if ( $title ) { $row['seo_title']       = self::expand_aioseo_vars( $title ); }
        if ( $desc )  { $row['seo_description'] = self::expand_aioseo_vars( $desc ); }
        if ( $kw )    { $row['focus_keyword']   = trim( (string) explode( ',', $kw )[0] ); }
        if ( 'on' === $noindex ) { $row['robots_noindex'] = 1; }
        return $row;
    }

    public static function expand_aioseo_vars( $tpl ) {
        $tpl = (string) $tpl;
        $repl = array(
            '#site_title#'        => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
            '#tagline#'           => wp_specialchars_decode( get_bloginfo( 'description' ), ENT_QUOTES ),
            '#separator_sa#'      => '–',
            '#current_year#'      => date_i18n( 'Y' ),
            '#current_date#'      => date_i18n( get_option( 'date_format' ) ),
        );
        return strtr( $tpl, $repl );
    }

    public static function list_redirects() {
        global $wpdb;
        $tbl = $wpdb->prefix . 'aioseo_redirects';
        if ( ! $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tbl ) ) ) {
            return array();
        }
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT source_url, target_url, type FROM %i WHERE redirect_option = 'redirect' OR redirect_option IS NULL LIMIT 5000",
                $tbl
            ),
            ARRAY_A
        );
        $out = array();
        foreach ( (array) $rows as $r ) {
            if ( empty( $r['source_url'] ) || empty( $r['target_url'] ) ) { continue; }
            $type = (int) $r['type'];
            $out[] = array(
                'source_path' => '/' . ltrim( (string) $r['source_url'], '/' ),
                'target_url'  => (string) $r['target_url'],
                'status_code' => in_array( $type, array( 301, 302, 307, 308 ), true ) ? $type : 301,
                'match_type'  => 'exact',
                'note'        => 'imported from AIOSEO',
            );
        }
        return $out;
    }
}
