<?php
namespace Core\System\License;

use Core\System\Version;

/**
 * Sends license-tamper / fraud signals to the license server,
 * which stores them in violations_logs.
 *
 * Best-effort: never breaks the app flow if the server is unreachable.
 */
class ViolationsReporter
{
    protected string $endpoint = 'https://license.ar-script.com/api/report.php';

    // Optional product label (stored in violations_logs.product)
    protected string $product = 'MTEngine';

    public function __construct()
    {
        if (defined('MTE_PRODUCT')) {
            $this->product = (string) constant('MTE_PRODUCT');
        } elseif (class_exists(Version::class)) {
            $this->product = (string) Version::PRODUCT;
        }
    }

    public function report(string $reason, ?string $domain = null, ?string $fingerprint = null): void
    {
        $reason = trim($reason);
        if ($reason === '') {
            return;
        }

        try {
            $domain = $domain ?? (string)($_SERVER['HTTP_HOST'] ?? 'unknown');
            $domain = $this->normalizeDomain($domain);

            $fingerprint = $fingerprint ?? Fingerprint::generate();

            // ✅ جلب البريد من جدول admins فقط (كما طلبت)
            $email = $this->getAdminEmail();

            $payload = [
                'product'     => $this->product,
                'domain'      => $domain,
                'reason'      => $reason,
                'fingerprint' => $fingerprint,
                'email'       => $email,
                'reported_at' => time(),
            ];

            $ch = curl_init($this->endpoint);
            if ($ch === false) {
                return;
            }

            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST           => true,
                CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
                CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                CURLOPT_TIMEOUT        => 5,
                CURLOPT_CONNECTTIMEOUT => 3,
            ]);

            @curl_exec($ch);
            @curl_close($ch);

        } catch (\Throwable $e) {
            // Best-effort: لا نكسر أي شيء
        }
    }

    /**
     * ✅ Get admin email from admins table ONLY.
     */
    protected function getAdminEmail(): string
    {
        try {
            if (!function_exists('db')) {
                return '';
            }

            $pdo = db();

            $stmt = $pdo->prepare("
                SELECT email
                FROM admins
                WHERE is_active = 1
                  AND email IS NOT NULL
                  AND email != ''
                ORDER BY id ASC
                LIMIT 1
            ");

            $stmt->execute();
            $email = trim((string)$stmt->fetchColumn());

            return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : '';

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

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