<?php

namespace Blazemedia\Affiliation\AdminUserInterface\Settings;

use Blazemedia\Affiliation\Support\Environment;
use Env\Env;

class FormatsStyles
{
    const TRANSIENT_KEY = 'affiliation_format_styles_css';
    const EXPIRATION = MONTH_IN_SECONDS; // Default expiration time for the transient (1 month)

    /**
     * Set the CSS in a transient.
     *
     * @param string $css
     * @param int|null $expiration
     * @return bool
     */
    public static function setCss(): bool
    {
        self::deleteCss();

        // TODO - Replace with AffiliationAPI Library
        $rendering_manager_url = Environment::get('BLZ_API_RENDERING_MANAGER', 'https://rendering-manager.blazemedia.it/api/') . 'v2/';
        $apiSecret = Environment::get('BLZ_AFF_API_SECRET', '');

        $domain = get_option('domain_2');
        
        $domain = empty($domain) ? preg_replace('/^.*?\.(.*?\..*?)$/', '$1', home_url() ) : $domain;

        $response = wp_remote_get($rendering_manager_url.'styles/formats', [
            'timeout' => 30,
            'sslverify' => false,
            'headers' => [
                'X-API-KEY' => hash('sha256', $apiSecret),
                'User-Agent' => 'WordPress/Affiliation Plugin',
                'Source' => $domain ?? home_url(),
                'Accept' => 'application/json',
            ],
        ]);

        // Check if the API call was successful
        if (is_wp_error($response)) {
            error_log('FormatsStyles API call failed: ' . $response->get_error_message());
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            error_log('FormatsStyles API call returned error code: ' . $response_code);
            return false;
        }

        $expiration = $expiration ?? self::EXPIRATION;

        $response = json_decode(wp_remote_retrieve_body($response));
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('FormatsStyles JSON decode error: ' . json_last_error_msg());
            return false;
        }

        if (!isset($response->css) || empty($response->css)) {
            error_log('FormatsStyles CSS not found in API response');
            return false;
        }
        return set_transient(self::TRANSIENT_KEY, $response->css, $expiration);
    }

    /**
     * Get the CSS from the transient.
     *
     * @return string
     */
    public static function getCss(): string
    {
        $transient = get_transient(self::TRANSIENT_KEY);
        if ($transient === false) {
            // If the transient is not set, try to set it again
           self::setCss();
        }

        $transient = get_transient(self::TRANSIENT_KEY);
        if ($transient === false) {
            error_log('FormatsStyles transient not found or expired');
            return '';
        }
        return json_encode($transient);
    }

    /**
     * Delete the CSS transient.
     *
     * @return bool
     */
    public static function deleteCss(): bool
    {
        return delete_transient(self::TRANSIENT_KEY);
    }
}