<?php

namespace App\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use App\Entity\PropertySale;
use \DateTime;

class SalesByRegion
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
      $this->em = $em;
    }

    public function __invoke(Request $data)
    {
        $year = $data->query->get('year');

        if(!preg_match('/^\d{4}$/', $year)) {
            return new Response(
                'Bad Request',
                Response::HTTP_BAD_REQUEST,
                ['content-type' => 'application/text']
            );
        }

        $year = $year.'-01-01';

        $query = "SELECT
                    ps.region,
                    COUNT(ps) value
                FROM App:PropertySale ps
                WHERE
                    DATE_TRUNC('year', ps.date) = '$year'
                GROUP BY ps.region";

        $query = $this->em
            ->createQuery($query)
            ->getResult();

        $result = array_map(function($data) {
            $data['value'] = intval($data['value']);
            return $data;
        }, $query);

        return new Response(
            json_encode($result),
            Response::HTTP_OK,
            ['content-type' => 'application/json']
        );
    }
}

?>