<?php
namespace Backend\BaseBundle\Controller\API;

use Backend\BaseBundle\Model\Site;
use Backend\BaseBundle\Response\APIJsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\ProcessBuilder;

/**
 * @Route("/seo")
 */
class SEOController extends BaseController
{
    /**
     * @Route("/")
     * @Method({"GET"})
     */
    public function indexAction(Site $site, Request $request)
    {
        $url = $request->get('url');

        if($url === null){
            return new Response('', Response::HTTP_BAD_REQUEST);
        }

        $parsed = parse_url($url);
        $domains = $this->findAcceptDomain($site);

        if(!$parsed || !isset($parsed['host']) || !isset($parsed['scheme']) || !preg_match('/^https?$/i', $parsed['scheme'])) {
            return new Response('', Response::HTTP_NOT_ACCEPTABLE);
        }

        if(!$domains || !in_array($parsed['host'], $domains)){
            return new Response('bad request domain', Response::HTTP_FORBIDDEN);
        }

        if(!($scriptPath = $this->getFetchScriptPath())){
            throw $this->createNotFoundException();
        }

        $tmpOutput = tempnam($this->container->getParameter('kernel.cache_dir'), md5(self::class));

        $builder = new ProcessBuilder();
        $process = $builder->setPrefix('env')
            ->setArguments(array(
                'phantomjs',
                '--proxy-type=none',
                '--ignore-ssl-errors=true',
                '--load-images=false',
                '--local-to-remote-url-access=true',
                $scriptPath,
                $tmpOutput,
                $url,
            ))
            ->getProcess()
        ;
        $process->run();
        $result = file_get_contents($tmpOutput);
        @unlink($tmpOutput);
        return $this->createJsonResponse($result);
    }

    protected function getFetchScriptPath()
    {
        return realpath($this->container->getParameter('kernel.root_dir').'/../seo/fetch.js');
    }

    protected function findAcceptDomain(Site $site)
    {
        $config = $this->get('backend_base.site_config_builder')->build($site->getId())->get('system');

        if(!isset($config['domains'])){
            return null;
        }

        return explode(',', trim($config['domains']));
    }
}