<?php
defined( 'ABSPATH' ) || exit;

class NASEO_SEO_Writer {

    public static function write( int $post_id, array $seo ): void {
        $keyword     = sanitize_text_field( $seo['focus_keyphrase'] ?? '' );
        $title       = sanitize_text_field( $seo['seo_title'] ?? '' );
        $description = sanitize_text_field( $seo['meta_description'] ?? '' );
        $og_title    = sanitize_text_field( $seo['og_title'] ?? '' );
        $og_desc     = sanitize_text_field( $seo['og_description'] ?? '' );
        $tw_title    = sanitize_text_field( $seo['twitter_title'] ?? '' );
        $tw_desc     = sanitize_text_field( $seo['twitter_description'] ?? '' );

        if ( self::has_yoast() ) {
            self::write_yoast( $post_id, $keyword, $title, $description, $og_title, $og_desc, $tw_title, $tw_desc );
            NASEO_Logger::log( 'info', "SEO: Yoast meta saved for post #{$post_id}" );
        }

        if ( self::has_rankmath() ) {
            self::write_rankmath( $post_id, $keyword, $title, $description, $og_title, $og_desc, $tw_title, $tw_desc );
            NASEO_Logger::log( 'info', "SEO: RankMath meta saved for post #{$post_id}" );
        }

        if ( self::has_aioseo() ) {
            self::write_aioseo( $post_id, $keyword, $title, $description, $og_title, $og_desc, $tw_title, $tw_desc );
            NASEO_Logger::log( 'info', "SEO: AIOSEO meta saved for post #{$post_id}" );
        }

        if ( ! self::has_yoast() && ! self::has_rankmath() && ! self::has_aioseo() ) {
            // Жодного SEO плагіна — пишемо базові мета напряму
            update_post_meta( $post_id, '_naseo_seo_title',       $title );
            update_post_meta( $post_id, '_naseo_meta_description', $description );
            update_post_meta( $post_id, '_naseo_focus_keyword',    $keyword );
            NASEO_Logger::log( 'info', "SEO: No SEO plugin found, saved to _naseo_* meta for post #{$post_id}" );
        }

        // Теги — для всіх
        if ( ! empty( $seo['tags'] ) && is_array( $seo['tags'] ) ) {
            $tags = array_map( 'sanitize_text_field', $seo['tags'] );
            wp_set_post_tags( $post_id, $tags, false );
        }
    }

    // ── Yoast SEO ─────────────────────────────────────────────────────────────

    private static function write_yoast( int $post_id, string $keyword, string $title, string $description, string $og_title, string $og_desc, string $tw_title, string $tw_desc ): void {
        $map = [
            '_yoast_wpseo_focuskw'               => $keyword,
            '_yoast_wpseo_title'                 => $title,
            '_yoast_wpseo_metadesc'              => $description,
            '_yoast_wpseo_opengraph-title'       => $og_title,
            '_yoast_wpseo_opengraph-description' => $og_desc,
            '_yoast_wpseo_twitter-title'         => $tw_title,
            '_yoast_wpseo_twitter-description'   => $tw_desc,
        ];
        foreach ( $map as $key => $value ) {
            if ( ! empty( $value ) ) {
                update_post_meta( $post_id, $key, $value );
            }
        }
    }

    // ── RankMath ──────────────────────────────────────────────────────────────

    private static function write_rankmath( int $post_id, string $keyword, string $title, string $description, string $og_title, string $og_desc, string $tw_title, string $tw_desc ): void {
        $map = [
            'rank_math_focus_keyword'      => $keyword,
            'rank_math_title'              => $title,
            'rank_math_description'        => $description,
            'rank_math_facebook_title'     => $og_title,
            'rank_math_facebook_description' => $og_desc,
            'rank_math_twitter_title'      => $tw_title,
            'rank_math_twitter_description' => $tw_desc,
        ];
        foreach ( $map as $key => $value ) {
            if ( ! empty( $value ) ) {
                update_post_meta( $post_id, $key, $value );
            }
        }
    }

    // ── All in One SEO ────────────────────────────────────────────────────────

    private static function write_aioseo( int $post_id, string $keyword, string $title, string $description, string $og_title, string $og_desc, string $tw_title, string $tw_desc ): void {
        // AIOSEO зберігає дані в окремій таблиці aioseo_posts
        global $wpdb;
        $table = $wpdb->prefix . 'aioseo_posts';

        // Перевіряємо чи таблиця існує
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
            // Таблиці немає — пишемо в post_meta (старий формат AIOSEO)
            $legacy_map = [
                '_aioseop_title'       => $title,
                '_aioseop_description' => $description,
                '_aioseop_keywords'    => $keyword,
            ];
            foreach ( $legacy_map as $key => $value ) {
                if ( ! empty( $value ) ) {
                    update_post_meta( $post_id, $key, $value );
                }
            }
            return;
        }

        // AIOSEO v4+ — upsert в таблицю
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $existing = $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM `" . esc_sql( $table ) . "` WHERE post_id = %d", $post_id
        ) );

        $data = [
            'post_id'            => $post_id,
            'title'              => $title,
            'description'        => $description,
            'keywords'           => $keyword,
            'og_title'           => $og_title,
            'og_description'     => $og_desc,
            'twitter_title'      => $tw_title,
            'twitter_description' => $tw_desc,
            'updated'            => current_time( 'mysql' ),
        ];

        if ( $existing ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update( $table, $data, [ 'post_id' => $post_id ] );
        } else {
            $data['created'] = current_time( 'mysql' );
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->insert( $table, $data );
        }
    }

    // ── Перевірки наявності плагінів ──────────────────────────────────────────

    private static function has_yoast(): bool {
        return defined( 'WPSEO_VERSION' )
            || is_plugin_active( 'wordpress-seo/wp-seo.php' )
            || is_plugin_active( 'wordpress-seo-premium/wp-seo-premium.php' );
    }

    private static function has_rankmath(): bool {
        return defined( 'RANK_MATH_VERSION' )
            || is_plugin_active( 'seo-by-rank-math/rank-math.php' );
    }

    private static function has_aioseo(): bool {
        return defined( 'AIOSEO_VERSION' )
            || is_plugin_active( 'all-in-one-seo-pack/all_in_one_seo_pack.php' )
            || is_plugin_active( 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php' );
    }
}
