<?php

namespace App\Controller;

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

use App\Entity\PropertySale;

class AverageSurfacePrice
{
    private $em;

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

    public function __invoke(Request $data)
    {
        $query = "SELECT AVG(ps.price/ps.surface) as value, DATE_TRUNC('month', ps.date) month
            FROM App:PropertySale ps
            WHERE ps.price != 0 AND ps.surface != 0
            GROUP BY month";

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

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

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

?>