<?php require_once "/var/www/html/config.database.php"; ?>
<?php
/**
 * FXH News Blocker (ForexFactory HTML Scrape – RED Impact Only)
 * Response must be ONLY:
 *   BLOCK
 *   OK
 */

date_default_timezone_set("Europe/London");

$blockBefore = 10;
$blockAfter  = 10;
$debug       = isset($_GET['debug']);

$calendarUrl = "https://www.forexfactory.com/calendar?week";

// ------------------- Fetch page -------------------
$ch = curl_init($calendarUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => 0,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_USERAGENT      => "Mozilla/5.0",
]);
$html = curl_exec($ch);
curl_close($ch);

if(!$html || strlen($html) < 50) {
    if($debug) echo "OK | Unable to load FF page";
    exit("OK");
}

// ------------------- Extract events -------------------
$now = time();
$pattern = '/<tr.*?calendar__row.*?>(.*?)<\/tr>/si';
preg_match_all($pattern, $html, $rows);

foreach($rows[1] as $row) {

    // Check for RED impact icon
    if(stripos($row, 'impact-red') === false)
        continue;

    // Extract date and time
    preg_match('/calendar__date.*?>(.*?)</si', $row, $dateMatch);
    preg_match('/calendar__time.*?>(.*?)</si', $row, $timeMatch);

    $date = trim(strip_tags($dateMatch[1] ?? ''));
    $time = trim(strip_tags($timeMatch[1] ?? ''));

    if(!$date || !$time || $time == "All Day" || $time == "Tentative")
        continue;

    // Convert to timestamp
    $eventTS = strtotime("$date $time");
    if(!$eventTS) continue;

    $from = $eventTS - ($blockBefore * 60);
    $to   = $eventTS + ($blockAfter * 60);

    // Check active blocking window
    if($now >= $from && $now <= $to) {
        if($debug) {
            preg_match('/calendar__event-title.*?>(.*?)</si', $row, $titleMatch);
            $title = trim(strip_tags($titleMatch[1] ?? "High Impact News"));
            echo "BLOCK | $title | Window=" . date("H:i", $from) . "-" . date("H:i", $to);
            exit;
        }
        exit("BLOCK");
    }
}

// ------------------- No RED News Active -------------------
if($debug) {
    echo "OK | NO RED NEWS ACTIVE";
} else {
    echo "OK";
}
exit;
?>
