<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Controller\Dashboard;

use Doctrine\DBAL\Connection;
use Ferienpass\AdminBundle\Controller\TagsResponses;
use Ferienpass\CoreBundle\HttpCache\CacheTag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;

/**
 * ESI fragment rendering the attendances-per-day heatmap on the admin
 * dashboard. Like {@see \Ferienpass\AdminBundle\Controller\Fragment\StashCountController}
 * it's a tenant-global aggregate carrying the synthetic {@see CacheTag::dashboard()}
 * tag, so the year-cached outer /admin page stays frozen while the
 * CacheInvalidationListener keeps this fragment fresh on attendance changes.
 */
class HeatmapController extends AbstractController
{
    use TagsResponses;

    private const int TTL = 31556926;

    public function __construct(private readonly Connection $connection)
    {
    }

    public function __invoke(#[Autowire(param: 'app.id')] string $appId): Response
    {
        if (!$this->isGranted('ROLE_ADMIN')) {
            return new Response('', Response::HTTP_NO_CONTENT);
        }

        $response = $this->render('@FerienpassAdmin/fragment/dashboard/heatmap.html.twig', [
            'values' => $this->countAttendancesByDay(),
        ]);

        // Tenant-global and identical for every admin of the tenant (Varnish
        // keys the fragment by host), so it's shareable — no Vary: Cookie.
        $response->setPublic();
        $response->setSharedMaxAge(self::TTL);
        $this->tagResponse(CacheTag::dashboard($appId));

        return $response;
    }

    private function countAttendancesByDay(): array
    {
        $days = $this->connection
            ->executeQuery(
                <<<'SQL'
                    SELECT DATE_FORMAT(a.createdAt, '%Y-%m-%d') AS day, COUNT(*)
                    FROM Attendance a
                    WHERE a.createdAt > (NOW() - INTERVAL 1 YEAR)
                    GROUP BY day
                    ORDER BY day
                    SQL
            )
            ->fetchAllNumeric();

        $return = [];
        foreach ($days as $row) {
            $ymd = $row[0];
            $ymd = strtotime((string) $ymd);
            $return[$ymd] = (int) $row[1];
        }

        return $return;
    }
}
