<?php declare(strict_types=1);

namespace BrandCrockAquaTheme\Content;

use BrandCrockAquaTheme\Content\InstagramPostStruct;
use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
use Shopware\Core\Content\Cms\DataResolver\CriteriaCollection;
use Shopware\Core\Content\Cms\DataResolver\Element\AbstractCmsElementResolver;
use Shopware\Core\Content\Cms\DataResolver\Element\ElementDataCollection;
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\ResolverContext;

class InstagramWidgetCmsElementResolver extends AbstractCmsElementResolver
{
    public function getType(): string
    {
        return 'bc-instagram-widget';
    }

    public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
    {
        return null;
    }

    public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
    {
        $config = $slot->getFieldConfig();
        $token = $config->get('accessToken')->getValue();
        $fields = "id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username";
        $limit = $config->get('limit')->getValue() ?? 12;

        try {
            $json_feed_url= "https://graph.instagram.com/me/media?fields={$fields}&access_token={$token}&limit={$limit}";
            $ch = curl_init($json_feed_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $json_feed = file_get_contents($json_feed_url);
            $contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);
            $posts = new InstagramPostStruct();
            $posts->setPosts($contents['data']);
            $slot->setData($posts);
        } catch (\Throwable $th) {}
    }
}
