<?php
// Pobranie pliku XML
$url = 'https://feed.syntogether.com/skroutz/xml?shop=ac8a92-2.myshopify.com';
$xmlContent = file_get_contents($url);
if ($xmlContent === false) {
    die("Nie udało się pobrać XML.");
}

// Wczytanie XML
$doc = new DOMDocument();
$doc->loadXML($xmlContent);
$xpath = new DOMXPath($doc);

$newDoc = new DOMDocument('1.0', 'UTF-8');
$newDoc->formatOutput = true;

$root = $newDoc->createElement('products');
$root->setAttribute('xmlns:g', 'http://base.google.com/ns/1.0'); // dodanie namespace dla g:
$newDoc->appendChild($root);

// Iteracja po produktach
foreach ($xpath->query('//product') as $product) {
    $newProduct = $newDoc->createElement('product');

    // Mapa znaczników ze starego na nowy
    $fields = [
        'id' => 'g:id',
        'name' => 'title',
        'link' => 'link',
        'image' => 'g:image_link',
        'mpn' => 'g:mpn',
        'manufacturer' => 'g:brand',
        'category' => 'g:product_type'
    ];

    foreach ($fields as $tag => $newTag) {
        $element = $xpath->query($tag, $product)->item(0);
        if ($element) {
            $value = trim($element->textContent);
            $newProduct->appendChild($newDoc->createElement($newTag, $value));
        }
    }

    // Dodaj gtin z pola <ean>
    $eanElement = $xpath->query('ean', $product)->item(0);
    $gtinValue = $eanElement ? trim($eanElement->textContent) : '';
    $newProduct->appendChild($newDoc->createElement('g:gtin', $gtinValue));

    $root->appendChild($newProduct);
}

// Zapis pliku XML
$newDoc->save('ekomi-feed.xml');

// Komunikat
echo 'Zapisano plik https://cdn.projectpro.pl/magiczne-perfumy.pl/ekomi-feed.xml';
