<?php

namespace App\Controller\Www;
use App\Entity\Event;
use App\Entity\EventDate;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

#[Route("/calendrier", name: "www_calendar_")]
class CalendarController extends AbstractController
{
    #[Route("/",             name: "current")]
    #[Route("/current",      name: "current_2")]
    public function calendar_current(Request $request, EntityManagerInterface $manager, LoggerInterface $logger) {
        return $this->_calendar_by_month($request, $manager, $logger, 0);
    }

    #[Route("/next/{index}", name: "next", 
        requirements:[ 
            "index" => "\d+"
        ]
    )] 
    public function calendar_next(Request $request, EntityManagerInterface $manager, LoggerInterface $logger, $index = 1) {
        return $this->_calendar_by_month($request, $manager, $logger, $index);
    }

    #[Route("/prev/{index}", name: "prev", 
        requirements:[ 
            "index" => "\d+"
        ]
    )] 
    public function calendar_prev(Request $request, EntityManagerInterface $manager, LoggerInterface $logger, $index = 1) {
        return $this->_calendar_by_month($request, $manager, $logger, -$index);
    }

    public function _calendar_by_month(Request $request, EntityManagerInterface $manager, LoggerInterface $logger, $index) {

        // gestion du vrai min et max

        $now = new \DateTime("now");
        $now = new \DateTime($now->format('Y-M') . "-01");

        // https://www.php.net/manual/fr/class.dateinterval.php
        $interval = new \DateInterval("P". abs($index) ."M");
        if ($index < 0) {
            $interval->invert = 1;
        }

        $period = $now->add($interval);

        // $current_year = $now->format("Y");
        // $current_month = $now->format("M");

        $events_date = $manager->getRepository(EventDate::class)->getFormattedByMonth($period->format('Y'), $period->format('m'));

        return $this->render("www/calendar.html.twig",
            [
                "cal_index" => $index,
                "events_date" => $events_date,
                "prem_date" => $period
            ]
        );
    }
}