<?php

declare(strict_types=1);

namespace MyCustomizer\WooCommerce\Connector\Libs;

use Exception;
use MyCustomizer\WooCommerce\Connector\Config\MczrConfig;
use MyCustomizer\WooCommerce\Connector\Libs\MczrSettings;
use WP_Error;

class MczrConnect
{
    public const TOKEN_FIELD_NAME = 'apiToken';

    /** @var MczrSettings */
    private $settings;

    public function __construct()
    {
        $this->settings = new MczrSettings();
    }

    /**
     * @throws Exception
     */
    private function getToken(): string
    {
        $token = $this->settings->get(self::TOKEN_FIELD_NAME);
        if (!$token) {
            throw new Exception('Could not get token in db nor in class');
        }

        return $token;
    }

    /**
     * @param string $path
     * @param array $content
     * @param array $headers
     * @param bool $bearer
     * @param bool $retry
     *
     * @return array|WP_Error|void
     */
    public function post($path, $content = [], $headers = [], $bearer = true, $retry = true)
    {
        if ($bearer) {
            $headers['Authorization'] = 'Bearer ' . $this->getToken();
        }
        $headers['Content-Type'] = 'application/json';
        $args = [
            'body' => json_encode($content),
            'timeout' => '5',
            'redirection' => '5',
            'httpversion' => '1.0',
            'blocking' => true,
            'headers' => $headers,
            'cookies' => [],
        ];
        $response = wp_remote_post(MczrConfig::getConfig()['apiBaseUrl'] . $path, $args);
        if (\is_wp_error($response)) {
            if (true === $retry) {
                $this->post($path, $content, $headers, $bearer, false);
            }
            $error_message = $response->get_error_message();

            try {
                $logger = \wc_get_logger();
                $logger->warning("Kickflip Plugin couldn't POST to {$path}. {$error_message}. Please contact us at info@mycustomizer.com", ['source' => 'Kickflip Product Configurators']);
            } catch (Exception $e) {
            }
        } else {
            return $response;
        }
    }

    /**
     * @param string $path
     * @param bool $retry
     * @param bool $bearer
     *
     * @return \stdClass|void
     */
    public function get($path, $retry = true, $bearer = true)
    {
        $headers = [];
        if ($bearer) {
            $headers['Authorization'] = 'Bearer ' . $this->getToken();
        }
        $args = [
            'headers' => $headers
        ];
        $wpget = \wp_remote_get(MczrConfig::getConfig()['apiBaseUrl'] . $path, $args);

        if (\is_wp_error($wpget)) {
            if (true === $retry) {
                $this->get($path, false, $bearer);
            } else {
                try {
                    $error_message = $wpget->get_error_message();
                    $logger = \wc_get_logger();
                    $logger->warning("Kickflip Plugin couldn't GET to {$path}. {$error_message}. Please contact us at info@mycustomizer.com", ['source' => 'Kickflip Product Configurators']);
                } catch (Exception $e) {
                }
            }
        } else {
            $body = \wp_remote_retrieve_body($wpget);
            $json = json_decode($body);

            return $json;
        }
    }

    public function uninstall(string $brand, string $onlineStoreId): bool
    {
        try {
            $data = [
                'status' => 'uninstalled',
            ];

            $this->post("/brands/$brand/onlinestores/$onlineStoreId", $data);

            return true;
        } catch (Exception $ex) {
            error_log($ex->getMessage());

            return false;
        }
    }

    private function serialize_url(string $url): string
    {
        return preg_replace('#^(https?://)?www\.#', '$1', $url);
    }

    public function connect(string $brand, string $onlineStoreId = null): bool
    {
        try {
            if (empty($onlineStoreId)) {
                $shopUrl = $this->serialize_url(get_site_url());
                $onlineStores = $this->get("/brands/$brand/onlinestores");

                if (is_array($onlineStores)) {
                    foreach ($onlineStores as $onlineStore) {
                        $onlineStoreUrl = $this->serialize_url($onlineStore->url);
                        if ($onlineStoreUrl === $shopUrl) {
                            $onlineStoreId = (string) $onlineStore->id;

                            break;
                        }
                    }
                }
            }

            $data = [
                'name' => \get_bloginfo('name'),
                'currency' => \get_woocommerce_currency(),
                'url' => \get_site_url(),
                'status' => 'installed',
                'eCommerce' => 'woocommerce',
                'accessToken' => $this->settings->get('authorizationKey'),
            ];

            if (empty($onlineStoreId)) {
                $response = $this->post("/brands/$brand/onlinestores", $data);
            } else {
                $response = $this->post("/brands/$brand/onlinestores/$onlineStoreId", $data);
            }
            $onlineStore = json_decode($response['body']);

            $this->settings->updateOne('shopId', $onlineStore->id);

            return true;
        } catch (Exception $ex) {
            error_log($ex->getMessage());

            return false;
        }
    }
}
