<?php

namespace SEOAIC\rest_api;

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

class Options
{
    private $seoaic;

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

        add_action('rest_api_init', function () {
            register_rest_route('seoaic/v1', '/options/seoaic_options/(?P<seoaic_option>[a-zA-Z0-9_-]+)', [
                'methods' => 'GET',
                'callback' => [$this, 'getSEOAICOption'],
                'permission_callback' => function() {
                    return current_user_can('edit_posts');
                },
            ]);
        });

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

    public function getSEOAICOption(WP_REST_Request $request)
    {
        try {
            $seoaicOption = $request->get_param('seoaic_option');

            if (empty($seoaicOption)) {
                throw new Exception("Empty Option name");
            }

            $SEOAIC_OPTIONS = get_option('seoaic_options');
            $optionValue = isset($SEOAIC_OPTIONS[$seoaicOption]) ? $SEOAIC_OPTIONS[$seoaicOption] : null;


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

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

    public function getGenerateImageOptions()
    {
        global $SEOAIC_OPTIONS;

        try {
            $options = ['seoaic_images_credit', 'seoaic_images_credit_limit'];
            $data = [];
            $sync = false;
            foreach ($options as $option) {
                $item = get_option($option);
                if (!$item) {
                    $sync = true;
                    break;
                }
                $data[$option] = $item;
            }

            if ($sync) {
                $params = [
                    'email' => $SEOAIC_OPTIONS['seoaic_api_email'],
                    'domain' => $_SERVER['HTTP_HOST'],
                ];
                $result = $this->seoaic->curl->init('api/companies/credits', $params, true, true, true);
                $data['seoaic_images_credit'] = isset($result['images_limit']) && isset($result['images_used'])
                    ? intval($result['images_limit']) - intval($result['images_used'])
                    : 0;
                $data['seoaic_images_credit_limit'] = $result['images_limit'];
                $this->seoaic->set_api_credits($result);
            }

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

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