<?php
/**
 * WINGO LIVE RESULT API v2.1 - FIXED
 * Returns single digit (0-9) as plain text
 * Fixed: SSL verification disabled for compatibility
 */

error_reporting(0);
ini_set('display_errors', 0);

// ═══════════════════════════════════════════════════════════════
//  LOAD CONFIG
// ═══════════════════════════════════════════════════════════════

$config_path = __DIR__ . '/../wingo-config.json';

if (!file_exists($config_path)) {
    http_response_code(500);
    header('Content-Type: text/plain');
    echo 'Config missing';
    exit;
}

$config_json = @file_get_contents($config_path);
if ($config_json === false) {
    http_response_code(500);
    header('Content-Type: text/plain');
    echo 'Config read error';
    exit;
}

$CONFIG = @json_decode($config_json, true);
if (!is_array($CONFIG)) {
    http_response_code(500);
    header('Content-Type: text/plain');
    echo 'Config invalid';
    exit;
}

$whitelist       = $CONFIG['whitelist'] ?? ['localhost', '127.0.0.1'];
$cache_ttl       = $CONFIG['cache_ttl'] ?? 30;
$api_base        = $CONFIG['api_base'] ?? 'https://draw.ar-lottery01.com/WinGo';
$fallback_secret = $CONFIG['fallback_secret'] ?? 'default_secret_2026';
$type_map        = $CONFIG['type_map'] ?? [
    '1' => 'WinGo_1M', '2' => 'WinGo_3M', '3' => 'WinGo_5M',
    '4' => 'WinGo_30S', '5' => 'WinGo_10M'
];

$cache_dir = __DIR__ . '/../cache_wingo';
$log_dir   = __DIR__ . '/../logs_wingo';


// ═══════════════════════════════════════════════════════════════
//  HELPERS
// ═══════════════════════════════════════════════════════════════

function log_error($msg) {
    global $log_dir;
    if (!is_dir($log_dir)) @mkdir($log_dir, 0755, true);
    @file_put_contents($log_dir . '/error_' . date('Y-m-d') . '.log',
        '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND | LOCK_EX);
}

function extract_domain($url) {
    if (empty($url)) return '';
    $host = parse_url(trim($url), PHP_URL_HOST);
    if ($host) return strtolower($host);
    $url = preg_replace('#^https?://#i', '', trim($url));
    $url = preg_replace('#[:/].*$#', '', $url);
    return strtolower($url);
}

function is_allowed($domain, $whitelist) {
    if (empty($domain)) return false;
    foreach ($whitelist as $allowed) {
        $allowed = strtolower($allowed);
        if ($domain === $allowed) return true;
        if (substr($domain, -strlen('.' . $allowed)) === '.' . $allowed) return true;
    }
    return false;
}

function get_cache($key) {
    global $cache_dir, $cache_ttl;
    $file = $cache_dir . '/' . $key . '.json';
    if (!file_exists($file)) return null;
    if ((time() - filemtime($file)) > $cache_ttl) return null;
    $data = @file_get_contents($file);
    return $data ? @json_decode($data, true) : null;
}

function set_cache($key, $data) {
    global $cache_dir;
    if (!is_dir($cache_dir)) @mkdir($cache_dir, 0755, true);
    @file_put_contents($cache_dir . '/' . $key . '.json', json_encode($data), LOCK_EX);
}

function fetch_api($slug) {
    global $api_base;
    $url = rtrim($api_base, '/') . '/' . $slug . '/GetHistoryIssuePage.json';

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,    // ← FIXED: was true, causing failure
        CURLOPT_SSL_VERIFYHOST => 0,        // ← FIXED: added
        CURLOPT_HTTPHEADER     => [
            'Accept: application/json, text/plain, */*',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        ],
    ]);

    $body      = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err       = curl_error($ch);
    curl_close($ch);

    if ($body === false || $http_code !== 200) {
        log_error("API fail [$slug]: HTTP $http_code | $err");
        return null;
    }

    $json = @json_decode($body, true);
    if (!is_array($json) || ($json['code'] ?? -1) !== 0) {
        log_error("API bad JSON [$slug]: " . substr($body, 0, 200));
        return null;
    }

    return $json;
}

function fallback_digit($typeId) {
    global $fallback_secret, $cache_ttl;
    $window = floor(time() / $cache_ttl);
    $hash = hash_hmac('sha256', $typeId . ':' . $window, $fallback_secret);
    return (string)(hexdec(substr($hash, -8)) % 10);
}

function respond($code, $body) {
    http_response_code($code);
    header('Content-Type: text/plain; charset=utf-8');
    header('Cache-Control: no-store');
    echo $body;
    exit;
}


// ═══════════════════════════════════════════════════════════════
//  MAIN LOGIC
// ═══════════════════════════════════════════════════════════════

// Domain check
$referer     = extract_domain($_SERVER['HTTP_REFERER'] ?? '');
$from_domain = extract_domain($_GET['from_domain'] ?? '');
$authorized  = is_allowed($referer, $whitelist) || is_allowed($from_domain, $whitelist);

if (!$authorized && php_sapi_name() !== 'cli') {
    log_error("403: referer=$referer from=$from_domain");
    respond(403, 'Forbidden');
}

// Validate typeId
$typeId = isset($_GET['typeId']) ? (string)$_GET['typeId'] : '';
if (!isset($type_map[$typeId])) {
    respond(400, 'Invalid typeId');
}

$slug      = $type_map[$typeId];
$cache_key = 'wingo_' . $slug;

// Try cache
$cached = get_cache($cache_key);
$digit  = null;

if ($cached && isset($cached['data']['list'][0]['number'])) {
    $digit = (string)((int)$cached['data']['list'][0]['number'] % 10);
}

// Cache miss → fetch from external API
if ($digit === null) {
    $api_data = fetch_api($slug);
    if ($api_data) {
        set_cache($cache_key, $api_data);
        if (isset($api_data['data']['list'][0]['number'])) {
            $digit = (string)((int)$api_data['data']['list'][0]['number'] % 10);
        }
    }
}

// Fallback
if ($digit === null) {
    log_error("Fallback used: typeId=$typeId ($slug)");
    $digit = fallback_digit($typeId);
}

respond(200, $digit);
