<?php
require_once __DIR__ . '/EntityClass.php';
use Core\EntityIpCheck;

function EntityMessage($action = "VISIT", $ip = "::1") {
    require_once __DIR__ . '/EntityVariables.php';

    $entity = new EntityIpCheck();
    $result = $entity->lookup($ip);

    if ($result) {
        $logEntry = [
            'timestamp'        => date('c'),
            'visitorIp'        => $result['visitorIp'] ?? '',
            'isp'              => $result['connection']['isp'] ?? '',
            'visitorCountry'   => $result['visitorCountry'] ?? '',
            'visitorDevice'    => $result['visitorDevice'] ?? '',
            'message'          => $action
        ];

        $logDir = dirname(__DIR__) . '/logs';
        if (!is_dir($logDir)) {
            mkdir($logDir, 0777, true);
        }

        $logFile = $logDir . '/entity_visitors.jsonl';
        file_put_contents($logFile, json_encode($logEntry) . PHP_EOL, FILE_APPEND);
    }
}

function EntityInfo($ip = "::1") {
    require_once __DIR__ . '/EntityVariables.php';
    $time = date("Y-m-d H:i:s");
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $visitorData = [
        'ip'             => $ip,
        'userAgent'      => $userAgent,
        'time'           => $time,
        'visitorCountry' => "Unknown",
        'visitorCountryCode' => "Unknown",
        'visitorDevice'  => "Unknown",
        'isp'            => "Unknown",
        'asn'            => "Unknown",
        'location'       => [
            'city'      => "Unknown",
            'region'    => "Unknown",
            'zip'       => "Unknown",
            'latitude'  => "",
            'longitude' => ""
        ],
        'timezone'       => [
            'id'  => "Unknown",
            'utc' => "Unknown"
        ]
    ];

    $entity = new EntityIpCheck();
    $result = $entity->lookup($ip);

    if (is_array($result)) {
        $visitorData['ip']             = $result['ip'] ?? $visitorData['ip'];
        $visitorData['userAgent']      = $result['visitorUserAgent'] ?? $visitorData['userAgent'];
        $visitorData['visitorCountry'] = $result['visitorCountry'] ?? $visitorData['visitorCountry'];
        $visitorData['visitorCountryCode'] = $result['visitorCountryCode'] ?? $visitorData['visitorCountryCode'];
        $visitorData['visitorDevice']  = $result['visitorDevice'] ?? $visitorData['visitorDevice'];
        $visitorData['isp']            = $result['connection']['isp'] ?? $visitorData['isp'];
        $visitorData['asn']            = $result['connection']['asn'] ?? $visitorData['asn'];
        $visitorData['location']['city']      = $result['location']['city'] ?? $visitorData['location']['city'];
        $visitorData['location']['region']    = $result['location']['region'] ?? $visitorData['location']['region'];
        $visitorData['location']['zip']       = $result['location']['zip'] ?? $visitorData['location']['zip'];
        $visitorData['location']['latitude']  = $result['location']['latitude'] ?? $visitorData['location']['latitude'];
        $visitorData['location']['longitude'] = $result['location']['longitude'] ?? $visitorData['location']['longitude'];
        $visitorData['timezone']['id']        = $result['timezone']['id'] ?? $visitorData['timezone']['id'];
        $visitorData['timezone']['utc']       = $result['timezone']['utc'] ?? $visitorData['timezone']['utc'];
    }

    return $visitorData;
}

