<?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 SalesByGranularity
{
    private $em;

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

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

        if(!preg_match('/^(day|month|year)$/', $granularity)) {
            return new Response(
                'Bad Request : granularity in wrong format',
                Response::HTTP_BAD_REQUEST,
                ['content-type' => 'application/text']
            );
        }

        $date_regex = '/^\d{4}-\d{2}-\d{2}$/';
        if(!preg_match($date_regex, $date_start)) {
            return new Response(
                'Bad Request : date_start is in wrong format',
                Response::HTTP_BAD_REQUEST,
                ['content-type' => 'application/text']
            );
        }
        if(!preg_match($date_regex, $date_end)) {
            return new Response(
                'Bad Request : date_end is in wrong format',
                Response::HTTP_BAD_REQUEST,
                ['content-type' => 'application/text']
            );
        }

        $start = DateTime::createFromFormat("Y-m-d", $date_start);
        $end = DateTime::createFromFormat("Y-m-d", $date_end);

        if($end < $start) {
            return new Response(
                'Bad Request : date_end before date_start',
                Response::HTTP_BAD_REQUEST,
                ['content-type' => 'application/text']
            );
        }
        
        $query = "SELECT
                    DATE_TRUNC('$granularity', ps.date) sales_date,
                    COUNT(ps.price) sales
                  FROM App:PropertySale ps
                  WHERE
                    ps.date BETWEEN '$date_start' AND '$date_end'
                  GROUP BY sales_date
                  ORDER BY sales_date";       

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

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

?>