<?php
namespace EasyChat\Library;

class InstallationConsent {
    const VERSION = '2026-06-29';

    public static function fromInstallParams(array $params, $source = 'generic_installer') {
        $services = self::truthy(self::value($params, 'easychat_services_consent', '0'));
        $news = self::truthy(self::value($params, 'easychat_news_consent', '0'));
        $news_email = strtolower(trim(self::value($params, 'easychat_news_email', '')));
        if ($news_email === '') {
            $news_email = strtolower(trim(self::value($params, 'admin_email', '')));
        }

        if ($news && !filter_var($news_email, FILTER_VALIDATE_EMAIL)) {
            return array(
                'success' => false,
                'error' => 'Укажите корректный email для новостей EasyChat24 или снимите галочку получения новостей.',
            );
        }

        $now = date('c');
        return array(
            'success' => true,
            'settings' => array(
                'chat_easychat_services_consent' => $services ? '1' : '0',
                'chat_easychat_services_consent_version' => $services ? self::VERSION : '',
                'chat_easychat_services_consent_at' => $services ? $now : '',
                'chat_easychat_services_consent_source' => $services ? self::safeSource($source) : '',
                'chat_easychat_news_consent' => $news ? '1' : '0',
                'chat_easychat_news_consent_version' => $news ? self::VERSION : '',
                'chat_easychat_news_consent_at' => $news ? $now : '',
                'chat_easychat_news_consent_source' => $news ? self::safeSource($source) : '',
                'chat_easychat_news_email' => $news ? $news_email : '',
            ),
        );
    }

    private static function value(array $params, $key, $default = '') {
        return isset($params[$key]) ? (string)$params[$key] : (string)$default;
    }

    private static function truthy($value) {
        return in_array(strtolower(trim((string)$value)), array('1', 'true', 'yes', 'on'), true);
    }

    private static function safeSource($source) {
        $source = preg_replace('/[^a-z0-9_-]/i', '', (string)$source);
        return $source !== '' ? substr($source, 0, 64) : 'generic_installer';
    }
}
