<?php
namespace EasyChat\Library\Notification;

use EasyChat\Library\CentralGatewayClient;
use EasyChat\Library\RequestContext;
use EasyChat\Model\Setting;

class TrialLockGuard {
    private $registry;
    private $settings;

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

    public function resolveCentralDomainStatus(bool $force_refresh = false): array {
        $central_api = CentralGatewayClient::normalizeBaseUrl($this->settings->get('chat_central_api'));
        if ($central_api === '') {
            return $this->normalizeCentralDomainStatus([]);
        }

        $domain = $this->currentDomain();
        $cache_key = 'chat_central_domain_status_cache';
        $cached = json_decode((string)$this->settings->get($cache_key, ''), true);
        if (!$force_refresh
            && is_array($cached)
            && ($cached['domain'] ?? '') === $domain
            && (int)($cached['checked_at'] ?? 0) > time() - 30) {
            return $this->normalizeCentralDomainStatus($cached);
        }

        $result = CentralGatewayClient::postJson(
            $central_api,
            '/api/v1/auth/domain-status',
            CentralGatewayClient::buildSignedInstallBody($this->settings, $domain),
            4,
            $this->registry
        );

        $response = is_array($result['json'] ?? null)
            ? $result['json']
            : json_decode((string)$result['response'], true);
        if (is_array($response) && in_array((int)$result['status'], [200, 403], true)) {
            $state = $this->normalizeCentralDomainStatus(array_merge($response, [
                'domain' => $domain,
                'checked_at' => time(),
            ]));
            $this->settings->set($cache_key, json_encode($state));
            return $state;
        }

         
         
         
        if (is_array($cached)) {
            $cached_status = $this->normalizeCentralDomainStatus($cached);
            if (in_array($cached_status['state'], ['admin_blocked', 'trial_expired'], true)) {
                return $cached_status;
            }
        }

        return $this->normalizeCentralDomainStatus([]);
    }

    public function isTrialExpired(bool $force_refresh = false): bool {
        return $this->resolveCentralDomainStatus($force_refresh)['state'] === 'trial_expired';
    }

    public function isSmsBlocked(bool $force_refresh = false): bool {
        return $this->isTrialExpired($force_refresh);
    }

    public function trialExpiredPayload(array $status = []): array {
        $status = $status ?: $this->resolveCentralDomainStatus(false);
        return [
            'success' => 0,
            'code' => 'trial_limit_exceeded',
            'message_key' => 'auth.trial_limit_exceeded',
            'trial_expired' => 1,
            'trial_push_used' => (int)($status['trial_push_used'] ?? 300),
            'trial_push_limit' => (int)($status['trial_push_limit'] ?? 300),
            'purchase_url' => (string)($status['purchase_url'] ?? 'https://easychat24.ru/pricing/'),
        ];
    }

    private function normalizeCentralDomainStatus(array $data): array {
        $code = isset($data['code']) && is_scalar($data['code']) ? (string)$data['code'] : '';
        $reason = isset($data['reason']) && is_scalar($data['reason']) ? (string)$data['reason'] : '';
        $trial_expired = !empty($data['trial_expired'])
            || $code === 'trial_limit_exceeded'
            || $reason === 'trial_limit_exceeded';
        $blocked = !empty($data['blocked']);

        $state = 'active';
        if ($trial_expired) {
            $state = 'trial_expired';
        } elseif ($blocked || $code === 'domain_blocked' || $reason === 'blocked_by_admin') {
            $state = 'admin_blocked';
        }

        return [
            'state' => $state,
            'domain' => isset($data['domain']) && is_scalar($data['domain']) ? (string)$data['domain'] : $this->currentDomain(),
            'blocked' => $state === 'admin_blocked',
            'trial_expired' => $state === 'trial_expired',
            'reason' => $state === 'trial_expired' ? 'trial_limit_exceeded' : ($reason !== '' ? $reason : ($state === 'admin_blocked' ? 'blocked_by_admin' : '')),
            'code' => $state === 'trial_expired' ? 'trial_limit_exceeded' : ($code !== '' ? $code : ($state === 'admin_blocked' ? 'domain_blocked' : '')),
            'mode' => isset($data['mode']) && is_scalar($data['mode']) ? (string)$data['mode'] : '',
            'trial_push_used' => isset($data['trial_push_used']) ? (int)$data['trial_push_used'] : 0,
            'trial_push_limit' => isset($data['trial_push_limit']) ? (int)$data['trial_push_limit'] : 300,
            'purchase_url' => isset($data['purchase_url']) && is_scalar($data['purchase_url']) ? (string)$data['purchase_url'] : 'https://easychat24.ru/pricing/',
            'checked_at' => isset($data['checked_at']) ? (int)$data['checked_at'] : time(),
        ];
    }

    private function currentDomain(): string {
        $domain = RequestContext::server()['HTTP_HOST'] ?? '';
        if (is_scalar($domain) && trim((string)$domain) !== '') {
            return trim((string)$domain);
        }

         
         
        foreach (['chat_last_known_domain', 'chat_public_domain', 'config_url'] as $setting_key) {
            $value = trim((string)$this->settings->get($setting_key, ''));
            if ($value === '') {
                continue;
            }

            $host = parse_url($value, PHP_URL_HOST);
            if (is_string($host) && $host !== '') {
                return $host;
            }

            return $value;
        }

        return 'localhost';
    }
}
