<?php

namespace Core\App\Controllers\Admin;

use Core\System\PluginManager;
use Core\System\License\Fingerprint;

class PluginLicenseController
{
    private const SETTINGS_TABLES = [
        'rewards-contest'  => 'rc_settings',
        'social-campaigns' => 'sc_settings',
        'facebook-ads'     => 'fb_settings',
        'safe-updater'     => 'su_settings',
    ];

    private const GUARD_PATHS = [
        'rewards-contest'  => 'RewardsContest/PluginLicenseGuard.php',
        'social-campaigns' => 'SocialCampaigns/PluginLicenseGuard.php',
        'facebook-ads'     => 'FacebookAds/PluginLicenseGuard.php',
        'safe-updater'     => 'SafeUpdater/PluginLicenseGuard.php',
    ];

    private const LICENSE_SERVER = 'https://license.ar-script.com';

    private function json(array $data, int $code = 200): never
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    private function loadGuard(string $slug): bool
    {
        $guardFile = ROOT_PATH . '/plugins/' . (self::GUARD_PATHS[$slug] ?? '');

        if (!class_exists('\\PluginLicenseGuard', false) && is_file($guardFile)) {
            require_once $guardFile;
        }

        return class_exists('\\PluginLicenseGuard', false);
    }

    private function normalizeDomain(string $domain): string
    {
        $domain = strtolower(trim($domain));
        $domain = preg_replace('#^https?://#i', '', $domain);
        $domain = preg_replace('#/.*$#', '', $domain);
        $domain = preg_replace('#:\d+$#', '', $domain);
        $domain = preg_replace('#^www\.#i', '', $domain);
        return $domain !== '' ? $domain : 'unknown';
    }

    private function currentDomain(): string
    {
        return $this->normalizeDomain((string)($_SERVER['HTTP_HOST'] ?? ''));
    }

    private function currentFingerprint(): string
    {
        try {
            return Fingerprint::generate();
        } catch (\Throwable $e) {
            return hash('sha256', $this->currentDomain() . '|' . PHP_VERSION);
        }
    }

    private function getAdminEmail(): string
    {
        try {
            $stmt = db()->query("SELECT email FROM admins WHERE is_active = 1 AND email IS NOT NULL AND email <> '' ORDER BY id ASC LIMIT 1");
            $email = trim((string)$stmt->fetchColumn());
            return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : '';
        } catch (\Throwable $e) {
            return '';
        }
    }

