<?php

namespace KupShop\MarketingBundle\Controller;

use KupShop\MarketingBundle\SupportBox\InfoProvider;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class SupportBoxController extends AbstractController
{
    /**
     * @Route(path="/_supportbox/")
     */
    public function accountAction(Request $request, InfoProvider $infoProvider)
    {
        $this->authorization('id', $request);

        if (!$request->get('email') && !$request->get('phone')) {
            return new JsonResponse(['html' => '', 'error' => 'Query parameters `email` or `phone` not provided']);
        }

        return new JsonResponse(
            $infoProvider->getAdditionalData((string) $request->get('email'), (string) $request->get('phone'))
        );
    }

    /**
     * @Route(path="/_supportbox/phone/{number}/")
     */
    public function phoneAction(Request $request, InfoProvider $infoProvider, $number)
    {
        $this->authorization('id_phone', $request);

        return new JsonResponse($infoProvider->getName($number));
    }

    public function authorization($serviceType, $request)
    {
        $dbcfg = \Settings::getDefault();

        $key = $dbcfg->analytics['supportbox'][$serviceType] ?? false;

        if (!$key || ($key != $request->get('key') && 'Basic '.$key != $request->headers->get('Authorization'))
        ) {
            throw new NotFoundHttpException('Route not found.');
        }
    }
}
