<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\helpers\ImageHelpers;
use SEOAIC\repositories\PostRepository;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SEOAIC_POSTS;
use SEOAIC\SEOAIC_SETTINGS;
use SEOAIC_FRAMES;
use WP_REST_Request;
use WP_REST_Response;
use SEOAIC\posts_mass_actions\ThumbnailsGenerate;

class Posts
{
    private $seoaic;

    public function __construct($seoaic)
    {
        $this->seoaic = $seoaic;

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/posts/count', [
                'methods' => 'GET',
                'callback' => [$this, 'get_post_count'],
                'permission_callback' => '__return_true',
            ]);

            register_rest_route('seoaic/v1', '/post/(?P<post_id>\d+)/thumbnail-generate', [
                'methods' => 'POST',
                'callback' => [$this, 'generateThumbnail'],
                'permission_callback' => function () {
                    return current_user_can('edit_posts');
                },
                'args' => array(
                    'post_id' => array(
                        'validate_callback' => function($param) {
                            return is_numeric($param);
                        }
                    ),
                ),
            ]);

            register_rest_route('seoaic/v1', '/posts/titles-from-urls', [
                'methods' => 'POST',
                'callback' => [$this, 'get_page_titles_by_urls'],
                'permission_callback' => '__return_true',
            ]);
        });
    }

    public function get_post_count() {
        global $SEOAIC;
        $results = $SEOAIC->posts->get_post_statuses_with_dates(false);

        if (empty($results)) {
            return new WP_REST_Response(Result::error(__FUNCTION__, esc_html__('No data found', 'seoaic')));
        }

        return new WP_REST_Response(Result::success('dates', 'OK', $results));
    }

    public function generateThumbnail(WP_REST_Request $request)
    {
        try {
            $jsonParams = $request->get_json_params();
            $params = $request->get_params();
            $postID = !empty($params['post_id']) ? $params['post_id'] : '';
            $prompt = !empty($jsonParams['prompt']) ? $jsonParams['prompt'] : '';
            $style = !empty($jsonParams['style']) ? $jsonParams['style'] : '';
            $width = !empty($jsonParams['width'])
                ? (int)$jsonParams['width']
                : ThumbnailsGenerate::DEFAULT_THUMBNAIL_WIDTH;
            $height = !empty($jsonParams['height'])
                ? (int)$jsonParams['height']
                : ThumbnailsGenerate::DEFAULT_THUMBNAIL_HEIGHT;

            if (empty($postID)) {
                throw new Exception("Empty post ID");
            }

            $posts = get_posts([
                'numberposts'   => -1,
                'post_type'     => seoaic_get_post_types(),
                'post_status'   => SEOAIC_POSTS::ANY_STATUS,
                'include'       => [$postID],
                'lang'          => '',
                'meta_query' => [ // all posts, without hiding feature
                    'relation' => 'OR',
                    [
                        'key' => 'seoaic_posted',
                        'compare' => 'EXISTS'
                    ],
                    [
                        'key' => 'seoaic_posted',
                        'compare' => 'NOT EXISTS'
                    ],
                ]
            ]);

            if (empty($posts)) {
                throw new Exception(esc_html__("Post not found or new post is not saved yet.", "seoaic"));
            }

            $post = $posts[0];
            $ideaContent = get_post_meta($post->ID, 'seoaic_idea_content', true);
            if (!empty($ideaContent)) {
                $ideaContent = json_decode($ideaContent, true);
            } else {
                $ideaContent = [];
            }

            $data = [
                'post_title'        => $post->post_title,
                'language'          => $this->seoaic->multilang->get_post_language($post->ID),
                'company_name'      => SEOAIC_SETTINGS::getBusinessName(),
                'company_desc'      => SEOAIC_SETTINGS::getBusinessDescription(),
                'industry'          => SEOAIC_SETTINGS::getIndustry(),
                'domain'            => $_SERVER['HTTP_HOST'],
                'keywords'          => !empty($ideaContent['idea_keywords']) ? implode(',', $ideaContent['idea_keywords']) : '',
                'meta_description'  => !empty($ideaContent['idea_description']) ? $ideaContent['idea_description'] : '',
                'subtitles'         => !empty($ideaContent['idea_skeleton']) ? SEOAIC_FRAMES::formatWithOutlines($ideaContent['idea_skeleton']) : [],
                'with_outlines'     => true,
                'image_style'       => $style ?? SEOAIC_SETTINGS::getImageGenerateStyle(),
                'width'             => SEOAIC_SETTINGS::getImageGenerateWidthDefault(),
                'height'            => SEOAIC_SETTINGS::getImageGenerateHeightDefault(),
                'prompt'            => $prompt,
                'thumbnail_generator' => 'flux',
            ];

            if (checkSizeOfImage($width, $height)) {
                $data['width'] = $width;
                $data['height'] = $height;
            }

            $response = $this->seoaic->curl->initWithReturn('/api/ai/post-thumbnail', $data, true);
            $this->seoaic->curl->validateResponse($response, true);

            if (empty($response['content'])) {
                throw new Exception(esc_html__("Empty content", "seoaic"));
            }

            $alt = !empty($response['content']['alt']) ? $response['content']['alt'] : '';
            $readableFilename = !empty($response['content']['filename']) ? $response['content']['filename'] : '';

            // save image
            $result = ImageHelpers::uploadFromURL(
                $response['content']['url'],
                [
                    'post_title'        => $response['content']['title'],
                    'readable_filename' => $readableFilename,
                ],
                [
                    'alt' => $alt,
                ]
            );

            return new WP_REST_Response(Result::success(__FUNCTION__, esc_html__('OK', 'seoaic'), [
                'image' => $response['content'],
                'attachment' => $result,
            ]));

        } catch (Exception $e) {
            return new WP_REST_Response(Result::error(__FUNCTION__, $e->getMessage()));
        }
    }

    function get_page_titles_by_urls(WP_REST_Request $request) {
        $postsRepository = new PostRepository();
        $urls = $request->get_param('urls');

        if (empty($urls) || !is_array($urls)) {
            return new WP_REST_Response(['error' => 'Invalid input. Provide an array of URLs.'], 400);
        }

        $results = [];

        foreach ($urls as $url) {
            $results[$url] = $url;
            $post_id = url_to_postid($url);

            if ($post_id) {
                $title = get_the_title($post_id);
                $results[$url] = $title;
            }
        }

        return new WP_REST_Response(Result::success('dates', 'OK', $results));
    }
}
