<?php

namespace App\Controller;



use App\Entity\Formules;
use App\Entity\Product;
use App\Repository\FormulesRepository;
use App\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;

class FeedController extends AbstractController
{
    #[Route('/rss/{channel}', name: 'app_rss_feed', defaults: ['channel' => 'all'])]
    public function rss(
        string $channel,
        ProductRepository $productRepo,
        FormulesRepository $formuleRepo
    ): Response {
        $items = [];

        if ($channel === 'all' || $channel === 'products') {
            $items = array_merge($items, $productRepo->findBy([], ['updatedAt' => 'DESC'], 20));
        }

        if ($channel === 'all' || $channel === 'formules') {
            $items = array_merge($items, $formuleRepo->findBy(['isPublish' => true], ['updatedAt' => 'DESC'], 20));
        }

        // Sort everything by date descending
        usort($items, fn($a, $b) => $b->getUpdatedAt() <=> $a->getUpdatedAt());

        return $this->render('feed/rss.xml.twig', [
            'items' => $items,
            'current_channel' => $channel
        ], new Response('', 200, ['Content-Type' => 'application/xml']));
    }

    // src/Controller/FeedController.php

    #[Route('/feed/json', name: 'app_json_feed')]
    public function jsonFeed(UploaderHelper $uploaderHelper,ProductRepository $productRepo, FormulesRepository $formuleRepo): JsonResponse
    {
        $products = $productRepo->findBy([], ['updatedAt' => 'DESC'], 20);
        $formules = $formuleRepo->findBy(['isPublish' => true], ['updatedAt' => 'DESC'], 20);

        $items = array_merge($products, $formules);
        usort($items, fn($a, $b) => $b->getUpdatedAt() <=> $a->getUpdatedAt());

        $data = [
            'version' => 'https://jsonfeed.org/version/1.1',
            'title' => 'LudikEvent - Catalogue JSON',
            'home_page_url' => $this->generateUrl('app_crm_reservation', [], 0),
            'feed_url' => $this->generateUrl('app_json_feed', [], 0),
            'feed_rss' => $this->generateUrl('app_rss_feed', [], 0),
            'items' => []
        ];

        foreach ($items as $item) {
            $isProduct = ($item instanceof Product);

            $url = $isProduct
                ? $this->generateUrl('reservation_product_show', ['id' => $item->slug()], 0)
                : $this->generateUrl('reservation_formule_show', ['slug' => $item->slug()], 0);

            $data['items'][] = [
                'id' => $url,
                'url' => $url,
                'title' => $item->getName(),
                'content_html' => $item->getDescription(),
                'date_modified' => (is_null($item->getUpdatedAt()) ? null : $item->getUpdatedAt()->getTimestamp()),
                'image' => ($item->getImageFile() !="")?$uploaderHelper->asset($items,'imageFile'):'/provider/images/favicon.webp',
                '_type' => $isProduct ? 'produit' : 'formule'
            ];
        }

        return new JsonResponse($data);
    }
}
