<?php

declare(strict_types=1);

namespace App\Extensions\Twig;

use DateTime;
use Twig\Environment;
use Twig\TwigFunction;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Twig\Error\RuntimeError;
use App\Entity\Acteurs\Locataires;
use Doctrine\ORM\NoResultException;
use Symfony\UX\Chartjs\Model\Chart;
use Twig\Extension\AbstractExtension;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Component\Security\Core\Security;
use App\Repository\Acteurs\LocatairesRepository;
use App\Repository\Security\Logs\LogsRepository;
use App\Repository\Acteurs\ProprietairesRepository;
use App\Repository\Properties\PropertiesRepository;
use App\Repository\Quittances\QuittancesRepository;
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;

class DashboardExtension extends AbstractExtension
{

    public function __construct(
        private Environment $twig,
        private ChartBuilderInterface $chartBuilder,
        private QuittancesRepository $quittancesRepository,
        private LocatairesRepository $locatairesRepository,
        private LogsRepository $logsRepository,
        private ProprietairesRepository $proprietairesRepository,
        private PropertiesRepository $propertiesRepository,
        private Security $security
    ) {}

    /**
     * @return TwigFunction[]
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('getCounts', [$this, 'setCounts'], ['is_safe' => ['html']]),
            new TwigFunction('getHomeTabs', [$this, 'setHomeTabs'], ['is_safe' => ['html']]),
            new TwigFunction('statistique_loyers_mensuels', [$this, 'getStatistiqueLoyersMensuels'], ['is_safe' => ['html']]),
            new TwigFunction('total_impayer_locataire', [$this, 'getTotalImpayerLocataire'], ['is_safe' => ['html']]),
            new TwigFunction('total_is_impayer_locataire', [$this, 'getTotalIsImpayerLocataire']),
            new TwigFunction('liste_impayer_locataire', [$this, 'getListeImpayerLocataire'], ['is_safe' => ['html']]),
            new TwigFunction('last_activities', [$this, 'getLastsActivities'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * @return string
     * @throws NoResultException
     * @throws NonUniqueResultException
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function setCounts(): string
    {
        // $datas = [];
        // $datas['totalPayeMois'] = $this->quittancesRepository->getTotalPayer()[0]['total'] ?? 0;
        // $datas['totalImpayeMois'] = $this->quittancesRepository->getTotalPayer(false)[0]['total'] ?? 0;
        // $datas['propertieUsed'] = $this->propertiesRepository->getPropertiesUsed();
        // $datas['locataire'] = $this->locatairesRepository->getCount();
        // $datas['proprietaire'] = $this->proprietairesRepository->getCount();
        // return $this->twig->render('admin/statistiques/_dashboard.html.twig', [
        //     'datas' => $datas,
        // ]);

        $user = $this->security->getUser();

        $isSuperAdmin = in_array('ROLE_SUPER_ADMIN', $user->getRoles(), true);
        $companyId = $user->getCompanyId();

        // On filtre selon le rôle
        $datas = [];
        $datas['totalPayeMois'] = $this->quittancesRepository->getTotalPayer(true, $isSuperAdmin ? null : $companyId)[0]['total'] ?? 0;
        $datas['totalImpayeMois'] = $this->quittancesRepository->getTotalPayer(false, $isSuperAdmin ? null : $companyId)[0]['total'] ?? 0;
        $datas['propertieUsed'] = $this->propertiesRepository->getPropertiesUsed($isSuperAdmin ? null : $companyId);
        $datas['locataire'] = $this->locatairesRepository->getCount($isSuperAdmin ? null : $companyId);
        $datas['proprietaire'] = $this->proprietairesRepository->getCount($isSuperAdmin ? null : $companyId);


        // Nouveau : cumul des commissions
        $properties = $this->propertiesRepository->findByCompany($isSuperAdmin ? null : $companyId); // à adapter si findByCompany existe
        $totalCommissions = 0;
        foreach ($properties as $property) {
            $proprietaire = $property->getProprietaires();
            if ($proprietaire) {
                $commissionRate = $proprietaire->getCommission() ?? 0;
                $totalCommissions += ($property->getMontantLoyer() * $commissionRate / 100);
            }
        }
        $datas['totalCommissions'] = $totalCommissions;

        return $this->twig->render('admin/statistiques/_dashboard.html.twig', [
            'datas' => $datas,
        ]);
    }

    /**
     * @param string $class
     * @return string
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function setHomeTabs(string $class = ''): string
    {

        return $this->twig->render('admin/statistiques/_locataires_appartements.html.twig', [
            'properties' => $this->propertiesRepository->latest(),
            'quittances' => $this->quittancesRepository->latest(),
            'title' => 'Liste des propriétés',
            'class' => $class,
        ]);
    }

    /**
     * @param Locataires $locataire
     * @return float|int|null
     * @throws NoResultException
     * @throws NonUniqueResultException
     */
    public function getTotalIsImpayerLocataire(Locataires $locataire): float|int|null
    {
        $totalImpayer = 0;
        if ($this->quittancesRepository->getTotalImpayer($locataire)) {
            $totalImpayer = $this->quittancesRepository->getTotalImpayer($locataire);
        }
        return $totalImpayer;
    }