    private function postJson(string $endpoint, array $payload): ?array
    {
        if (!function_exists('curl_init')) {
            return null;
        }

        $url = self::LICENSE_SERVER . $endpoint;
        $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if ($json === false) {
            return null;
        }

        $attempts = [
            [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2],
            [CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0],
        ];

        foreach ($attempts as $sslOpts) {
            $ch = curl_init($url);
            if ($ch === false) {
                continue;
            }

            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $json,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Accept: application/json',
                ],
                CURLOPT_CONNECTTIMEOUT => 5,
                CURLOPT_TIMEOUT => 12,
            ] + $sslOpts);

            $raw = curl_exec($ch);
            $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($raw === false || $http < 200 || $http >= 500) {
                continue;
            }

            $data = json_decode((string) $raw, true);
            if (is_array($data)) {
                return $data;
            }
        }

        return null;
    }

    private function reportViolation(string $slug, string $key, string $reason): void
    {
        try {
            $this->postJson('/api/report.php', [
                'license_key' => $key,
                'domain' => $this->currentDomain(),
                'reason' => $reason,
                'product' => $slug,
                'plugin_slug' => $slug,
                'fingerprint' => $this->currentFingerprint(),
                'email' => $this->getAdminEmail(),
            ]);
        } catch (\Throwable $e) {
        }
    }

    public function verifyLicense(): void
    {
        $key  = trim((string)($_POST['license_key'] ?? ''));
        $slug = trim((string)($_POST['slug'] ?? ''));

        if ($key === '' || $slug === '') {
            $this->json(['success' => false, 'message' => 'Missing license key or plugin slug.']);
        }

        if (!isset(self::GUARD_PATHS[$slug])) {
            $this->json(['success' => false, 'message' => 'Unknown licensed plugin slug.']);
        }

        if ($this->loadGuard($slug) && method_exists('\\PluginLicenseGuard', 'clearCache')) {
            \PluginLicenseGuard::clearCache($slug, $key);
        }

        $response = $this->postJson('/api/verify.php', [
            'license_key' => $key,
            'domain' => $this->currentDomain(),
            'fingerprint' => $this->currentFingerprint(),
            'plugin_slug' => $slug,
        ]);

        if (!is_array($response)) {
            $this->json([
                'success' => false,
                'message' => 'تعذر الاتصال بسيرفر التراخيص. حاول مجددًا.'
            ]);
        }

        $serverSlug = trim((string)($response['plugin_slug'] ?? ''));
        if ($serverSlug !== '' && $serverSlug !== $slug) {
            $this->reportViolation($slug, $key, 'wrong_plugin');
            $this->json([
                'success' => false,
                'message' => "هذا الكود مخصص للإضافة [{$serverSlug}] وليس [{$slug}].",
            ]);
        }

        $action = (string)($response['action'] ?? 'block');
        $status = (string)($response['status'] ?? 'invalid');
        $serverMsg = trim((string)($response['message'] ?? ''));
        $domainBound = trim((string)($response['domain_bound'] ?? ''));

        if ($action !== 'allow' || !in_array($status, ['active', 'ok'], true)) {
            $reason = match ($status) {
                'expired' => 'expired',
                'disabled' => 'disabled',
                'delete_required' => 'delete_required',
                'limit_reached' => 'limit_reached',
                'violation', 'domain_mismatch' => 'domain_mismatch',
                default => 'invalid',
            };
            $this->reportViolation($slug, $key, $reason);

            $msg = match ($status) {
                'expired' => 'انتهت صلاحية هذا الترخيص.',
                'disabled' => 'هذا الترخيص معطّل.',
                'delete_required' => 'تم إصدار أمر نهائي من السيرفر لهذا الترخيص.',
                'limit_reached' => 'تجاوز الترخيص الحد المسموح به.',
                'domain_mismatch' => $domainBound !== '' ? 'هذا الكود مرتبط بدومين آخر: ' . $domainBound : 'هذا الكود مرتبط بدومين آخر.',
                'violation' => $serverMsg !== '' ? $serverMsg : ($domainBound !== '' ? 'هذا الكود مرتبط بدومين آخر: ' . $domainBound : 'تم رفض هذا الترخيص.'),
                default => $serverMsg !== '' ? $serverMsg : 'كود الترخيص غير صالح.',
            };

            $this->json([
                'success' => false,
                'message' => $msg,
                'status' => $status,
            ]);
        }

        $this->json([
            'success' => true,
            'message' => 'License verified.',
            'status' => $status,
            'expires' => $response['expires'] ?? null,
            'type' => $response['type'] ?? 'single_domain',
            'plugin_slug' => $response['plugin_slug'] ?? $slug,
        ]);
    }

    public function enableLicensed(string $slug): void
    {
        $key = trim((string)($_POST['license_key'] ?? ''));

        if ($key === '' || $slug === '') {
            $this->json(['success' => false, 'message' => 'Missing data.']);
        }

        $table = self::SETTINGS_TABLES[$slug] ?? null;
        if (!$table) {
            $this->json(['success' => false, 'message' => 'Unknown licensed plugin slug.']);
        }

        try {
            $pdo = db();

            try {
                $pdo->exec("ALTER TABLE `{$table}` ADD COLUMN IF NOT EXISTS `license_key` VARCHAR(64) DEFAULT NULL");
            } catch (\Throwable $e) {
            }

            $count = (int)$pdo->query("SELECT COUNT(*) FROM `{$table}`")->fetchColumn();
            if ($count === 0) {
                $pdo->prepare("INSERT INTO `{$table}` (`license_key`) VALUES (?)")->execute([$key]);
            } else {
                $pdo->prepare("UPDATE `{$table}` SET license_key = ?")->execute([$key]);
            }

            if ($this->loadGuard($slug) && method_exists('\\PluginLicenseGuard', 'clearCache')) {
                \PluginLicenseGuard::clearCache($slug, $key);
            }

            PluginManager::enable($slug);

            $this->json(['success' => true, 'message' => 'Plugin activated successfully!']);
        } catch (\Throwable $e) {
            $this->json(['success' => false, 'message' => 'Activation error: ' . $e->getMessage()]);
        }
    }
}
