<?php

namespace apexl\Io\modules\user\services;

use apexl\Config\Singleton;
use GuzzleHttp\Client;


class apexlWPManageService
{
    protected $config;

    public function __construct()
    {
        $this->config = Singleton::getInstance();
    }

    public static function getWPUserData($email)
    {
        return self::makePostRequest('user/getdata', (object)[
            'email' =>  $email
        ]);

    }

    public static function checkWPCredentials($username, $password)
    {
        $data = self::makePostRequest('user/validate', [
            'user' =>  $username,
            'password' => $password
        ]);

        return (isset($data->data->user_login) && $data->data->user_login == $username);
    }

    protected static function getBasicAuthDetails()
    {
        $config = Singleton::getInstance();
        return [
            $config->app->wordpress->apexl_wordpress_manage->username,
            $config->app->wordpress->apexl_wordpress_manage->secret,
        ];
    }

    protected static function getWordpressApiUrl($path)
    {
        $config = Singleton::getInstance();
        if (isset($config->app->wordpress->apexl_wordpress_manage->api_url)) {
            return $config->app->wordpress->apexl_wordpress_manage->api_url . $path;
        }

        return null;
    }

    protected static function makeGetRequest($path)
    {
        try {
            $url = self::getWordpressApiUrl($path);
            $client = new Client(['verify' => false, 'timeout' => 4]);
            $response = $client->get($url, [
                'auth' => self::getBasicAuthDetails(),
                'headers' => [
                    'Content-Type' => 'application/json'
                ]
            ]);
            $contents = $response->getBody()->getContents();

            return json_decode($contents);

        } catch (\Exception $e){
            error_log('[Apexl WP plugin makeGetRequest('.$url.')] FAILED - with - '.$e->getMessage());
        }

        return;
    }

    protected static function makePostRequest($path, $data)
    {
        try {
            $url = self::getWordpressApiUrl($path);
            $client = new Client(['verify' => false]);
            $response = $client->request('POST', $url, [
                'body' => json_encode($data),
                'auth' => self::getBasicAuthDetails(),
                'headers' => [
                    'Content-Type' => 'application/json'
                ]
            ]);
            $contents = $response->getBody()->getContents();

            return json_decode($contents);

        } catch (\Exception $e){
            echo $e->getMessage();
            error_log('[Apexl WP plugin makePostRequest('.$url.')] FAILED - with - '.$e->getMessage());
        }

        return null;

    }

}
