<?php

namespace Core\System\License;

class LicenseStorage
{
    protected static string $key = 'license_cache';

    public static function getCache(): ?array
    {
        return self::get();
    }

    public static function storeCache(array $payload): bool
    {
        return self::save($payload);
    }

    public static function get(): ?array
    {
        if (!function_exists('db')) {
            return null;
        }

        try {
            $stmt = db()->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([self::$key]);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);

            if (!$row || !isset($row['setting_value'])) {
                return null;
            }

            $raw = trim((string)$row['setting_value']);
            if ($raw === '') {
                return null;
            }

            $data = json_decode($raw, true);

            if (!is_array($data)) {
                $data = json_decode(stripslashes($raw), true);
            }

            if (!is_array($data)) {
                return null;
            }

            return $data;

        } catch (\Throwable $e) {
            return null;
        }
    }

    public static function save(array $payload): bool
    {
        if (!function_exists('db')) {
            return false;
        }

        try {
            $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            $stmt = db()->prepare("SELECT id FROM settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([self::$key]);
            $exists = $stmt->fetchColumn();

            if ($exists) {
                $upd = db()->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ? LIMIT 1");
                $upd->execute([$json, self::$key]);
            } else {
                $ins = db()->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");
                $ins->execute([self::$key, $json]);
            }

            return true;
        } catch (\Throwable $e) {
            return false;
        }
    }


    public static function saveVerifiedState(string $licenseKey, array $response, array $overrides = []): bool
    {
        $payload = array_merge([
            'license_key'     => $licenseKey,
            'status'          => 'active',
            'action'          => (string)($response['action'] ?? 'allow'),
            'type'            => $response['type'] ?? null,
            'type_original'   => $response['type_original'] ?? null,
            'expires'         => $response['expires'] ?? null,
            'domain_bound'    => $response['domain_bound'] ?? null,
            'max_domains'     => (int)($response['max_domains'] ?? 0),
            'domains_used'    => (int)($response['domains_used'] ?? 0),
            'message'         => (string)($response['message'] ?? ''),
            'checked_at'      => time(),
            'last_ok_at'      => time(),
            'ping_at'         => time(),
            'ping_last_ok_at' => time(),
            'ttl'             => 3600,
            'failures'        => 0,
        ], $overrides);

        return self::save($payload);
    }

    public static function clear(): void
    {
        if (!function_exists('db')) {
            return;
        }

        try {
            $del = db()->prepare("DELETE FROM settings WHERE setting_key = ? LIMIT 1");
            $del->execute([self::$key]);
        } catch (\Throwable $e) {
        }
    }
}
