<?php

namespace RistrettoApps\Spawnster;

use RistrettoApps\Spawnster\Base\Constants;
use RistrettoApps\Spawnster\Base\DefaultPages;
use RistrettoApps\Spawnster\Helpers\TemplateView;
use RistrettoApps\Spawnster\Interfaces\ConstantsTrait;
use RistrettoApps\Spawnster\Services\GenerateContent;

/**
 * The base controller of the MVC implementation.
 *
 * Serves as the entry point of admin settings.
 *
 * @package    Spawnster
 * @subpackage Spawnster/public
 * @author     Ristretto Apps
 */
class BaseController
{
    use ConstantsTrait;

    const OPTION_KEY_OPENAPI = Constants::SPAWNSTER_OPTION_OPENAPI_KEY;
    const OPTION_KEY_LANGUAGE = Constants::SPAWNSTER_OPTION_DEFAULT_LANGUAGE;
    const OPTION_KEY_LOGGING = Constants::SPAWNSTER_OPTION_LOGGING_ENABLED;

    private TemplateView $view;
    private string $nonce;

    public function __construct(TemplateView $view) {
        $this->view = $view;
        $this->nonce = wp_create_nonce('spawnster-nonce');
    }

    /**
     * The generate page form.
     *
     * Provides the user interface to set page name and description.
     *
     * @return string
     */
    public function setupYourPages(array $post)
    {
       //$this->shouldRedirect();

        if ($post) {
            $generateContent = new GenerateContent();
            return $generateContent->handle($post);
        }

        $data = [
            'pages' => DefaultPages::DEFAULT_PAGES
        ];

        return $this->view::render('views/admin/setup-your-pages', $data);
    }

    /**
     * Setup website form.
     *
     * Provides the user interface to set website name and description.
     *
     * @return string|void
     * @since 1.0.0
     */
    public function setupYourWebsite()
    {
        $data = [
            'data' => [
                'website_name' => null,
                'website_description' => null
            ]
        ];

        $key = Constants::SPAWNSTER_SETUP_YOUR_WEBSITE_KEY;
        $option = get_option($key);

        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) ) : null;

        if (! wp_verify_nonce( $nonce, 'spawnster-nonce' )) {
            wp_die('Security check failed');
        } else {
            if ($option) {
                $data = json_decode($option, true);
            }
            return $this->view::render('views/admin/setup-your-website', $data);
        }
    }

    /**
     * Setup API key.
     *
     * Provides the user interface for saving OpenAI API key.
     *
     * @return string
     * @since 1.0.0
     */
    public function settings(): string
    {
        $apiKey = get_option(self::OPTION_KEY_OPENAPI);
        $defaultLanguage = get_option(self::OPTION_KEY_LANGUAGE, 'English');
        $loggingEnabled = get_option(self::OPTION_KEY_LOGGING, true); // Default to enabled

        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field( wp_unslash($_REQUEST['_wpnonce']) ) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            // Handle API key update
            if (isset($_POST['open-ai-api-key'])) {
                $openApiKey = sanitize_text_field( wp_unslash( $_POST['open-ai-api-key'] ) );
                if (!$apiKey) {
                    add_option(self::OPTION_KEY_OPENAPI, $openApiKey);
                } else {
                    update_option(self::OPTION_KEY_OPENAPI, $openApiKey);
                }
            }

            // Handle language setting update
            if (isset($_POST['default-language'])) {
                $selectedLanguage = sanitize_text_field( wp_unslash( $_POST['default-language'] ) );
                if (!$defaultLanguage || $defaultLanguage === 'English') {
                    add_option(self::OPTION_KEY_LANGUAGE, $selectedLanguage);
                } else {
                    update_option(self::OPTION_KEY_LANGUAGE, $selectedLanguage);
                }
                $defaultLanguage = $selectedLanguage;
            }

            // Handle logging toggle update
            if (isset($_POST['logging-enabled'])) {
                $loggingValue = sanitize_text_field( wp_unslash( $_POST['logging-enabled'] ) ) === 'on';
                update_option(self::OPTION_KEY_LOGGING, $loggingValue);
                $loggingEnabled = $loggingValue;
            } elseif (isset($_POST['submit'])) {
                // If form was submitted but logging-enabled wasn't set, it means checkbox was unchecked
                update_option(self::OPTION_KEY_LOGGING, false);
                $loggingEnabled = false;
            }

            $data = [
                'api_key' => get_option(self::OPTION_KEY_OPENAPI),
                'default_language' => $defaultLanguage,
                'logging_enabled' => $loggingEnabled
            ];

            return $this->view::render('views/admin/settings', $data);
        }
    }

    /**
     * Display the welcome page.
     *
     * Provides the main dashboard/welcome interface.
     *
     * @return string
     * @since 1.0.0
     */
    public function welcome(): string
    {
        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : null;

        if ( ! wp_verify_nonce( $nonce, 'spawnster-nonce' ) ) {
            wp_die('Security check failed');
        } else {
            $data = [
                'api_key_set' => !empty(get_option(self::OPTION_KEY_OPENAPI))
            ];

            return $this->view::render('views/admin/welcome', $data);
        }
    }

    /**
     * Generated content edit page.
     *
     * Here you can modify or update the page content before publishing.
     *
     * @return string
     */
    public function checkGeneratedContent(): string
    {
        $requests = unserialize(get_option(Constants::SPAWNSTER_PAGE_NAME_REQUEST));
        $response = get_option(Constants::SPAWNSTER_SETUP_YOUR_PAGES_KEY);

        $parsedResponse = (new GenerateContent())->parseResponse($response);

        $data = [
            'pages' => $requests,
            'contents' => $parsedResponse
        ];

        return $this->view::render('views/admin/check-generated-content', $data);
    }

    /**
     * Redirect if OpenAPI key has not been set.
     *
     * @return void
     */
    public static function shouldRedirect(): void
    {
        if (isset($_GET['page']) && $_GET['page'] === 'spawnster') {
            $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : null;

            if (!wp_verify_nonce($nonce, 'spawnster-nonce')) {
                $admin_url = admin_url('admin.php?page=spawnster&view=settings&_wpnonce=' . wp_create_nonce('spawnster-nonce'));
                wp_redirect($admin_url);
                exit;
            }
        }
    }

    public static function handle_setup_your_website_submission(): void
    {
        $key = Constants::SPAWNSTER_SETUP_YOUR_WEBSITE_KEY;
        $post = $_POST ?? null;

        $nonce = isset($_REQUEST['_wpnonce'])
            ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce']))
            : null;

        if (!wp_verify_nonce($nonce, 'spawnster-nonce')) {
            wp_die('Security check failed');
        }

        if ($post) {
            $option = get_option($key);
            $postData = wp_json_encode([
                'website_name' => $post['website_name'] ?? null,
                'website_description' => $post['website_description'] ?? null,
            ]);

            if ($option) {
                update_option($key, wp_kses_post($postData));
            } else {
                add_option($key, wp_kses_post($postData));
            }

            $_nonce = wp_create_nonce('spawnster-nonce');
            $admin_url = admin_url(Constants::SPAWNSTER_ADMIN_SETUP_PAGES . '&_wpnonce=' . $_nonce);
            wp_redirect($admin_url);
            exit;
        }
    }
}