    /**
     * @param Locataires $locataire
     * @return string
     * @throws LoaderError
     * @throws NoResultException
     * @throws NonUniqueResultException
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function getTotalImpayerLocataire(Locataires $locataire): string
    {
        $totalImpayer = 0;
        $totalPayer = 0;
        if ($this->quittancesRepository->getTotalImpayer($locataire)) {
            $totalImpayer = $this->quittancesRepository->getTotalImpayer($locataire);
        }
        if ($this->quittancesRepository->getTotalImpayer($locataire, true)) {
            $totalPayer = $this->quittancesRepository->getTotalImpayer($locataire, true);
        }
        return $this->twig->render('admin/acteurs/locataires/_partials/_total_impayer_locataire.html.twig', [
            'totalImpayer' => $totalImpayer,
            'totalPayer' => $totalPayer,
        ]);
    }

    /**
     * @param Locataires $locataire
     * @return string
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function getListeImpayerLocataire(Locataires $locataire, string $class): string
    {
        $quittancesImpayes = $this->quittancesRepository->getListeImpayer($locataire);
        return $this->twig->render('admin/acteurs/locataires/_partials/_liste_impayer_locataire.html.twig', [
            'quittancesImpayes' => $quittancesImpayes,
            'class' => $class,
        ]);
    }

    /**
     * @param string $class
     * @param int|null $limit
     * @return string
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function getLastsActivities(string $class, ?int $limit = 5): string
    {
        $logs = $this->logsRepository->lasts($limit);
        return $this->twig->render('admin/security/logs/partials/_lasts_activities.html.twig', [
            'logs' => $logs,
            'class' => $class,
        ]);
    }

    /**
     * @return string
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
    public function getStatistiqueLoyersMensuels(): string
    {
        $chart = $this->chartBuilder->createChart(Chart::TYPE_BAR);
        $quittances = $this->quittancesRepository->getTotalByMonth();
        $dataQuittances = [];
        $months = [];
        foreach ($quittances as $quittance) {
            $dataQuittances[] = $quittance['total'];
            $monthNum  = $quittance['month'];
            //setlocale(LC_TIME, "fr", "french");
            $dateObj   = DateTime::createFromFormat('!m', "$monthNum");
            $monthName = $dateObj->format('F'); // March
            $months[] = ucfirst(strftime("%B", strtotime($monthName)));
        }

        $maxDataQuittance = null;
        if (!empty($dataQuittances)) {
            $maxDataQuittance = max($dataQuittances);
        }

        $chart->setData([
            'labels' => array_unique(array_values($months)),
            'datasets' => [
                [
                    'label' => 'Loyers mensuelles',
                    'backgroundColor' => 'rgb(199, 105, 50)',
                    'borderColor' => 'rgb(199, 105, 50)',
                    'data' => array_values($dataQuittances),
                ]
            ],
        ]);

        $chart->setOptions([
            'scales' => [
                'yAxes' => [
                    ['ticks' => ['min' => 0, 'max' => intval($maxDataQuittance)]],
                ],
            ],
        ]);

        return $this->twig->render('admin/statistiques/_quittances.html.twig', [
            'chart' => $chart,
        ]);
    }
}