function KarmaGetRandomQuote() {
    $quotes = [
        "And whoever puts their trust in Allah, then He alone is sufficient for them. — Qur’an 65:3",
        "Indeed, Allah is with those who trust in Him. — Qur’an 3:159",
        "So do not lose hope, nor be sad. You will surely be victorious if you are true believers. — Qur’an 3:139",
        "When you have taken a decision, put your trust in Allah. — Qur’an 3:159",
        "Indeed, Allah is with the patient. — Qur’an 2:153",
        "So be patient. Indeed, the promise of Allah is truth. — Qur’an 30:60",
        "Verily, with hardship comes ease. — Qur’an 94:6",
        "And be patient, for your patience is with the help of Allah. — Qur’an 16:127",
        "If you are grateful, I will surely increase you [in favor]. — Qur’an 14:7",
        "And Allah is the bestower of bounty to whomever He wills. — Qur’an 62:4",
        "Say: Whatever blessing you have is from Allah. — Qur’an 16:53",
        "Verily, in the remembrance of Allah do hearts find rest. — Qur’an 13:28",
        "The best among you are those who have the best manners and character. — Prophet Muhammad ﷺ (Bukhari)",
        "Modesty brings nothing but goodness. — Prophet Muhammad ﷺ (Muslim)",
        "Wealth is not in having many possessions, but true wealth is contentment of the soul. — Prophet Muhammad ﷺ (Bukhari & Muslim)",
        "And it is He who enriches and suffices. — Qur’an 53:48",
        "Indeed, your Lord extends provision to whom He wills. — Qur’an 17:30",
        "Whoever fears Allah, He will make a way for him and provide for him from where he does not expect. — Qur’an 65:2-3",
        "The best of people are those who are most beneficial to others. — Prophet Muhammad ﷺ (Daraqutni)",
        "There is no fatigue or illness that afflicts a Muslim, except that Allah expiates some of his sins. — Bukhari & Muslim",
        "Indeed, my Lord is near and responsive. — Qur’an 11:61",
        "And your Lord says: Call upon Me, I will respond to you. — Qur’an 40:60",
        "Whoever puts their trust in Allah – then indeed, Allah is Exalted in Might and Wise. — Qur’an 8:49",
        "Allah does not burden a soul beyond that it can bear. — Qur’an 2:286",
        "Say: Never will we be struck except by what Allah has decreed for us; He is our protector. — Qur’an 9:51",
        "And whoever turns away from My remembrance – indeed, he will have a depressed life. — Qur’an 20:124",
        "Indeed, Allah loves those who rely upon Him. — Qur’an 3:159",
        "And be not like those who forgot Allah, so He made them forget themselves. — Qur’an 59:19",
        "And whoever is patient and forgives – indeed, that is of the matters requiring determination. — Qur’an 42:43",
        "And whoever does righteous deeds, whether male or female, while being a believer – We will surely cause them to live a good life. — Qur’an 16:97",
        "Do not grieve; indeed Allah is with us. — Qur’an 9:40",
        "Indeed, Allah will not change the condition of a people until they change what is in themselves. — Qur’an 13:11",
        "Indeed, the mercy of Allah is near to the doers of good. — Qur’an 7:56",
        "And establish prayer for My remembrance. — Qur’an 20:14",
        "So remember Me; I will remember you. — Qur’an 2:152",
        "Indeed, good deeds erase bad deeds. — Qur’an 11:114",
        "Indeed, those who have believed and done righteous deeds – they will have the Gardens of Paradise. — Qur’an 18:107",
        "Indeed, Allah loves those who are constantly repentant and loves those who purify themselves. — Qur’an 2:222",
        "And your Lord is Forgiving, Full of Mercy. — Qur’an 18:58",
        "And Allah is the best of planners. — Qur’an 3:54",
        "Whoever comes [on the Day of Judgment] with a good deed will have ten times the like thereof. — Qur’an 6:160",
        "The strong believer is more beloved to Allah than the weak believer, while there is good in both. — Prophet Muhammad ﷺ (Muslim)",
        "Make things easy, and do not make them difficult. — Prophet Muhammad ﷺ (Bukhari)",
        "Whoever does not thank people has not thanked Allah. — Prophet Muhammad ﷺ (Ahmad, Tirmidhi)",
        "Do not become angry. — Prophet Muhammad ﷺ (Bukhari)",
        "The most beloved deeds to Allah are those done regularly, even if they are small. — Prophet Muhammad ﷺ (Bukhari)",
        "A smile is charity. — Prophet Muhammad ﷺ (Tirmidhi)",
        "Allah is Gentle and loves gentleness in all matters. — Prophet Muhammad ﷺ (Bukhari & Muslim)",
        "He who does not show mercy to others, will not be shown mercy. — Prophet Muhammad ﷺ (Bukhari & Muslim)",
        "The best among you are those who learn the Qur’an and teach it. — Prophet Muhammad ﷺ (Bukhari)",
        "None of you truly believes until he loves for his brother what he loves for himself. — Prophet Muhammad ﷺ (Bukhari & Muslim)",
        "Part of the perfection of one's Islam is his leaving that which does not concern him. — Prophet Muhammad ﷺ (Tirmidhi)",
        "He who believes in Allah and the Last Day should speak good or remain silent. — Prophet Muhammad ﷺ (Bukhari & Muslim)",
        "Whoever follows a path in pursuit of knowledge, Allah will make a path to Paradise easy for him. — Prophet Muhammad ﷺ (Muslim)",
        "Be in this world as though you were a stranger or a traveler. — Prophet Muhammad ﷺ (Bukhari)",
        "Fear Allah wherever you are, and follow up a bad deed with a good one and it will wipe it out. — Prophet Muhammad ﷺ (Tirmidhi)",
        "The most beloved of people to Allah are those who bring the most benefit to others. — Prophet Muhammad ﷺ (Tabarani)",
        "Whoever relieves a believer’s distress of the distressful aspects of this world, Allah will rescue him from a difficulty of the difficulties of the Hereafter. — Prophet Muhammad ﷺ (Muslim)"
    ];
    return $quotes[array_rand($quotes)];
}

