<?php
namespace ShopyPress\Helpers;
if ( ! defined( 'ABSPATH' ) ) exit;

use ShopyPress\Utils\OptionUtils;

class ShopifyAuth {

    const ACCESS_TOKEN_OPTION_KEY = 'synckube_shopify_access_token';
    const ACCESS_TOKEN_EXPIRES_OPTION_KEY = 'shopify_access_token_expires';

    /**
     * Get a valid access token (fetch new one if expired)
     *
     * @param string $shop The shop domain (e.g., 'mystore.myshopify.com')
     * @return string|null The access token or null on failure
     */
    public static function getAccessToken(string $shop): ?string {
        $options = OptionUtils::getInstance();
        $client_id = $options->getOption('client_id');
        $client_secret = $options->getOption('client_secret');

        if (empty($client_id) || empty($client_secret)) {
            return null;
        }

        // Check if we have a valid cached token
        $cached_token = get_transient(self::ACCESS_TOKEN_OPTION_KEY);
        if ($cached_token) {
            return $cached_token;
        }

        // Fetch a new token
        return self::fetchNewAccessToken($shop, $client_id, $client_secret);
    }

    /**
     * Fetch a new access token from Shopify
     *
     * @param string $shop The shop domain
     * @param string $client_id The client ID
     * @param string $client_secret The client secret
     * @return string|null The access token or null on failure
     */
    private static function fetchNewAccessToken(string $shop, string $client_id, string $client_secret): ?string {
        $url = "https://{$shop}/admin/oauth/access_token";

        $body = [
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
        ];

        $response = wp_remote_post($url, [
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'body' => $body,
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return null;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);

        if ($response_code !== 200) {
            return null;
        }

        $data = json_decode($response_body, true);

        if (empty($data['access_token'])) {
            return null;
        }

        $access_token = $data['access_token'];

        // Cache the token for 15 hours
        $cache_duration = 15 * HOUR_IN_SECONDS; // 15 hours
        set_transient(self::ACCESS_TOKEN_OPTION_KEY, $access_token, $cache_duration);

        return $access_token;
    }

    /**
     * Clear the cached access token
     */
    public static function clearAccessToken(): void {
        delete_transient(self::ACCESS_TOKEN_OPTION_KEY);
    }
}
