<?php

$url = "https://logistek.windstripedesign.ro/en/";
$saveDir = __DIR__ . "/downloaded_site";
if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);

function downloadFile($fileUrl, $savePath) {
    $data = @file_get_contents($fileUrl);
    if ($data === false) {
        echo "Failed: $fileUrl\n";
        return false;
    }
    file_put_contents($savePath, $data);
    echo "Downloaded: $fileUrl -> $savePath\n";
    return true;
}

function absoluteUrl($base, $relative) {
    if (parse_url($relative, PHP_URL_SCHEME) != '') return $relative;
    if ($relative[0] == '/') {
        $parts = parse_url($base);
        return $parts['scheme'] . "://" . $parts['host'] . $relative;
    }
    return rtrim($base, '/') . '/' . ltrim($relative, '/');
}

// ---- Download main page ----
$html = file_get_contents($url);
if (!$html) die("Could not fetch main URL\n");

$localHtml = $saveDir . "/index.html";
file_put_contents($localHtml, $html);
echo "Saved HTML: $localHtml\n";

// ---- Parse assets ----
preg_match_all('/(src|href)="([^"]+)"/i', $html, $matches);
$assets = array_unique($matches[2]);

$assetDir = $saveDir . "/assets";
if (!is_dir($assetDir)) mkdir($assetDir, 0777, true);

foreach ($assets as $asset) {
    if (strpos($asset, "http") === false) {
        $fullUrl = absoluteUrl($url, $asset);
    } else {
        $fullUrl = $asset;
    }

    $pathInfo = pathinfo($asset);
    $filename = preg_replace('/[^a-zA-Z0-9_\.-]/', '_', $pathInfo['basename']);
    $localAssetPath = "$assetDir/$filename";

    if (downloadFile($fullUrl, $localAssetPath)) {
        // rewrite links in HTML
        $html = str_replace($asset, "assets/$filename", $html);
    }
}

file_put_contents($localHtml, $html);
echo "Updated HTML links.\n";

echo "\nDONE! Offline copy saved in: $saveDir\n";

?>
