<?php
// DEBUG SCRIPT: descarga la página indicada y muestra los primeros bytes en texto y hex.
// Uso: acceder vía navegador: http://tu-host/debug_fetch.php?url=/fuelpos/
// o por CLI: php debug_fetch.php http://localhost/fuelpos/

$url = $_GET['url'] ?? ($argv[1] ?? '');
if (!$url) {
    echo "Usage: debug_fetch.php?url=/path/to/index.php  OR php debug_fetch.php http://localhost/fuelpos/\n";
    exit;
}

// make sure url is absolute for CLI convenience
if (!preg_match('/^https?:\\/\\//', $url)) {
    // assume local host if path only
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    if (strpos($url, '/') === 0) $url = $scheme . '://' . $host . $url;
    else $url = $scheme . '://' . $host . '/' . ltrim($url, '/');
}

echo "Fetching: $url\n\n";

$opts = [
    "http"=> [
        "method"=>"GET",
        "header"=>"User-Agent: DebugFetchScript/1.0\r\nAccept: */*\r\n"
    ]
];
$context = stream_context_create($opts);
$resp = @file_get_contents($url, false, $context);
if ($resp === false) {
    echo "ERROR: Could not fetch URL. Try from server CLI: php -r \"echo file_get_contents('$url');\" \n";
    exit;
}

// show first N bytes and lines
$Nbytes = 1024;
$firstBytes = substr($resp, 0, $Nbytes);

// show as text (first 80 lines)
echo "=== FIRST 80 LINES (text) ===\n";
$lines = preg_split("/(\r\n|\n|\r)/", $firstBytes);
for ($i=0; $i < min(80, count($lines)); $i++) {
    $ln = $lines[$i];
    $num = $i+1;
    printf("%04d: %s\n", $num, $ln);
}

echo "\n=== FIRST " . $Nbytes . " BYTES (hex) ===\n";
// hex dump
$hex = unpack('C*', $firstBytes);
$bytes = array_values($hex);
$line = '';
for ($i=0;$i<count($bytes);$i++) {
    printf("%02x ", $bytes[$i]);
    if ((($i+1) % 16) === 0) echo "\n";
}
echo "\n\n=== RAW (escaped) ===\n";
// show non-printables as \xHH
$rawEsc = '';
for ($i=0;$i<strlen($firstBytes);$i++) {
    $c = $firstBytes[$i];
    $oc = ord($c);
    if ($oc >= 32 && $oc <= 126) $rawEsc .= $c;
    else $rawEsc .= sprintf("\\x%02x",$oc);
}
echo $rawEsc . "\n";
?>