<?php declare(strict_types=1);

namespace App\Controller\Page;

use App\Repository\UserRepository;
use App\Service\PaginationMaker;
use App\Service\SizeFormatter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    public function __construct(private readonly UserRepository $userRepository)
    {
    }

    #[Route(
        path: '/home/{page?}',
        name: 'app_home',
        requirements: ['page' => '\d+'],
        defaults: ['page' => 1],
        methods: ['GET']
    )]
    public function index(Request $request, int $page): Response
    {
        $user = $this->userRepository->findOneBy(['username' => $this->getUser()->getUserIdentifier()]);
        $allFiles = $user->getFiles();

        // Define the number of files to display per page
        $perPage = 10;

        // Create a pagination object
        $pagination = new PaginationMaker();
        $files = $pagination->paginate($allFiles->toArray(), $page, $perPage);

        $sizeFormatter = new SizeFormatter();

        // Calculate total size and total uploads
        $totalSize = $sizeFormatter->calculateTotalSize($allFiles);
        $todaysUploads = $this->countTodaysUploads($allFiles);

        // Calculate total pages
        $totalPages = ceil(count($allFiles) / $perPage);

        return $this->render('home/index.html.twig', [
            'files' => $files,
            'totalUploads' => count($allFiles),
            'totalSize' => $totalSize,
            'todaysUploads' => $todaysUploads,
            'currentPage' => $page,
            'totalPages' => $totalPages,
        ]);
    }

    private function countTodaysUploads($files): int
    {
        $today = date('Y-m-d');
        $filesArray = $files->toArray();

        return count(array_filter($filesArray, function ($file) use ($today) {
            return $file->getCreatedAt()->format('Y-m-d') === $today;
        }));
    }
}
