<?php
require 'vendor/autoload.php';
require "./lib/config.php";

use GuzzleHttp\Client;

$responseJSON = [];

$client = new Client();
$headers = [
    'authorization' => 'Basic ' . $ebayKleinanzeigenToken,
    'user-agent' => 'okhttp/4.9.1',
    'x-ebayk-app' => '4e10d7fd-6fef-4f87-afb0-b8ede2f494071636475109828',
    'Host' => 'api.ebay-kleinanzeigen.de',
    'Accept' => '*/*',
    'Accept-Encoding' => 'gzip, deflate, br'
];
$response = $client->request('GET', "https://api.ebay-kleinanzeigen.de/api/ads.json?_in=title,price,pictures,link,features-active,search-distance,negotiation-enabled,attributes,medias,medias.media,medias.media.title,medias.media.media-link,store-id,store-title&page=0&size=31&userIds=$ebayKleinanzeigenUserId&pictureRequired=false&includeTopAds=false&limitTotalResultCount=true", [
    'headers' => $headers ]);

$response = json_decode($response->getBody(), true);
$ads = $response["{http://www.ebayclassifiedsgroup.com/schema/ad/v1}ads"]["value"]["ad"];

foreach($ads as $ad) {
    $element = [
        "title" => $ad["title"]["value"],
        "price" => $ad["price"]["amount"]["value"] . " €",
        "shipping" => "nein"
    ];

    foreach($ad["attributes"]["attribute"] as $attribute) {
        if(str_contains($attribute["name"], "versand")) {
            $element["shipping"] = $attribute["value"][0]["value"];
        }
    }

    foreach($ad["link"] as $link) {
        if($link["rel"] == "self-public-website") {
            $element["link"] = $link["href"];
        }
    }

    if(sizeof($ad["pictures"]["picture"]) > 0) {
        foreach($ad["pictures"]["picture"][0]["link"] as $picture) {
            if($picture["rel"] == "teaser") {
                $element["previewImage"] = str_replace("https://i.ebayimg.com", "/API/ebayimg.php?url=", $picture["href"]);
            }
            if($picture["rel"] == "XXL") {
                
                $element["image"] = str_replace("https://i.ebayimg.com", "/API/ebayimg.php?url=", $picture["href"]);
            }
        }
    }

    array_push($responseJSON, $element);
}

if(isset($_GET["count"])) {
    echo sizeof($responseJSON);
    die();
}
echo json_encode($responseJSON);