<?php

use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
use GuzzleHttp\Client;

$ebayKleinanzeigenImages = new ObjectType([
    "name" => "EBK Image",
    "fields" => [
        "preview" => Type::string(),
        "image" => Type::string()
    ]
]);

$ebayKleinanzeigenElements = new ObjectType([
    "name" => "EBK Elements",
    "fields" => [
        "title" => Type::string(),
        "price" => Type::string(),
        "shipping" => Type::string(),
        "link" => Type::string(),
        "images" => [
            "type" => Type::listOf($ebayKleinanzeigenImages),    
            "args" => [
                "count" => Type::int()
            ]
        ],
        "id" => Type::string()
    ]
]);

$ebayKleinanzeigenFields = new ObjectType([
    "name" => "Ebay Kleinanzeigen",
    "fields" => [
        "count" => Type::int(),
        "elements" => Type::listOf($ebayKleinanzeigenElements)
    ],
]);

function ebayKleinanzeigen($imageCount) {
    require "./lib/config.php";
    $elements = [];

    $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" => html_entity_decode($ad["title"]["value"]),
            "id" => $ad["id"],
            "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"];
            }
        }

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

        array_push($elements, $element);
    }

    return [
        "count" => sizeof($elements),
        "elements" => $elements
    ];
}