<?php
// ==========================
// ✅ Database Configuration
// ==========================
include "../includes/db.php";

// ==========================
// 🕒 Timezone & Dates
// ==========================
date_default_timezone_set('Asia/Kolkata');
$today        = date('Y-m-d');
$current_time = date('H:i');
$yesterday    = date('Y-m-d', strtotime('-1 day'));

// ==========================
// 🧠 Load Active Markets
// ==========================
$markets = [];
$stmt = $db->query("SELECT title, game_id, time_open FROM games WHERE is_active = 1");
foreach ($stmt as $row) {
    $markets[$row['title']] = [
        'game_id'   => $row['game_id'],
        'time_open' => $row['time_open']
    ];
}

// ==========================
// 🌐 Robust cURL Fetch Function
// ==========================
function fetchHTML($url, $maxAttempts = 3): ?string {
    for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);
        $html = curl_exec($ch);
        $error = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($error) {
            echo "⚠️ Attempt $attempt: cURL Error – $error<br>";
        } elseif ($http_code !== 200) {
            echo "⚠️ Attempt $attempt: HTTP Status $http_code<br>";
        } elseif ($html && strlen($html) > 10000) {
            echo "✅ Attempt $attempt: HTML fetched successfully (" . strlen($html) . " bytes)<br>";
            return $html;
        }

        // Retry delay
        sleep(3);
    }

    echo "❌ All $maxAttempts attempts failed to fetch HTML.<br>";
    return null;
}

// ==========================
// 🧠 Extract Result by Market Name
// ==========================
function extractResult(string $title, string $html): ?string {
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query("//h4[text()='{$title}']/following-sibling::span[1]");
    return $nodes->length ? trim($nodes->item(0)->nodeValue) : null;
}

// ==========================
// 🧩 Parse Result Pattern
// ==========================
function parseResult(string $text): array {
    $text = trim(str_replace(["\n", "\r"], "", $text));
    if (preg_match('/^(\d{3})-\d{1,3}-(\d{3})$/', $text, $m)) return ['open' => $m[1], 'close' => $m[2]];
    if (preg_match('/^(\d{3})-\d{1,3}$/', $text, $m))        return ['open' => $m[1], 'close' => null];
    if (preg_match('/^(\d{3})$/', $text, $m))                return ['open' => $m[1], 'close' => null];
    return ['open' => null, 'close' => null];
}

// ==========================
// 🌐 Fetch HTML & Save Locally
// ==========================
$url = "https://dpboss.boston/";
$html = fetchHTML($url);

if (!$html) {
    exit("❌ Failed to fetch or empty HTML from $url. Please check if the site is blocking bots or down.<br>");
}

// Save a local copy (for backup)
$file_path = 'local_clone.html';
file_put_contents($file_path, $html);
echo "✅ HTML page saved to $file_path<br>";

// ==========================
// 🔍 Read Local File & Process
// ==========================
$html = file_get_contents($file_path);
if (!$html) exit("❌ Failed to read local HTML file: $file_path<br>");

// ==========================
// 🧾 Process Each Market
// ==========================
foreach ($markets as $market => $info) {
    $game_id   = $info['game_id'];
    $time_open = $info['time_open'];

    $raw = extractResult($market, $html);
    if (!$raw) {
        echo "❌ $market: No result found<br>";
        continue;
    }

    $parsed = parseResult($raw);
    if (!$parsed['open']) {
        echo "❌ $market: Invalid format '$raw'<br>";
        continue;
    }

    $open_digits  = str_pad($parsed['open'], 3, '0', STR_PAD_LEFT);
    $close_digits = $parsed['close'] !== null ? str_pad($parsed['close'], 3, '0', STR_PAD_LEFT) : null;

    // Determine correct draw date
    $draw_date = (strtotime($current_time) < strtotime($time_open)) ? $yesterday : $today;

    // Check last saved result
    $stmt = $db->prepare("SELECT draw_date, open_digits, close_digits FROM results WHERE game_id = ? ORDER BY draw_date DESC LIMIT 1");
    $stmt->execute([$game_id]);
    $last = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($last && $last['open_digits'] === $open_digits && $last['close_digits'] === $close_digits) {
        echo "⏩ $market: Same result as {$last['draw_date']}<br>";
        continue;
    }

    // Check if result exists for current date
    $stmt = $db->prepare("SELECT result_id, open_digits, close_digits FROM results WHERE game_id = ? AND draw_date = ?");
    $stmt->execute([$game_id, $draw_date]);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing) {
        $needUpdate = false;
        if ($existing['close_digits'] !== $close_digits && $close_digits !== null) {
            $stmt = $db->prepare("UPDATE results SET close_digits = ? WHERE result_id = ?");
            $stmt->execute([$close_digits, $existing['result_id']]);
            echo "🔁 $market: Close updated to $close_digits<br>";
            $needUpdate = true;
        }
        if ($existing['open_digits'] !== $open_digits) {
            $stmt = $db->prepare("UPDATE results SET open_digits = ?, close_digits = ? WHERE result_id = ?");
            $stmt->execute([$open_digits, $close_digits, $existing['result_id']]);
            echo "🔁 $market: Open/Full updated<br>";
            $needUpdate = true;
        }
        if (!$needUpdate) {
            echo "ℹ️ $market: Already up-to-date<br>";
        }
    } else {
        // DONO ERRORS YAHAN FIX KIYE GAYE HAIN: 'passing' aur 'is_holiday' add karke dono ko 0 value di hai
        $stmt = $db->prepare("INSERT INTO results (game_id, draw_date, open_digits, close_digits, passing, is_holiday) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$game_id, $draw_date, $open_digits, $close_digits, 0, 0]);
        echo "✅ $market: New inserted $open_digits / " . ($close_digits ?? 'NULL') . " for $draw_date<br>";
    }
}
?>