<?php

namespace SEOAIC\rest_api;

use Exception;
use SEOAIC\rest_api\http_resources\Result;
use SEOAIC\SeoaicTemplates;
use WP_REST_Request;
use WP_REST_Response;

class CustomTemplateAPI
{
    private $seoaic;

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

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/custom_template/content', [
                'methods' => 'GET',
                'callback' => [$this, 'getCustomTemplateContent'],
                'permission_callback' => function() {
                    return current_user_can('edit_posts');
                },
            ]);

            register_rest_route('seoaic/v1', '/custom_template/css', [
                'methods' => 'GET',
                'callback' => [$this, 'getCustomTemplateCSS'],
                'permission_callback' => function() {
                    return current_user_can('edit_posts');
                },
            ]);

        });
    }

    public function getCustomTemplateContent(WP_REST_Request $request)
    {
        global $SEOAIC_OPTIONS;

        $params = $request->get_params();
        $content = '';

        try {
            // $SEOAIC_OPTIONS = get_option('seoaic_options');
            // $templateOptions = isset($SEOAIC_OPTIONS['template']) ? $SEOAIC_OPTIONS['template'] : null;
            if (
                isset($params['default'])
                && "true" == $params['default']
            ) {
                $seoaicTemplates = new SeoaicTemplates();
                $content = $seoaicTemplates->getDefaultContent();
            }

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

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

    public function getCustomTemplateCSS(WP_REST_Request $request)
    {
        $params = $request->get_params();
        $css = '';

        try {
            if (
                isset($params['default'])
                && "true" == $params['default']
            ) {
                $seoaicTemplates = new SeoaicTemplates();
                $css = $seoaicTemplates->getDefaultCSS();
            }

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

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