<?php
namespace ZS_SEO\AuditOptimization\Admin;

defined( 'ABSPATH' ) || exit;

class Assets {

    public function __construct() {
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
        add_action( 'add_meta_boxes',        [ $this, 'add_meta_box' ] );
        add_action( 'save_post',             [ $this, 'save_meta_box' ] );
    }

    public function enqueue( string $hook ): void {
        $zs_seo_pages = [
            'toplevel_page_zs-seo-audit-optimization',
            'zs_seo_page_zs-seo-audit-optimization-audit',
            'zs_seo_page_zs-seo-audit-optimization-images',
            'zs_seo_page_zs-seo-audit-optimization-redirects',
            'zs_seo_page_zs-seo-audit-optimization-settings',
            'zs_seo_page_zs-seo-audit-optimization-pricing',
        ];
        $is_edit_page = in_array( $hook, [ 'post.php', 'post-new.php' ], true );

        if ( ! in_array( $hook, $zs_seo_pages, true ) && ! $is_edit_page ) return;

        wp_enqueue_style(
            'zs-seo-admin',
            ZS_SEO_ASSETS . 'css/admin.css',
            [],
            ZS_SEO_VERSION
        );

        wp_enqueue_script(
            'zs-seo-admin',
            ZS_SEO_ASSETS . 'js/admin.js',
            [ 'jquery' ],
            ZS_SEO_VERSION,
            true
        );

        // Get Freemius upgrade URL
        $pro_url = '#';
        if ( function_exists( 'zs_seo_fs' ) ) {
            try {
                $pro_url = zs_seo_fs()->get_upgrade_url();
            } catch ( \Exception $e ) {
                $pro_url = admin_url( 'admin.php?page=zs-seo-pricing' );
            }
        }

        wp_localize_script( 'zs-seo-admin', 'ZS_SEO', [
            'ajax_url'  => admin_url( 'admin-ajax.php' ),
            'nonce'     => wp_create_nonce( 'zs_seo_nonce' ),
            'is_pro'    => zs_seo_is_pro() ? 'yes' : 'no',
            'pro_url'   => esc_url( $pro_url ),
            'images_url'=> admin_url( 'admin.php?page=zs-seo-audit-optimization-images' ),
            'i18n'      => [
                'analyzing' => __('Analyzing...', 'zs-seo-audit-optimization'),
                'error'     => __('Something went wrong. Try again.', 'zs-seo-audit-optimization'),
            ],
        ] );
    }

    // ── Post Meta Box ─────────────────────────────────────────────────────────
    public function add_meta_box(): void {
        foreach ( [ 'post', 'page' ] as $screen ) {
            add_meta_box(
                'zs_seo_meta_box',
                __('🔍 ZS_SEO — SEO & GEO Settings', 'zs-seo-audit-optimization'),
                [ $this, 'render_meta_box' ],
                $screen,
                'normal',
                'high'
            );
        }
    }

    public function render_meta_box( \WP_Post $post ): void {
        wp_nonce_field( 'zs_seo_meta_box', 'zs_seo_meta_nonce' );

        $title     = get_post_meta( $post->ID, '_zs_seo_title',       true );
        $desc      = get_post_meta( $post->ID, '_zs_seo_description', true );
        $canonical = get_post_meta( $post->ID, '_zs_seo_canonical',   true );
        $noindex   = get_post_meta( $post->ID, '_zs_seo_noindex',     true );
        $nofollow  = get_post_meta( $post->ID, '_zs_seo_nofollow',    true );
        $faqs_raw  = get_post_meta( $post->ID, '_zs_seo_faqs',        true );
        $faqs      = is_array( $faqs_raw ) ? $faqs_raw : [];

        require_once ZS_SEO_DIR . 'templates/meta-box.php';
    }

    public function save_meta_box( int $post_id ): void {
        if ( ! isset( $_POST['zs_seo_meta_nonce'] ) ) return;
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['zs_seo_meta_nonce'] ) ), 'zs_seo_meta_box' ) ) return;
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;

        $fields = [
            '_zs_seo_title'       => 'sanitize_text_field',
            '_zs_seo_description' => 'sanitize_textarea_field',
            '_zs_seo_canonical'   => 'esc_url_raw',
        ];

        foreach ( $fields as $key => $sanitizer ) {
            $field = str_replace( '_zs_seo_', '', $key );
            if ( isset( $_POST[ 'zs_seo_' . $field ] ) ) {
                $raw_value = wp_unslash( $_POST[ 'zs_seo_' . $field ] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                if ( $sanitizer === 'sanitize_text_field' ) {
                    $val = sanitize_text_field( $raw_value );
                } elseif ( $sanitizer === 'sanitize_textarea_field' ) {
                    $val = sanitize_textarea_field( $raw_value );
                } else {
                    $val = esc_url_raw( $raw_value );
                }
                update_post_meta( $post_id, $key, $val );
            }
        }

        update_post_meta( $post_id, '_zs_seo_noindex',  isset( $_POST['zs_seo_noindex']  ) ? 1 : 0 );
        update_post_meta( $post_id, '_zs_seo_nofollow', isset( $_POST['zs_seo_nofollow'] ) ? 1 : 0 );

        $raw_faq_questions = isset( $_POST['zs_seo_faq_question'] ) ? wp_unslash( $_POST['zs_seo_faq_question'] ) : []; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        if ( is_array( $raw_faq_questions ) && ! empty( $raw_faq_questions ) ) {
            $faqs = [];
            $raw_faq_answers = isset( $_POST['zs_seo_faq_answer'] ) ? wp_unslash( $_POST['zs_seo_faq_answer'] ) : []; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            foreach ( $raw_faq_questions as $i => $question ) {
                $q = sanitize_text_field( $question );
                $a = isset( $raw_faq_answers[ $i ] ) ? wp_kses_post( $raw_faq_answers[ $i ] ) : '';
                if ( $q && $a ) {
                    $faqs[] = [ 'question' => $q, 'answer' => $a ];
                }
            }
            update_post_meta( $post_id, '_zs_seo_faqs', $faqs );
        }
    }
}
