<?php
// STRICT BOT BLOCKER - fail-closed (agresif terhadap bot)
// Ubah $humanPath / $botPath sesuai folder kamu

$ip        = $_SERVER['REMOTE_ADDR'] ?? '';
$ua        = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
$referer   = strtolower($_SERVER['HTTP_REFERER'] ?? '');
$isBot     = false;
$debugLog  = __DIR__ . '/debug_log.txt';

// Paths
$humanPath = '/id/regis/';   // halaman untuk manusia (HP)
$botPath   = '/id/selling/';   // halaman untuk bot & desktop

// --- Very aggressive bot signatures (block if matched) ---
$botSignatures = [
  'googlebot','adsbot-google','mediapartners-google','feedfetcher-google',
  'bingbot','slurp','yandexbot',
  'facebookexternalhit','facebot',
  'bytespider','ttcrawler','tiktokbot',
  'gptbot','claudebot','perplexitybot','applebot','openai','anthropic','cohere','huggingface',
  'curl','wget','python-urllib','node-fetch','okhttp','bot','spider','crawler','headless','phantomjs'
];

// --- Allowlist: UA fragments we want to PRESERVE as human (in-app browsers etc.)
$humanUaAllow = [
  'instagram', 'fbav', 'fban', 'fbbrowser', 'fbios', 'twitter', 'tiktok', 'okhttp', 'cfnetwork', 'mozilla', 'chrome', 'safari', 'edge'
];

// ==================
// DETEKSI HP / MOBILE
// ==================
$isMobile = false;
$mobileKeywords = [
  'iphone', 'ipod', 'ipad',     // iOS devices
  'android',                    // Android
  'blackberry',
  'opera mini',
  'iemobile',
  'windows phone',
  'mobile',                     // generic "mobile" flag
];

if ($ua !== '') {
  foreach ($mobileKeywords as $m) {
    if (strpos($ua, $m) !== false) {
      $isMobile = true;
      break;
    }
  }
}

// Quick check: click params from ads => treat as human (tetap, tapi nanti tetap dicek mobile / desktop)
$adClicks = isset($_GET['ttclid']) || isset($_GET['fbclid']) || isset($_GET['gclid']) || isset($_GET['wbraid']) || isset($_GET['gbraid']);
if ($adClicks) {
  $isBot = false;
}

// If UA contains any allowlist fragment => prefer human (skip false positive)
// But still continue other checks for verified bots (we'll not block if purely allowlist)
$uaIsLikelyHuman = false;
foreach ($humanUaAllow as $h) {
  if ($ua !== '' && strpos($ua, $h) !== false) {
    $uaIsLikelyHuman = true;
    break;
  }
}

// If UA matches strong bot signature => flag for verification
$uaMatchesBot = false;
foreach ($botSignatures as $b) {
  if ($ua !== '' && strpos($ua, $b) !== false) {
    $uaMatchesBot = true;
    break;
  }
}

// Helper: verify via reverse DNS + forward lookup for known vendor domains
function verifyVendorIP(string $ip, array $domains) : bool {
  if (!filter_var($ip, FILTER_VALIDATE_IP)) return false;
  $rdns = @gethostbyaddr($ip);
  if (!$rdns) return false;
  $rdns_l = strtolower($rdns);
  $ok = false;
  foreach ($domains as $d) {
    if (substr($rdns_l, -strlen($d)) === $d) { $ok = true; break; }
  }
  if (!$ok) return false;
  // forward confirm
  $fwd = @gethostbyname($rdns);
  return ($fwd === $ip);
}

// If the UA explicitly says it's an official crawler, verify it
$verifiedOfficialBot = false;
if ($uaMatchesBot) {
  // Google
  if (strpos($ua, 'googlebot') !== false || strpos($ua, 'adsbot-google') !== false || strpos($ua, 'mediapartners-google') !== false) {
    if (verifyVendorIP($ip, ['.googlebot.com', '.google.com'])) $verifiedOfficialBot = true;
  }
  // Bing/MSN
  if (strpos($ua, 'bingbot') !== false || strpos($ua, 'slurp') !== false) {
    if (verifyVendorIP($ip, ['.search.msn.com', '.bing.com'])) $verifiedOfficialBot = true;
  }
  // ByteDance / TikTok
  if (strpos($ua, 'bytespider') !== false || strpos($ua, 'ttcrawler') !== false || strpos($ua, 'tiktokbot') !== false) {
    if (verifyVendorIP($ip, ['.bytedance.com', '.byteplus.com'])) $verifiedOfficialBot = true;
  }
  // Facebook
  if (strpos($ua, 'facebookexternalhit') !== false || strpos($ua, 'facebot') !== false) {
    if (verifyVendorIP($ip, ['.facebook.com', '.fb.com'])) $verifiedOfficialBot = true;
  }

  // If verifiedOfficialBot true => definitely bot
  if ($verifiedOfficialBot) {
    $isBot = true;
  } else {
    // **STRICT MODE**: if UA looks like bot but vendor verification failed, treat as bot (fail-closed)
    $failOpen = false;
    if ($failOpen === false) {
      $isBot = true;
    } else {
      // fail-open: allow through but flag in logs
      $isBot = false;
    }
  }
}

// If UA didn't match bot signatures but also not allowlist, you can further examine headers:
if (!$isBot && !$uaIsLikelyHuman) {
  $accept = $_SERVER['HTTP_ACCEPT'] ?? '';
  $alang  = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
  // Heuristic: real browsers almost always send Accept and Accept-Language
  if (empty($accept) || empty($alang)) {
    // Strict: treat missing headers as bot
    $isBot = true;
  }
}

// --- Debug log entry ---
$entry = [
  'date' => date('c'),
  'ip' => $ip,
  'ua' => $ua,
  'referer' => $referer,
  'uaIsLikelyHuman' => $uaIsLikelyHuman,
  'uaMatchesBot' => $uaMatchesBot,
  'verifiedOfficialBot' => $verifiedOfficialBot,
  'isBot' => $isBot,
  'isMobile' => $isMobile,
  'adClicks' => $adClicks
];
file_put_contents($debugLog, json_encode($entry, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);

// Redirect (use 302 for testing; set to 301 when final)
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

// =========================
// LOGIC AKHIR REDIRECT:
// - Kalau BOT -> ke $botPath
// - Kalau BUKAN BOT tapi BUKAN MOBILE -> tetap ke $botPath (desktop)
// - HANYA MOBILE & bukan bot -> ke $humanPath
// =========================
$targetPath = $humanPath;

if ($isBot) {
  $targetPath = $botPath;
} else {
  if (!$isMobile) {
    // Desktop, walaupun manusia, diarahkan ke botPath
    $targetPath = $botPath;
  }
}

header("Location: {$targetPath}", true, 302);
exit();
