<?php

namespace App\Controller;

use App\Bundle\Calltouch\Request as CalltouchRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route("/api")
 */
class CalltouchAPIController extends AbstractController
{ 
    /**
     * @Route("/add-calltouch", methods={"POST"})
     */
    public function addCalltouch(Request $request): Response 
    {
        $data = [
            'requestNumber' => \md5(\time()),
            'subject' => $request->request->get('subject'),
            'requestUrl' => $request->request->get('requestUrl'),
            'requestDate' => \date('d-m-Y H:i:s'),
            'fio' => $request->request->get('fio'),
        ];
        
        if (! empty($request->request->get('sessionId'))) {
            $data['sessionId'] = $request->request->get('sessionId');
        }
                    
        if (! empty($request->request->get('customSources'))) {
            if (!empty($request->request->get('customSources')['source'])) {
                $data['customSources'] = $request->request->get('customSources');
            }
        }

        if (! empty($request->request->get('tag'))) {
            $data['addTags'][] = ['tag' => $request->request->get('tag')];
        }

        if (! empty($request->request->get('comment'))) {
            $data['comment']['text'] = json_encode($request->request->get('comment'), JSON_UNESCAPED_UNICODE);
        }

        if (! empty($request->request->get('phoneNumber'))) {
            $data['phoneNumber'] = $request->request->get('phoneNumber');
        }

        if (! empty($request->request->get('email'))) {
            $data['email'] = $request->request->get('email');
        }

        $calltouch = new CalltouchRequest();

        if (! empty($request->request->get('regionId'))) {
            $calltouch->changeRegion($request->request->get('regionId'));
        }

        $calltouch = $calltouch->create($data);
        
        return $this->json(['data' => $calltouch]);
    }
}
