<?php
/**
 * @author Colinet Julien
 */

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin\SocialNetworkNewController;
use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
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\Annotation\Route;

class SocialNetworkController extends AbstractController
{
    private $socialNetworkRepository;

    public function __construct(SocialNetworkNewController $socialNetworkRepository)
    {
        $this->socialNetworkRepository = $socialNetworkRepository;
    }

    /**
     *
     * DEPRECATED OLD INSTAGRAM API ( REMOVE IN THE FUTUR )
     * @Route("/request/instagram_token", options={"expose"=true}, name="instagram_token")
     *
     * @param Request $request
     * @return JsonResponse|RedirectResponse
     * @throws \Exception
     */
    public function instagramAccessTokenAction(Request $request)
    {
        $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')) {
            $client_id     = $config->getConfiguration()['clientId'];
            $client_secret = $config->getConfiguration()['clientSecret'];
            $redirect_uri  = $request->getUriForPath($this->get('router')->generate('instagram_token', [], true));
            //$scope         = 'basic+likes+comments+relationships';

            if ($request->get('code')) {
                $fields = [
                    'client_id'     => $client_id,
                    'client_secret' => $client_secret,
                    'grant_type'    => 'authorization_code',
                    'redirect_uri'  => $redirect_uri,
                    '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->getDoctrine()->getManager()->persist($config);
                $this->getDoctrine()->getManager()->flush();

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

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

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