<?php
$url = 'https://www.djmusiccharts.com/category/country-top-50/';
$html = file_get_contents($url);

libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

// Find the first chart block (usually the latest post)
$chartBlock = $xpath->query("//div[contains(@class, 'td_module_10')]//a/@href");
if ($chartBlock->length === 0) {
  echo "⚠️ Could not find chart post.";
  exit;
}

$latestChartUrl = $chartBlock->item(0)->nodeValue;
$chartHtml = file_get_contents($latestChartUrl);
$dom->loadHTML($chartHtml);
$xpath = new DOMXPath($dom);

// Extract chart lines (look for <p> tags with chart entries)
$paragraphs = $xpath->query("//div[contains(@class, 'td-post-content')]//p");
$chart = [];

foreach ($paragraphs as $p) {
  $line = trim($p->textContent);
  if (preg_match('/^\d{1,2}\./', $line)) {
    $chart[] = $line;
  }
}

// Save to file
if (!empty($chart)) {
  file_put_contents('../data/top50.txt', implode("\n", $chart));
  echo "✅ Chart updated successfully with " . count($chart) . " entries.";
} else {
  echo "⚠️ Chart update failed — no entries found.";
}
