<?php
function scrapeWinners($url)
{
    // Initialize cURL session
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // Execute cURL and get the HTML content
    $html = curl_exec($ch);

    if (curl_errno($ch)) {
        echo "cURL error: " . curl_error($ch);
        curl_close($ch);
        return [];
    }

    curl_close($ch);

    // Load HTML into DOMDocument
    $dom = new DOMDocument();
    libxml_use_internal_errors(true); // Suppress HTML warnings
    $dom->loadHTML($html);
    libxml_clear_errors();

    // Parse the table containing winners
    $xpath = new DOMXPath($dom);
    $rows = $xpath->query("//table[contains(@class, 'table')]//tr");

    $winners = [];
    foreach ($rows as $rowIndex => $row) {
        // Skip the header row
        if ($rowIndex === 0) {
            continue;
        }

        $columns = $row->getElementsByTagName('td');
        if ($columns->length > 0) {
            $winners[] = [
                'constituency' => trim($columns->item(0)->textContent),
                'candidate' => trim($columns->item(1)->textContent),
                'party' => trim($columns->item(2)->textContent),
                'votes' => trim($columns->item(3)->textContent),
                'margin' => trim($columns->item(4)->textContent),
                'gender' => trim($columns->item(5)->textContent),
            ];
        }
    }

    return $winners;
}

// URL to scrape
$url = "https://w...content-available-to-author-only...a.info/Jharkhand2024/index.php?action=show_winners&sort=default";

// Scrape the data
$winnersList = scrapeWinners($url);

// Display the results
if (!empty($winnersList)) {
    echo "<table border='1'>";
    echo "<tr><th>Constituency</th><th>Candidate</th><th>Party</th><th>Votes</th><th>Margin</th><th>Gender</th></tr>";
    foreach ($winnersList as $winner) {
        echo "<tr>";
        echo "<td>{$winner['constituency']}</td>";
        echo "<td>{$winner['candidate']}</td>";
        echo "<td>{$winner['party']}</td>";
        echo "<td>{$winner['votes']}</td>";
        echo "<td>{$winner['margin']}</td>";
        echo "<td>{$winner['gender']}</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "No data found or unable to scrape.";
}
