<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Linkquiver_SEO_Handler {

    /**
     * Detect which SEO plugin is active.
     *
     * @return array{plugin: string, active: bool}
     */
    public function detect() {
        if ( defined( 'RANK_MATH_VERSION' ) || class_exists( 'RankMath' ) ) {
            return array(
                'plugin'  => 'rank_math',
                'active'  => true,
                'version' => defined( 'RANK_MATH_VERSION' ) ? RANK_MATH_VERSION : 'unknown',
            );
        }

        if ( defined( 'WPSEO_VERSION' ) || class_exists( 'WPSEO_Meta' ) ) {
            return array(
                'plugin'  => 'yoast',
                'active'  => true,
                'version' => defined( 'WPSEO_VERSION' ) ? WPSEO_VERSION : 'unknown',
            );
        }

        if ( defined( 'AIOSEO_VERSION' ) ) {
            return array(
                'plugin'  => 'aioseo',
                'active'  => true,
                'version' => AIOSEO_VERSION,
            );
        }

        if ( defined( 'SEOPRESS_VERSION' ) || function_exists( 'seopress_init' ) ) {
            return array(
                'plugin'  => 'seopress',
                'active'  => true,
                'version' => defined( 'SEOPRESS_VERSION' ) ? SEOPRESS_VERSION : 'unknown',
            );
        }

        return array(
            'plugin' => 'none',
            'active' => false,
        );
    }

    /**
     * Update SEO meta for a post. Auto-detects the SEO plugin and uses
     * the appropriate meta keys.
     *
     * @param int    $post_id
     * @param string $title
     * @param string $description
     * @param string $focus_keyword
     * @return array
     */
    public function update( $post_id, $title, $description, $focus_keyword = '' ) {
        $post = get_post( $post_id );
        if ( ! $post ) {
            return array(
                'success' => false,
                'error'   => 'Post not found.',
            );
        }

        $detected = $this->detect();
        $plugin   = $detected['plugin'];
        $updated  = array();

        switch ( $plugin ) {
            case 'rank_math':
                $updated = $this->update_rank_math( $post_id, $title, $description, $focus_keyword );
                break;

            case 'yoast':
                $updated = $this->update_yoast( $post_id, $title, $description, $focus_keyword );
                break;

            case 'aioseo':
                $updated = $this->update_aioseo( $post_id, $title, $description, $focus_keyword );
                break;

            case 'seopress':
                $updated = $this->update_seopress( $post_id, $title, $description );
                break;

            default:
                // No SEO plugin: store as standard post meta
                if ( $title ) {
                    update_post_meta( $post_id, '_linkquiver_seo_title', $title );
                    $updated[] = '_linkquiver_seo_title';
                }
                if ( $description ) {
                    update_post_meta( $post_id, '_linkquiver_seo_description', $description );
                    $updated[] = '_linkquiver_seo_description';
                }
                break;
        }

        return array(
            'success'    => true,
            'seo_plugin' => $plugin,
            'post_id'    => $post_id,
            'updated'    => $updated,
        );
    }

    private function update_rank_math( $post_id, $title, $description, $focus_keyword ) {
        $updated = array();

        if ( $title ) {
            update_post_meta( $post_id, 'rank_math_title', $title );
            $updated[] = 'rank_math_title';
        }
        if ( $description ) {
            update_post_meta( $post_id, 'rank_math_description', $description );
            $updated[] = 'rank_math_description';
        }
        if ( $focus_keyword ) {
            update_post_meta( $post_id, 'rank_math_focus_keyword', $focus_keyword );
            $updated[] = 'rank_math_focus_keyword';
        }

        return $updated;
    }

    private function update_yoast( $post_id, $title, $description, $focus_keyword ) {
        $updated = array();

        if ( $title ) {
            update_post_meta( $post_id, '_yoast_wpseo_title', $title );
            $updated[] = '_yoast_wpseo_title';
        }
        if ( $description ) {
            update_post_meta( $post_id, '_yoast_wpseo_metadesc', $description );
            $updated[] = '_yoast_wpseo_metadesc';
        }
        if ( $focus_keyword ) {
            update_post_meta( $post_id, '_yoast_wpseo_focuskw', $focus_keyword );
            $updated[] = '_yoast_wpseo_focuskw';
        }

        return $updated;
    }

    private function update_aioseo( $post_id, $title, $description, $focus_keyword ) {
        global $wpdb;

        $updated    = array();
        $table_name = $wpdb->prefix . 'aioseo_posts';

        // Check if the AIOSEO custom table exists
        $table_exists = $wpdb->get_var(
            $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
        ) === $table_name;

        if ( $table_exists ) {
            // Check if a row exists for this post
            $existing = $wpdb->get_var(
                $wpdb->prepare( "SELECT id FROM {$table_name} WHERE post_id = %d", $post_id )
            );

            $data = array();
            if ( $title ) {
                $data['title'] = $title;
            }
            if ( $description ) {
                $data['description'] = $description;
            }
            if ( $focus_keyword ) {
                $data['keyphrases'] = wp_json_encode( array(
                    'focus'      => array( 'keyphrase' => $focus_keyword, 'score' => 0 ),
                    'additional' => array(),
                ) );
            }

            if ( ! empty( $data ) ) {
                $data['updated'] = current_time( 'mysql' );

                if ( $existing ) {
                    $wpdb->update( $table_name, $data, array( 'post_id' => $post_id ) );
                } else {
                    $data['post_id'] = $post_id;
                    $data['created']  = current_time( 'mysql' );
                    $wpdb->insert( $table_name, $data );
                }

                $updated[] = 'aioseo_posts_table';
            }
        }

        // Also update postmeta for compatibility (WPML, migrations, etc.)
        if ( $title ) {
            update_post_meta( $post_id, '_aioseo_title', $title );
            $updated[] = '_aioseo_title';
        }
        if ( $description ) {
            update_post_meta( $post_id, '_aioseo_description', $description );
            $updated[] = '_aioseo_description';
        }
        if ( $focus_keyword ) {
            update_post_meta( $post_id, '_aioseo_keyphrases', wp_json_encode( array(
                array( 'keyphrase' => $focus_keyword, 'score' => 0 ),
            ) ) );
            $updated[] = '_aioseo_keyphrases';
        }

        return $updated;
    }

    private function update_seopress( $post_id, $title, $description ) {
        $updated = array();

        if ( $title ) {
            update_post_meta( $post_id, '_seopress_titles_title', $title );
            $updated[] = '_seopress_titles_title';
        }
        if ( $description ) {
            update_post_meta( $post_id, '_seopress_titles_desc', $description );
            $updated[] = '_seopress_titles_desc';
        }

        return $updated;
    }
}
