<?php
/**
 * _             _       _
 * | |____      _| | __ _| |__
 * | '_ \ \ /\ / / |/ _` | '_ \
 * | |_) \ V  V /| | (_| | |_) |
 * |_.__/ \_/\_/ |_|\__,_|_.__/.
 *
 * @author    Bwlab di Luigi Massa <info@bwlab.it>
 * @copyright since 2014 Bwlab
 * @license   proprietary
 */

declare(strict_types=1);

namespace Bwlab\Withdrawal\Service;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Checks whether the installed PrestaShop version is the latest available.
 *
 * The native core feed (api.prestashop.com/xml/upgrader.xml) is dead (still serves 1.6.x),
 * so the latest version is fetched from the GitHub releases API and cached 24h in ps_configuration.
 */
class PrestashopVersionChecker
{
    private const GITHUB_LATEST_URL = 'https://api.github.com/repos/PrestaShop/PrestaShop/releases/latest';
    private const CACHE_VERSION_KEY = 'BWWITHDRAWAL_LATEST_PS_VERSION';
    private const CACHE_TIME_KEY = 'BWWITHDRAWAL_LATEST_PS_CHECK';
    private const CACHE_TTL = 86400; // 24h

    public function getLatestVersion(bool $force = false): ?string
    {
        $cached = (string) \Configuration::get(self::CACHE_VERSION_KEY);
        $lastCheck = (int) \Configuration::get(self::CACHE_TIME_KEY);

        if (!$force && $cached !== '' && $lastCheck > time() - self::CACHE_TTL) {
            return $cached;
        }

        $fetched = $this->fetchLatestFromGithub();
        if ($fetched !== null) {
            \Configuration::updateValue(self::CACHE_VERSION_KEY, $fetched);
            \Configuration::updateValue(self::CACHE_TIME_KEY, time());

            return $fetched;
        }

        // fetch failed: keep the last known value (may be empty) instead of breaking the dashboard
        return $cached !== '' ? $cached : null;
    }

    public function getInstalledVersion(): string
    {
        return _PS_VERSION_;
    }

    public function isUpToDate(): bool
    {
        $latest = $this->getLatestVersion();
        if ($latest === null) {
            return true; // unknown → assume ok, never alarm on missing data
        }

        return version_compare($this->getInstalledVersion(), $latest, '>=');
    }

    private function fetchLatestFromGithub(): ?string
    {
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => "User-Agent: bwwithdrawal-module\r\nAccept: application/vnd.github+json\r\n",
                'timeout' => 5,
            ],
        ]);

        $raw = \Tools::file_get_contents(self::GITHUB_LATEST_URL, false, $context, 5);
        if (!$raw) {
            return null;
        }

        $data = json_decode($raw, true);
        $tag = $data['tag_name'] ?? null;
        if (!is_string($tag) || $tag === '') {
            return null;
        }

        return ltrim($tag, 'vV');
    }
}
