<?php
namespace AIFI;

/**
 * Adds "Generate AI Image" row actions and a custom AI Image column to the post list table.
 *
 * @package AIFI
 */
class List_Actions {

    /** @var Settings */
    private $settings;

    /** @var Generator */
    private $generator;

    public function __construct( $settings, $generator ) {
        $this->settings  = $settings;
        $this->generator = $generator;

        $post_types = $this->settings->get_enabled_post_types();
        foreach ( $post_types as $post_type ) {
            add_filter( "manage_{$post_type}_posts_columns",       array( $this, 'add_column' ) );
            add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'render_column' ), 10, 2 );
        }

        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'rest_api_init',         array( $this, 'register_routes' ) );
    }

    /**
     * Append "AI Featured Image" as the last column.
     */
    public function add_column( $columns ) {
        $columns['aifi_image'] = __( 'AI Featured Image', 'ai-featured-image-generator' );
        return $columns;
    }

    /**
     * Render the AI Image column cell.
     *
     * @param string $column  Column slug.
     * @param int    $post_id Post ID.
     */
    public function render_column( $column, $post_id ) {
        if ( $column !== 'aifi_image' ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        $has_thumb   = has_post_thumbnail( $post_id );
        $thumb_url   = $has_thumb ? get_the_post_thumbnail_url( $post_id, array( 60, 60 ) ) : '';
        $link_label  = $has_thumb
            ? __( 'Regenerate Image', 'ai-featured-image-generator' )
            : __( 'Generate Image', 'ai-featured-image-generator' );

        echo '<div class="aifi-col-cell">';

        if ( $has_thumb ) {
            printf(
                '<img class="aifi-list-thumb" src="%s" alt="" width="60" height="60">',
                esc_url( $thumb_url )
            );
        } else {
            echo '<span class="aifi-no-image">' . esc_html__( 'No image', 'ai-featured-image-generator' ) . '</span>';
        }

        printf(
            '<a href="#" class="aifi-generate-link" data-post-id="%d" data-has-thumbnail="%d">%s</a>',
            absint( $post_id ),
            $has_thumb ? 1 : 0,
            esc_html( $link_label )
        );

        echo '</div>';
    }

    /**
     * Enqueue scripts and styles on the post list screen for enabled post types.
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_scripts( $hook ) {
        if ( $hook !== 'edit.php' ) {
            return;
        }

        $screen = get_current_screen();
        if ( ! $screen || empty( $screen->post_type ) ) {
            return;
        }

        $enabled_post_types = $this->settings->get_enabled_post_types();
        if ( ! in_array( $screen->post_type, $enabled_post_types, true ) ) {
            return;
        }

        wp_enqueue_style(
            'aifi-admin',
            AIFI_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            AIFI_VERSION
        );

        wp_enqueue_script(
            'aifi-list',
            AIFI_PLUGIN_URL . 'assets/js/admin-list.js',
            array( 'jquery' ),
            AIFI_VERSION,
            true
        );

        wp_localize_script( 'aifi-list', 'aifiListData', array(
            'nonce'   => wp_create_nonce( 'wp_rest' ),
            'restUrl' => rest_url( 'aifi/v1/list-generate' ),
            'i18n'    => array(
                'generating'      => __( 'Generating…', 'ai-featured-image-generator' ),
                'success'         => __( 'Image generated!', 'ai-featured-image-generator' ),
                'error'           => __( 'Error generating image. Please try again.', 'ai-featured-image-generator' ),
                'confirmOverwrite' => __( 'This will replace your current featured image. Continue?', 'ai-featured-image-generator' ),
                'regenerate'      => __( 'Regenerate Image', 'ai-featured-image-generator' ),
                'generate'        => __( 'Generate Image', 'ai-featured-image-generator' ),
            ),
        ) );
    }

    /**
     * Register the list-generate REST endpoint.
     */
    public function register_routes() {
        register_rest_route( 'aifi/v1', '/list-generate', array(
            'methods'             => 'POST',
            'callback'            => array( $this, 'list_generate_image' ),
            'permission_callback' => array( $this, 'check_permission' ),
            'args'                => array(
                'post_id' => array(
                    'required'          => true,
                    'type'              => 'integer',
                    'sanitize_callback' => 'absint',
                ),
            ),
        ) );
    }

    /**
     * Permission callback for list-generate endpoint.
     *
     * @param \WP_REST_Request $request Request object.
     * @return bool|\WP_Error
     */
    public function check_permission( $request ) {
        if ( ! wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
            return new \WP_Error(
                'rest_forbidden',
                __( 'Invalid nonce.', 'ai-featured-image-generator' ),
                array( 'status' => rest_authorization_required_code() )
            );
        }

        $post_id = absint( $request['post_id'] );

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return new \WP_Error(
                'rest_forbidden',
                __( 'Sorry, you are not allowed to edit this post.', 'ai-featured-image-generator' ),
                array( 'status' => rest_authorization_required_code() )
            );
        }

        $post = get_post( $post_id );
        if ( ! $post ) {
            return new \WP_Error(
                'rest_invalid_post',
                __( 'Invalid post.', 'ai-featured-image-generator' ),
                array( 'status' => 404 )
            );
        }

        $enabled_post_types = $this->settings->get_enabled_post_types();
        if ( ! in_array( $post->post_type, $enabled_post_types, true ) ) {
            return new \WP_Error(
                'rest_post_type_not_enabled',
                __( 'AI image generation is not enabled for this post type.', 'ai-featured-image-generator' ),
                array( 'status' => 403 )
            );
        }

        return true;
    }

    /**
     * Generate AI featured image for a single post from the list screen.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function list_generate_image( $request ) {
        $post_id = $request['post_id'];

        // Rate-limit per post (shared with the main /generate endpoint)
        $lock_key = 'aifi_lock_' . $post_id;
        if ( get_transient( $lock_key ) ) {
            return new \WP_Error(
                'rate_limited',
                __( 'Please wait a moment before generating another image.', 'ai-featured-image-generator' ),
                array( 'status' => 429 )
            );
        }
        set_transient( $lock_key, true, 5 );

        $post          = get_post( $post_id );
        $settings_data = $this->settings->get_settings();
        $provider      = isset( $settings_data['ai_provider'] ) ? $settings_data['ai_provider'] : 'openai';

        // Gemini is Pro-only — fall back silently for free users (matches bulk behaviour)
        if ( $provider === 'gemini' && ! ( function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code() ) ) {
            $provider = 'openai';
        }

        $api_key_fields = array(
            'openai'    => 'openai_api_key',
            'gemini'    => 'gemini_api_key',
            'stability' => 'stability_api_key',
            'grok'      => 'grok_api_key',
        );
        $api_key_field = isset( $api_key_fields[ $provider ] ) ? $api_key_fields[ $provider ] : 'openai_api_key';

        // Legacy OpenAI key fallback
        if ( $provider === 'openai' && empty( $settings_data['openai_api_key'] ) && ! empty( $settings_data['api_key'] ) ) {
            $api_key_field = 'api_key';
        }

        $provider_labels = array(
            'openai'    => 'OpenAI',
            'gemini'    => 'Google Gemini',
            'stability' => 'Stability AI',
            'grok'      => 'Grok (xAI)',
        );

        if ( empty( $settings_data[ $api_key_field ] ) ) {
            return new \WP_Error(
                'no_api_key',
                sprintf(
                    __( 'API key not configured for %s. Please configure it in the plugin settings.', 'ai-featured-image-generator' ),
                    isset( $provider_labels[ $provider ] ) ? $provider_labels[ $provider ] : $provider
                ),
                array( 'status' => 400 )
            );
        }

        // Auto-generate prompt from content + title
        $prompt = '';
        $prompt_result = $this->generator->generate_prompt_from_content( $post_id );
        if ( is_wp_error( $prompt_result ) ) {
            error_log( 'AIFI list-generate: prompt generation failed for post ' . $post_id . ': ' . $prompt_result->get_error_message() );
        } else {
            $prompt = $prompt_result;
            update_post_meta( $post_id, '_aifi_custom_prompt', $prompt );
        }

        $result = $this->generator->generate_image( $post_id, $prompt, '', $post->post_title, '', null );

        if ( is_wp_error( $result ) ) {
            return $result;
        }

        return rest_ensure_response( array(
            'success'       => true,
            'attachment_id' => $result,
            'thumbnail_url' => wp_get_attachment_image_url( $result, array( 60, 60 ) ),
            'url'           => wp_get_attachment_url( $result ),
        ) );
    }
}
