<?php

define('CONFIG', [
    'url'    => 'https://enemalta.com.mt/Planned-Outages6.php',
    'town'   => 'mellieha',
    'street' => 'qamh'
]);

/**
 * Normalizes text by removing Maltese accents, converting to lowercase, 
 * collapsing multiple spaces, and removing dashes.
 */
function normalizeText($text) {
    if (!$text) return '';
    
    // Lowercase
    $text = mb_strtolower($text, 'UTF-8');
    
    // Replace non-breaking spaces with standard space
    $text = str_replace(chr(194).chr(160), ' ', $text);
    $text = str_replace('&nbsp;', ' ', $text);
    
    // Convert specific Maltese characters
    $maltese = ['ħ', 'ġ', 'ż', 'ċ'];
    $replacements = ['h', 'g', 'z', 'c'];
    $text = str_replace($maltese, $replacements, $text);
    
    // Strip other accents (NFD normalization fallback via iconv or translit)
    $text = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);
    
    // Normalize dashes to spaces
    $text = preg_replace('/[-–—_]/u', ' ', $text);
    
    // Clear remaining special characters
    $text = preg_replace('/[^a-z0-9\s]/', '', $text);
    
    // Collapse multiple spaces & trim
    $text = preg_replace('/\s+/', ' ', $text);
    
    return trim($text);
}

function printMatch($event, $matchedContext) {
    echo "\n[MATCH FOUND] Planned Outage Detected!\n";
    echo "Town:    " . $event['town'] . "\n";
    echo "Time:    " . $event['from'] . " -> " . $event['to'] . "\n";
    echo "Context: " . substr($matchedContext, 0, 120) . "...\n";
}

function isPowerCutPlanned() {
    // 1. Fetch data using cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, CONFIG['url']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    
    $html = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($html === false || $httpCode !== 200) {
        trigger_error('Scraper failed to pull data.', E_USER_WARNING);
        return false;
    }

    // 2. Parse HTML using DOMDocument and DOMXPath
    $dom = new DOMDocument();
    // Suppress errors caused by invalid HTML structures commonly found on the web
    @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);

    $events = [];
    $currentTown = null;
    $currentFrom = null;
    $currentTo = null;

    // Grab all rows within any table
    $rows = $xpath->query('//table//tr');

    foreach ($rows as $row) {
        $tds = $xpath->query('.//td', $row);
        $rowId = $row->getAttribute('id');

        // Condition 1: Main Rows have exactly 4 columns and no row ID
        if ($tds->length === 4 && empty($rowId)) {
            $currentTown = trim($tds->item(0)->nodeValue);
            $currentFrom = trim($tds->item(1)->nodeValue);
            $currentTo   = trim($tds->item(2)->nodeValue);
        } 
        // Condition 2: Detail Rows have an active row ID starting with "row"
        elseif (str_starts_with($rowId, 'row')) {
            $detailsText = $tds->length > 0 ? trim($tds->item(0)->nodeValue) : '';
            
            if ($currentTown) {
                $events[] = [
                    'town'    => $currentTown,
                    'from'    => $currentFrom,
                    'to'      => $currentTo,
                    'details' => $detailsText
                ];
            }
        }
    }

    // 3. Search Evaluation Phase
    $targetTown = normalizeText(CONFIG['town']);
    $targetStreet = !empty(CONFIG['street']) ? normalizeText(CONFIG['street']) : null;
    $matchFound = false;

    foreach ($events as $event) {
        $currentTownCleaned = normalizeText($event['town']);
        $currentDetailsCleaned = normalizeText($event['details']);

        // Check if the town matches
        if ($currentTownCleaned === $targetTown || str_contains($currentTownCleaned, $targetTown)) {
            
            // Fallback: If no street is supplied, trigger a match on the town alone
            if (!$targetStreet) {
                $matchFound = true;
                // printMatch($event, "Entire Town (No specific street requested)");
                break;
            }

            // Standard Match: Look for specific street inside details text
            if (str_contains($currentDetailsCleaned, $targetStreet)) {
                $matchFound = true;
                // printMatch($event, $event['details']);
                break;
            }
        }
    }

    return $matchFound;
}

// Run Script
$isPlanned = isPowerCutPlanned();

header('Content-Type: application/json');
if ($isPlanned) {
    // Match found: Set status to 200 OK
    http_response_code(200);
    echo json_encode([
        'status' => 'found',
        'power_cut_planned' => true,
        'redirect_url' => 'https://www.enemalta.com.mt/map/',
        'message' => 'Power cut planned in your area. Check the map for more details.',
        'data' => [
            'town' => CONFIG['town'],
            'street' => CONFIG['street'],
            'from' => $currentFrom,
            'to' => $currentTo
        ]
    ]);
} else {
    // No match found: Set status to 204 No content found
    http_response_code(204);
    echo json_encode([
        'status' => 'not found',
        'power_cut_planned' => false
    ]);
}
