<?php
// functions.php — PHP 7.2 compatível (sem arrow functions / type hints)
require __DIR__ . '/vendor/autoload.php';

// Geolocalização via ip-api.com (inclui org como fallback)
function lookupIp($ip) {
    $url  = 'http://ip-api.com/json/' . $ip . '?fields=status,country,regionName,city,isp,org';
    $json = @file_get_contents($url);
    $data = $json ? json_decode($json, true) : array();

    $isp = isset($data['isp']) ? $data['isp'] : '';
    $org = isset($data['org']) ? $data['org'] : '';

    return array(
        'country' => isset($data['country'])    ? $data['country']    : 'Unknown',
        'state'   => isset($data['regionName']) ? $data['regionName'] : 'Unknown',
        'city'    => isset($data['city'])       ? $data['city']       : 'Unknown',
        'asn_org' => $org !== '' ? $org : $isp
    );
}

function isBot($ua) {
    $bots = array('bot','spider','crawl','slurp','facebookexternalhit');
    foreach ($bots as $b) {
        if (stripos($ua, $b) !== false) {
            return true;
        }
    }
    return false;
}

function isCloud($org) {
    // Lista de provedores/hosts a bloquear
    $clouds = array(
        'Amazon','AWS',
        'Microsoft','Azure',
        'Google','GCP',
        'DigitalOcean',
        'OVH',
        'Eveo',        // cobre EVEO Telecomunicações S.A.
        'Hostroyale',  // cobre Hostroyale
        'HSC'          // cobre HSC (ex.: HSC Networks)
    );

    foreach ($clouds as $c) {
        if ($c !== '' && stripos($org, $c) !== false) {
            return true;
        }
    }
    return false;
}

function shellBlock($action, $ip) {
    $safe = escapeshellarg($ip);
    exec('sudo ' . BLOCK_SCRIPT . ' ' . $action . ' ' . $safe);
}

function processAccess($ip, $ua) {
    $geo    = lookupIp($ip);
    $md     = new \Detection\MobileDetect();
    $device = $md->isMobile() ? 'mobile' : 'desktop';

    $status = 'liberado';

    // Bloqueia se: bot, fora do Brasil, ou provedor/AS de nuvem (inclui Eveo, Hostroyale e HSC)
    if (isBot($ua) || $geo['country'] !== 'Brazil' || isCloud($geo['asn_org'])) {
        $status = 'bloqueado';
        shellBlock('add', $ip);
    }

    $rec = array(
        'time'    => date('Y-m-d H:i:s'),
        'ip'      => $ip,
        'country' => $geo['country'],
        'state'   => $geo['state'],
        'city'    => $geo['city'],
        'asn'     => $geo['asn_org'],
        'device'  => $device,
        'status'  => $status
    );
    file_put_contents(LOG_FILE, json_encode($rec, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND | LOCK_EX);
    return $status;
}

function readLogs() {
    if (!file_exists(LOG_FILE)) return array();
    $lines = file(LOG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $out   = array();
    foreach ($lines as $l) {
        $d = json_decode($l, true);
        if (is_array($d)) $out[] = $d;
    }
    return $out;
}