function EntityDetectBin(string $digits): ?array
{
    require_once __DIR__ . '/EntityVariables.php';

    $apiKey = defined('IIN_API_KEY')
        ? IIN_API_KEY
        : 'QqAMZu2gQ70V5cbxsA5KFowevwO4MPQZ';

    if (empty($digits)) {
        return null;
    }

    $url = 'https://api.iinapi.com/iin?' . http_build_query([
        'key'    => $apiKey,
        'digits' => $digits
    ]);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER     => ['Accept: application/json']
    ]);

    $response = curl_exec($ch);
    $status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false || $status !== 200) {
        return null;
    }

    $json = json_decode($response, true);

    if (!empty($json['valid']) && isset($json['result']) && is_array($json['result'])) {
        return $json['result'];
    }

    return null;
}
function CheckEntity($ip, $userAgent) {
    $karma_config = require __DIR__ . '/../KarmaEntity/config/config.php';
    require_once __DIR__ . '/EntityVariables.php';

    $entityApiKey = $karma_config['entity_apikey'];
    $apiUrl = "https://entitygate.net/api/whoami/v1/sc";

    if (empty($ip)) {
        error_log("CheckEntity: Empty IP, aborting.");
        return false;
    }

    if (empty($userAgent)) {
        $userAgent = 'Mozilla/5.0 (compatible; EntityBotChecker/1.0)';
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "x-entity-api-key: $entityApiKey",
        "x-visitor-ip-asli: $ip",
        "x-visitor-user-agent: $userAgent",
        'x-visitor-accept: ' . ($_SERVER['HTTP_ACCEPT'] ?? ''),
        'x-visitor-accept-language: ' . ($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''),
        'x-visitor-accept-encoding: ' . ($_SERVER['HTTP_ACCEPT_ENCODING'] ?? ''),
        'x-visitor-connection: ' . ($_SERVER['HTTP_CONNECTION'] ?? ''),
        'x-visitor-referer: ' . ($_SERVER['HTTP_REFERER'] ?? ''),
        'x-visitor-sec-fetch-site: ' . ($_SERVER['HTTP_SEC_FETCH_SITE'] ?? ''),
        'x-visitor-sec-ch-ua: ' . ($_SERVER['HTTP_SEC_CH_UA'] ?? ''),
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode($response, true);

    if ($httpCode === 200 && isset($data['allowed']) && $data['allowed']) {
        EntityMessage('VISIT', $ip);
        return true;
    } elseif ($httpCode === 403 && isset($data['reason'])) {
        EntityMessage('BLOCKED BY ENTITY', $ip);
        header("Location: https://http.cat/images/404.jpg");
        exit;
    } elseif ($httpCode === 429) {
        die("Too many requests. Please try again later.");
    } else {
        die($response);
    }
}
?>
