<?php

namespace App\Controller;

use App\Entity\Flux;
use App\Entity\Prestataire;
use App\Entity\SolidoumeItem;
use App\Entity\SolidoumeParameter;
use App\Form\Type\SolidoumeParameterFormType;
use App\Utils\CustomEntityManager;
use DateTime;
use Ramsey\Uuid\Uuid;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Security;

class SolidoumeParameterController extends CRUDController
{
    protected $em;
    protected $security;

    public function __construct(CustomEntityManager $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    public function redistributionAction(Request $request): Response
    {
        $datas = [];
        $next = [];
        $solidoumeParam = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();

        $redistributions = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), null, 'prestataire_adherent')->getResult();
        $prelevements = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), null, 'adherent_prestataire')->getResult();
        foreach ($redistributions as $redistribution) {
            $datas[$redistribution->getCreatedAt()->format('d/m/Y')]['redis'][] = $redistribution;
        }
        ksort($datas);
        $lastRedist = array_key_last($datas);
        $lastRedistDate = DateTime::createFromFormat('d/m/Y', $lastRedist);
        $nextRedis = clone $lastRedistDate;
        $nextRedis = $nextRedis->modify('+1 month');
        $nextRedis = $nextRedis->format('d/m/Y');
        $nextRedis = $solidoumeParam->getExecutionDate().substr($nextRedis,2,strlen($nextRedis)-2);
        $datas[$nextRedis]['redis'] = [];
        $datas[$nextRedis]['prelev'] = [];
        foreach($prelevements as $prelevement) {
            foreach($datas as $key => $data) {
                $dateEnd = DateTime::createFromFormat('d/m/Y', $key);
                $dateStart = clone $dateEnd;
                $dateStart = $dateStart->modify('-1 month');
                if ($prelevement->getCreatedAt() > $dateStart && $prelevement->getCreatedAt() <= $dateEnd) {
                    $datas[$key]['prelev'][] = $prelevement;
                }
            }
        }
        $solidoumeItems = $this->em->getRepository(SolidoumeItem::class)->findBy([]);

        foreach ($datas as $key => $data) {
            $datas[$key]['adherent'] = [];
            $nbdonateur = 0;
            $totalperperson = 0;
            $totalAmountDon = 0;
            $totalAmountPrel = 0;
            $totalAmount = 0;
            $totalMissed = 0;
            foreach($data['prelev'] as $prelev) {
                $datas[$key]['adherent'][$prelev->getExpediteur()->__toString()]['prelevement'] = $prelev;
                $datas[$key]['adherent'][$prelev->getExpediteur()->__toString()]['don'] = false;
                $totalAmount += $prelev->getMontant();
                $totalAmountPrel += $prelev->getMontant();
            }
            foreach ($datas[$key]['prelev'] as $prelevement) {
                $isdon = true;
                foreach ($datas[$key]['redis'] as $redistribution) {
                    $datas[$key]['adherent'][$redistribution->getDestinataire()->__toString()]['redistribution'] = $redistribution;
                    $datas[$key]['adherent'][$redistribution->getDestinataire()->__toString()]['don'] = false;
                    $totalperperson = $redistribution->getMontant();
                    if ($prelevement->getExpediteur() == $redistribution->getDestinataire()) {
                        $isdon = false;
                    }
                }
                if ($isdon) {
                    $donFound = false;
                    $prelevementData = $prelevement->getData();
                    if ($prelevementData != null && isset($prelevementData['item'])) {
                        if (isset($prelevementData['item']['don']) && $prelevementData['item']['don'] == true) {
                            $datas[$key]['adherent'][$prelevement->getExpediteur()->__toString()]['don'] = true;
                            $donFound = true;
                            $data[$key]['dons'][] = $prelevement;
                            $totalAmountDon += $prelevement->getMontant();
                            $nbdonateur++;
                        } 
                    } else {
                        foreach ($solidoumeItems as $item) {
                            if ($item->getAdherent() == $prelevement->getExpediteur()) {
                                if ($item->getIsDonation()) {
                                    $datas[$key]['adherent'][$prelevement->getExpediteur()->__toString()]['don'] = true;
                                    $donFound = true;
                                    $data[$key]['dons'][] = $prelevement;
                                    $totalAmountDon += $prelevement->getMontant();
                                    $nbdonateur++;
                                }
                            }
                        }
                    }
                    if (!$donFound) {
                        $data[$key]['missed'][] = $prelevement;
                        $totalMissed += $prelevement->getMontant();
                    }
                }
            }
            foreach ($solidoumeItems as $item) {
                if (isset($datas[$key]['adherent'][$item->getAdherent()->__toString()])) {
                    $datas[$key]['adherent'][$item->getAdherent()->__toString()]['item'] = $item;
                }
            }
            ksort($datas[$key]['adherent']);
            $nbperson = count($data['redis']);
            //round((($totalAmount / $nbperson) * ((100 - $solidoumeParam->getCommission()) / 100)), 2, PHP_ROUND_HALF_DOWN);
            $amountcommission = $totalAmount/100*5;
            $datas[$key]['date'] = $key;
            $datas[$key]['totalAmount'] = $totalAmount;
            $datas[$key]['totalAmountDon'] = $totalAmountDon;
            $datas[$key]['totalAmountPrel'] = $totalAmountPrel;
            $datas[$key]['totalMissed'] = $totalMissed;
            $datas[$key]['nbmissed'] = count($data[$key]['missed']);
            $datas[$key]['nbperson'] = $nbperson;
            $datas[$key]['nbdonateur'] = $nbdonateur;
            $datas[$key]['totalperperson'] = $totalperperson;
            $datas[$key]['commission'] = $solidoumeParam->getCommission();
            $datas[$key]['amountcommission'] = $amountcommission;
        }
        krsort($datas);
        $firstKey = array_key_first($datas);
        $nextRedis = $datas[$firstKey];
        $datas['_next'] = $nextRedis;
        unset($datas[$firstKey]);
        krsort($datas);

        return $this->renderWithExtraParams('@kohinos/admin/solidoume_redistribution.html.twig', [
            'datas' => $datas
        ]);
    }

    /**
     * List action.
     *
     * @throws AccessDeniedException If access is not granted
     *
     * @return Response
     */
    public function listAction()
    {
        $request = $this->getRequest();

        $data = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();
        $oldData = null;
        if (!empty($data)) {
            $oldData = clone $data;
        }
        $form = $this->createForm(SolidoumeParameterFormType::class, $data);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (null != $oldData) {
                $oldData->setEnabled(false);
                $this->em->persist($oldData);
                $this->em->flush();
            }
            $solidoumeParameter = $form->getData();
            $solidoumeParameter->setId(Uuid::uuid4());
            $solidoumeParameter->setEnabled(true);
            $this->em->persist($solidoumeParameter);
            $this->em->flush();

            $this->addFlash(
                'sonata_flash_success',
                'Paramètres de la sécurite sociale alimentaire bien validés !'
            );

            return $this->redirectToRoute('solidoume_list');
        }

        $template = $this->admin->getTemplate('list');

        return $this->renderWithExtraParams($template, [
            'action' => 'list',
            'form' => $form->createView(),
        ], null);
    }
}
