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

use Backend\BaseBundle\Model\Site;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/config")
 */
class ConfigController extends BaseController
{
    /**
     * @Route("/{config}")
     * @Method({"GET"})
     * @Cache(expires="+24 hours", public=true)
     */
    public function indexAction(Site $site, Request $request, $config)
    {
        if(!in_array($config, array('google_tag_manager', 'recaptcha_site_key'))){
            return $this->createJsonResponse('', Response::HTTP_NOT_FOUND);
        }

        $content = $this->get('backend_base.site_config_builder')->build($site->getId())->get('system');

        return $this->createJsonResponse(array(
            'config' => isset($content[$config])?$content[$config]:null,
        ));
    }

    /**
     * 取得 g-reCaptcha 驗證是否成功
     * @Route("/grecaptchaverify")
     * @Method({"PUT"})
     * error[400.1] => 'not recaptcha'(沒有輸入驗證碼)
     */
    public function grecaptchaVerifyAction(Site $site, Request $request)
    {
        $parameters = json_decode($request->getContent(), true);

        if (!isset($parameters['grecaptcha']) || '' === trim($parameters['grecaptcha'])) {
            return $this->createJsonResponse(array('code' => 1, 'message' => 'not recaptcha'), Response::HTTP_BAD_REQUEST);
        }

        $content = $this->get('backend_base.site_config_builder')->build($site->getId())->get('system');
        $secretKey = isset($content['recaptcha_secret_key'])?$content['recaptcha_secret_key']:null;

        $response = $this->get('backend_base.custom_g_recaptcha')->captchaVerify($parameters['grecaptcha'], $secretKey);

        return $this->createJsonResponse(array(
            'status' => $response,
        ));
    }
}