<?php
namespace AIFI;

/**
 * Handles REST API endpoints for AI image generation.
 *
 * @package AIFI
 */
class REST {
    /**
     * Initialize REST API.
     */
    public function __construct() {
        add_action('rest_api_init', array($this, 'register_routes'));
    }

    /**
     * Register REST API routes.
     */
    public function register_routes() {
        register_rest_route('aifi/v1', '/validate-key', array(
            'methods' => 'POST',
            'callback' => array($this, 'validate_api_key'),
            'permission_callback' => function() {
                return current_user_can('manage_options');
            },
            'args' => array(
                'provider' => array(
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
                'api_key' => array(
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
            ),
        ));

        register_rest_route('aifi/v1', '/upscale', array(
            'methods' => 'POST',
            'callback' => array($this, 'upscale_image'),
            'permission_callback' => array($this, 'check_permission'),
            'args' => array(
                'post_id' => array(
                    'required' => true,
                    'type' => 'integer',
                    'sanitize_callback' => 'absint',
                ),
                'mode' => array(
                    'required' => false,
                    'type' => 'string',
                    'default' => 'conservative',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
            ),
        ));

        register_rest_route('aifi/v1', '/remove-background', array(
            'methods' => 'POST',
            'callback' => array($this, 'remove_background'),
            'permission_callback' => array($this, 'check_permission'),
            'args' => array(
                'post_id' => array(
                    'required' => true,
                    'type' => 'integer',
                    'sanitize_callback' => 'absint',
                ),
            ),
        ));

        register_rest_route('aifi/v1', '/generate-prompt', array(
            'methods'             => 'POST',
            'callback'            => array($this, 'generate_prompt'),
            'permission_callback' => array($this, 'check_permission'),
            'args'                => array(
                'post_id' => array(
                    'required'          => true,
                    'type'              => 'integer',
                    'sanitize_callback' => 'absint',
                ),
            ),
        ));

        register_rest_route('aifi/v1', '/save-prompt', array(
            'methods'             => 'POST',
            'callback'            => array($this, 'save_prompt'),
            'permission_callback' => array($this, 'check_permission'),
            'args'                => array(
                'post_id' => array(
                    'required'          => true,
                    'type'              => 'integer',
                    'sanitize_callback' => 'absint',
                ),
                'prompt' => array(
                    'required'          => true,
                    'type'              => 'string',
                    'sanitize_callback' => 'sanitize_textarea_field',
                ),
            ),
        ));

        register_rest_route('aifi/v1', '/generate', array(
            'methods' => 'POST',
            'callback' => array($this, 'generate_image'),
            'permission_callback' => array($this, 'check_permission'),
            'args' => array(
                'post_id' => array(
                    'required' => true,
                    'type' => 'integer',
                    'sanitize_callback' => 'absint'
                ),
                'title' => array(
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'prompt' => array(
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'custom_text' => array(
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'style' => array(
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'quality' => array(
                    'required' => false,
                    'type' => 'integer',
                    'sanitize_callback' => function($value) {
                        $quality = intval($value);
                        return max(1, min(100, $quality)); // Ensure quality is between 1 and 100
                    }
                )
            )
        ));
    }

    /**
     * Check if user has permission to generate images.
     *
     * @param \WP_REST_Request $request Request object.
     * @return bool|\WP_Error
     */
    public function check_permission($request) {
        $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 generate images for this post.', 'ai-featured-image-generator'),
                array('status' => rest_authorization_required_code())
            );
        }

        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())
            );
        }

        // Check if the post type is enabled for image generation
        $post = get_post($post_id);
        if (!$post) {
            return new \WP_Error(
                'rest_invalid_post',
                __('Invalid post.', 'ai-featured-image-generator'),
                array('status' => 404)
            );
        }

        $settings = new Settings();
        $enabled_post_types = $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;
    }

    /**
     * Validate an API key by making a lightweight test request.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function validate_api_key($request) {
        $provider = $request['provider'];
        $api_key  = $request['api_key'];

        if (empty($api_key)) {
            return new \WP_Error(
                'empty_key',
                __('Please enter an API key.', 'ai-featured-image-generator'),
                array('status' => 400)
            );
        }

        if ($provider === 'openai') {
            $response = wp_remote_get('https://api.openai.com/v1/models', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $api_key,
                ),
                'timeout' => 15,
            ));
        } elseif ($provider === 'gemini') {
            $response = wp_remote_get(
                'https://generativelanguage.googleapis.com/v1beta/models?key=' . urlencode($api_key),
                array('timeout' => 15)
            );
        } elseif ($provider === 'stability') {
            $response = wp_remote_get('https://api.stability.ai/v1/user/account', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $api_key,
                ),
                'timeout' => 15,
            ));
        } elseif ($provider === 'grok') {
            $response = wp_remote_get('https://api.x.ai/v1/models', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $api_key,
                ),
                'timeout' => 15,
            ));
        } else {
            return new \WP_Error(
                'invalid_provider',
                __('Invalid provider.', 'ai-featured-image-generator'),
                array('status' => 400)
            );
        }

        if (is_wp_error($response)) {
            return new \WP_Error(
                'connection_error',
                __('Could not connect to the API. Please check your internet connection.', 'ai-featured-image-generator'),
                array('status' => 500)
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);

        if ($status_code === 200) {
            $result = array(
                'success' => true,
                'message' => __('API key is valid!', 'ai-featured-image-generator'),
            );

            // Fetch Stability AI credits balance
            if ($provider === 'stability') {
                $balance_response = wp_remote_get('https://api.stability.ai/v1/user/balance', array(
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $api_key,
                    ),
                    'timeout' => 10,
                ));

                if (!is_wp_error($balance_response) && wp_remote_retrieve_response_code($balance_response) === 200) {
                    $balance_data = json_decode(wp_remote_retrieve_body($balance_response), true);
                    if (isset($balance_data['credits'])) {
                        $credits = round((float) $balance_data['credits'], 2);
                        $result['credits'] = $credits;
                        $result['message'] = sprintf(
                            /* translators: %s: credit balance */
                            __('API key is valid! Credits: %s', 'ai-featured-image-generator'),
                            $credits
                        );
                    }
                }
            }

            return rest_ensure_response($result);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $error_message = __('Invalid API key.', 'ai-featured-image-generator');

        if (isset($body['error']['message'])) {
            $error_message = $body['error']['message'];
        } elseif (isset($body['message'])) {
            $error_message = $body['message'];
        }

        return new \WP_Error(
            'invalid_key',
            $error_message,
            array('status' => $status_code)
        );
    }

    /**
     * Generate image via REST API.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function generate_image($request) {
        $post_id = $request['post_id'];
        $title = $request['title'];
        $prompt = $request['prompt'];
        $custom_text = $request['custom_text'];
        $style = $request['style'];
        $quality = $request['quality'];

        // Check for transient lock
        $lock_key = 'aifi_lock_' . $post_id;
        if (get_transient($lock_key)) {
            return new \WP_Error(
                'rest_forbidden',
                __('Please wait a moment before generating another image.', 'ai-featured-image-generator'),
                array('status' => 429)
            );
        }

        // Set transient lock (5 seconds)
        set_transient($lock_key, true, 5);

        // Get settings
        $settings = new Settings();
        $settings_data = $settings->get_settings();

        // Check if appropriate API key is configured based on provider
        $provider = isset($settings_data['ai_provider']) ? $settings_data['ai_provider'] : 'openai';
        
        // Premium check: Gemini is only available for premium users
        if ( $provider === 'gemini' ) {
            if ( ! function_exists('afig_fs') || ! afig_fs()->can_use_premium_code() ) {
                return new \WP_Error(
                    'premium_required',
                    __('Google Gemini is a Pro feature. Please upgrade to use Gemini for image generation, or switch to OpenAI in the plugin settings.', 'ai-featured-image-generator'),
                    array('status' => 403)
                );
            }
        }

        // Map provider to API key field
        $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';

        // Support legacy 'api_key' field for backward compatibility
        if ($provider === 'openai' && empty($settings_data['openai_api_key']) && !empty($settings_data['api_key'])) {
            $api_key_field = 'api_key';
        }

        // Provider labels for error messages
        $provider_labels = array(
            'openai' => 'OpenAI',
            'gemini' => 'Google Gemini',
            'stability' => 'Stability AI',
            'grok' => 'Grok / xAI',
        );
        $provider_label = isset($provider_labels[$provider]) ? $provider_labels[$provider] : $provider;

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

        // Generate image
        $generator = new Generator($settings);
        $result = $generator->generate_image($post_id, $prompt, $style, $title, $custom_text, $quality);

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

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

    /**
     * Upscale featured image via REST API.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function upscale_image($request) {
        $post_id = $request['post_id'];
        $mode = $request['mode'];

        // Premium check: upscaling is Pro only
        if ( ! function_exists('afig_fs') || ! afig_fs()->can_use_premium_code() ) {
            return new \WP_Error(
                'premium_required',
                __('Image upscaling is a Pro feature. Please upgrade to use this feature.', 'ai-featured-image-generator'),
                array('status' => 403)
            );
        }

        // Check for transient lock
        $lock_key = 'aifi_lock_upscale_' . $post_id;
        if (get_transient($lock_key)) {
            return new \WP_Error(
                'rest_forbidden',
                __('Please wait a moment before upscaling another image.', 'ai-featured-image-generator'),
                array('status' => 429)
            );
        }
        set_transient($lock_key, true, 5);

        $settings = new Settings();
        $generator = new Generator($settings);
        $result = $generator->upscale_image($post_id, $mode);

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

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

    /**
     * Remove background from featured image via REST API.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function remove_background($request) {
        $post_id = $request['post_id'];

        // Premium check: background removal is Pro only
        if ( ! function_exists('afig_fs') || ! afig_fs()->can_use_premium_code() ) {
            return new \WP_Error(
                'premium_required',
                __('Background removal is a Pro feature. Please upgrade to use this feature.', 'ai-featured-image-generator'),
                array('status' => 403)
            );
        }

        // Check for transient lock
        $lock_key = 'aifi_lock_rmbg_' . $post_id;
        if (get_transient($lock_key)) {
            return new \WP_Error(
                'rest_forbidden',
                __('Please wait a moment before processing another image.', 'ai-featured-image-generator'),
                array('status' => 429)
            );
        }
        set_transient($lock_key, true, 5);

        $settings = new Settings();
        $generator = new Generator($settings);
        $result = $generator->remove_background($post_id);

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

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

    /**
     * Generate an image prompt from a post's title and body content.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function generate_prompt($request) {
        $post_id = $request['post_id'];

        $settings  = new Settings();
        $generator = new Generator($settings);
        $result    = $generator->generate_prompt_from_content($post_id);

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

        // Persist the generated prompt to post meta
        update_post_meta($post_id, '_aifi_custom_prompt', $result);

        return rest_ensure_response(array(
            'success' => true,
            'prompt'  => $result,
        ));
    }

    /**
     * Save a custom prompt to post meta.
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response|\WP_Error
     */
    public function save_prompt($request) {
        $post_id = $request['post_id'];
        $prompt  = $request['prompt'];

        update_post_meta($post_id, '_aifi_custom_prompt', $prompt);

        return rest_ensure_response(array('success' => true));
    }
}