<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\RouterInterface;

final class SocialNetworkController extends AbstractController
{
    public function __construct(
        private readonly SocialNetworkRepository $socialNetworkRepository,
        private readonly RouterInterface $router,
        private readonly EntityManagerInterface $entityManager,
    ) {
    }

    /**
     * DEPRECATED OLD INSTAGRAM API (REMOVE IN THE FUTURE).
     *
     * @throws \Exception
     */
    #[Route('/request/instagram_token', options: ['expose' => true], name: 'instagram_token')]
    public function instagramAccessToken(Request $request): JsonResponse|RedirectResponse
    {
        $config = $this->socialNetworkRepository->findOneBy(['network' => 'instagram']);

        if (!$config) {
            throw new NotFoundHttpException('Instagram non installé sur ce site');
        }

        if (!$config->getToken() || $config->getTokenAt() < new \DateTime('now')) {
            $clientId = $config->getConfiguration()['clientId'];
            $clientSecret = $config->getConfiguration()['clientSecret'];

            $redirectUri = $request->getUriForPath(
                $this->router->generate('instagram_token', [], RouterInterface::ABSOLUTE_PATH)
            );

            if ($request->get('code')) {
                $fields = [
                    'client_id' => $clientId,
                    'client_secret' => $clientSecret,
                    'grant_type' => 'authorization_code',
                    'redirect_uri' => $redirectUri,
                    'code' => $request->get('code'),
                ];

                $url = 'https://api.instagram.com/oauth/access_token';

                $ch = curl_init();
                curl_setopt($ch, \CURLOPT_URL, $url);
                curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, \CURLOPT_TIMEOUT, 20);
                curl_setopt($ch, \CURLOPT_POST, true);
                curl_setopt($ch, \CURLOPT_POSTFIELDS, $fields);
                $result = curl_exec($ch);
                curl_close($ch);

                $result = json_decode($result);

                $config->setToken($result->access_token);

                $date = new \DateTime('now');
                $date->add(new \DateInterval('P1M'));
                $config->setTokenAt($date);

                $this->entityManager->persist($config);
                $this->entityManager->flush();

                return new JsonResponse($config->getToken());
            }

            return new RedirectResponse(
                'https://www.instagram.com/oauth/authorize/?client_id='
                .$clientId
                .'&redirect_uri='
                .$redirectUri
                .'&response_type=code'
            );
        }

        return new JsonResponse($config->getToken());
    }
}
