<?php

namespace RistrettoApps\Spawnster\Services;

use RistrettoApps\Spawnster\Base\Constants;
use RistrettoApps\Spawnster\Interfaces\ConstantsTrait;

/**
 * The service which parses the response from OpenAI.
 *
 * Generates the pages and parses the response as content.
 *
 * @package    Spawnster
 * @subpackage Spawnster/public
 * @author     Ristretto Apps
 */
class GenerateContent
{
    use ConstantsTrait;

    /**
     * Use the OpenAI service to handle the post request.
     *
     * @param  array  $request
     * @return bool|null
     *
     * @since 1.0.0
     */
    public function handle(array $request)
    {
        if (!$request) {
            return null;
        }

        try {
            $openAIService = new OpenAiService();
            $openAIService->content = $this->formatContent($request['page_name'], $request['page_description']);

            $response = $openAIService->getResponse();

            $option_key = Constants::SPAWNSTER_SETUP_YOUR_PAGES_KEY;

            if (get_option($option_key)) {
                update_option($option_key, wp_json_encode($response));
            } else {
                add_option($option_key, wp_json_encode($response));
            }

            return $this->generateThePages($response, $request['page_name']);
        } catch (\Exception $e) {
            // Log the error for debugging
            OpenAiService::log('Content Generation Error: ' . $e->getMessage());
            
            // Return a JSON error response with the specific error message
            wp_send_json_error($e->getMessage());
            return false;
        }
    }

    /**
     * Parse the response from OpenAI and generate the wordpress pages.
     *
     * @param  string  $response
     * @param  array  $page_name
     * @return string
     *
     * @since 1.0.0
     */
    protected function generateThePages(string $response, array $page_name): string
    {
        $generated_content_key = Constants::SPAWNSTER_GENERATED_CONTENT_KEY;
        $divisor = ceil(100 / count($page_name));
        $init = 1;

        if (
            preg_match_all('/<body>(.*?)<\/body>/is', $response, $matches, PREG_SET_ORDER) ||
            preg_match_all('/<section>(.*?)<\/section>/is', $response, $matches, PREG_SET_ORDER) ||
            preg_match_all('/```html(.*?)```/is', $response, $matches, PREG_SET_ORDER)
            ) {

            foreach ($matches as $i => $match) {
                $this->parsePage($i, $match[1]);
//                if (get_option( $generated_content_key . $i)) {
//                    update_option($generated_content_key . $i, serialize(['title' => sanitize_text_field($page_name[$i]), 'content' => wp_kses_post($match[1])]));
//                } else {
//                    add_option($generated_content_key . $i, serialize(['title' => sanitize_text_field($page_name[$i]), 'content' => wp_kses_post($match[1])]));
//                }
//
                $progress = $init * $divisor;

                if (get_option('spawnster-generated-progress')) {
                    update_option('spawnster-generated-progress', $progress);
                } else {
                    add_option('spawnster-generated-progress', $progress);
                }

                $init++;
            }

            return wp_send_json_success();
        }
        return wp_send_json_error();
    }

    protected function parsePage(int $key, string $content): void
    {
        $header = Constants::SPAWNSTER_GENERATED_HEADING_KEY;
        $content_heading = Constants::SPAWNSTER_GENERATED_CONTENT_KEY;

        if (
            preg_match('/<h1>(.*?)<\/h1>/is', $content, $heading) ||
            preg_match('/<h2>(.*?)<\/h2>/is', $content, $heading) ||
            preg_match('/<h3>(.*?)<\/h3>/is', $content, $heading)
        ) {
            if (get_option($header . $key)) {
                update_option($header . $key, $heading[0]);
            } else {
                add_option($header . $key, $heading[0]);
            }
        }

        if (preg_match_all('/<p>(.*?)<\/p>/is', $content, $matches, PREG_SET_ORDER)) {
            $paragraphs = [];
            foreach ($matches as $match) {
                $paragraphs[] = $match[0];
            }
            if (get_option($content_heading . $key)) {
                update_option($content_heading . $key, serialize($paragraphs));
            } else {
                add_option($content_heading . $key, serialize($paragraphs));
            }
        }

    }

    /**
     * Parse the response.
     *
     * @param  string  $response
     * @return array
     */
    public function parseResponse(string $response): array
    {
        $data = [];
        if (
            preg_match_all('/<body>(.*?)<\/body>/is', $response, $matches, PREG_SET_ORDER) ||
            preg_match_all('/<section>(.*?)<\/section>/is', $response, $matches, PREG_SET_ORDER) ||
            preg_match_all('/```html(.*?)```/is', $response, $matches, PREG_SET_ORDER)
        ) {

            foreach ($matches as $i => $match) {
                $data[$i] = $match[1];
            }
        }

        return $data;
    }

    /**
     * Format the content for OpenAI request.
     *
     * @param  array  $page_name
     * @param  array  $page_description
     * @return void
     *
     * @since 1.0.0
     */
    protected function formatContent(array $page_name, array $page_description): string
    {
        $messages = [];
        $website = get_option(Constants::SPAWNSTER_SETUP_YOUR_WEBSITE_KEY);

        if ($website) {
            $website = json_decode($website, true);
        }

        if (!empty($page_name)) {
            $openai_service = new OpenAiService();
            $language_instruction = $openai_service->get_language_instruction();
            
            foreach ($page_name as $key => $page)
            {
                $message = 'Create a 3 paragraph Wordpress content in HTML format for ' . $page . ' page about a website ' . $website['website_name'] . ' which ' . $website['website_description'];
                if (!empty($page_description[$key])) $message .= ' but highlight specific details for ' . $page_description[$key];
                $message .= $language_instruction;
                // $message .= ' and include free to use images.';
                $messages[] = $message;
            }

            return implode("\n", $messages);
        }
    }
}
