<?php

header("Content-Type: application/xml; charset=utf-8");

$SUPABASE_URL = "https://dgbfllheakeofycxsxci.supabase.co";
$SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRnYmZsbGhlYWtlb2Z5Y3hzeGNpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDgwOTQ0NjgsImV4cCI6MjA2MzY3MDQ2OH0._0k4cDOsfpD0yeqINheTIVZi5PrWMDW7NKjEu5-aGqE";

$url = $SUPABASE_URL . "/rest/v1/ads?select=id,title,location,ad_images(image_url,is_main)&limit=500";

$options = [
  "http" => [
    "method" => "GET",
    "header" =>
      "apikey: $SUPABASE_KEY\r\n" .
      "Authorization: Bearer $SUPABASE_KEY\r\n"
  ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);

echo '<?xml version="1.0" encoding="UTF-8"?>';

echo '<urlset 
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';

foreach ($data as $ad) {

  $image = "";

  if(isset($ad["ad_images"])) {
    foreach($ad["ad_images"] as $img) {
      if($img["is_main"]){
        $image = $img["image_url"];
        break;
      }
    }
  }

  if($image){

    echo "<url>";

    echo "<loc>https://6maps.online/ad/".$ad["id"]."</loc>";

    echo "<image:image>";
    echo "<image:loc>".$image."</image:loc>";
    echo "<image:title>".htmlspecialchars($ad["title"])."</image:title>";
    echo "<image:caption>".htmlspecialchars($ad["location"])." erotické služby</image:caption>";
    echo "</image:image>";

    echo "</url>";
  }

}

echo "</urlset>";