<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Plugin;

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

class Post_Meta_Box {

    public function __construct() {
        add_action( 'add_meta_boxes', [ $this, 'register_meta_box' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    public function register_meta_box(): void {
        $settings = Plugin::get_settings();

        if ( empty( $settings['modules']['content_steward'] ) ) {
            return;
        }

        $post_types = [ 'post', 'page' ]; // adjust as needed.

        foreach ( $post_types as $post_type ) {
            add_meta_box(
                'aah_content_steward',
                __( 'AtlasAgent', 'ai-workflow-automation-ai-agent-hub' ),
                [ $this, 'render_meta_box' ],
                $post_type,
                'side',
                'high'
            );
        }
    }

    public function render_meta_box( $post ): void {
        $post_id = $post ? (int) $post->ID : 0;

        echo '<div id="aah-content-steward-root" data-post-id="' . esc_attr( $post_id ) . '"></div>';
    }

    public function enqueue_assets( $hook ): void {
        // Only on post editor screens.
        if ( ! in_array( $hook, [ 'post.php', 'post-new.php' ], true ) ) {
            return;
        }

        $screen = get_current_screen();
        if ( ! $screen || ! in_array( $screen->post_type, [ 'post', 'page' ], true ) ) {
            return;
        }

        $settings = Plugin::get_settings();
        if ( empty( $settings['modules']['content_steward'] ) ) {
            return;
        }

        $js  = AWFAH_PLUGIN_URL . 'assets/js/post-meta-box.min.js';
        $css = AWFAH_PLUGIN_URL . 'assets/css/admin.css';

        wp_enqueue_style(
            'ai-workflow-automation-ai-agent-hub-admin',
            $css,
            [],
            AWFAH_VERSION
        );

        wp_enqueue_script(
            'ai-workflow-automation-ai-agent-hub-post-meta-box',
            $js,
            [],
            AWFAH_VERSION,
            true
        );

        global $post;
        $post_id = $post ? (int) $post->ID : 0;

        wp_localize_script(
            'ai-workflow-automation-ai-agent-hub-post-meta-box',
            'aahPostMetaBoxConfig',
            [
                'restUrl'          => esc_url_raw( rest_url( 'awfah/v1' ) ),
                'providersRestUrl' => esc_url_raw( rest_url( 'awfah/v1/providers' ) ),
                'abilitiesRestUrl' => esc_url_raw( rest_url( 'awfah/v1/abilities' ) ),
                'workflowsRestUrl' => esc_url_raw( rest_url( 'awfah/v1/workflows' ) ),
                'wpNonce'              => wp_create_nonce( 'wp_rest' ),
                'postId'               => $post_id,
                'aiProviderConfigured' => class_exists( \WordPress\AI_Client\AI_Client::class ),
            ]
        );
    }
}
