<?php

namespace App\Controller;

use App\Entity\Chimp;
use App\Repository\ChimpRepository;

use DrewM\MailChimp\MailChimp;
use Exception;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ChimpController extends AbstractController
{
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var ChimpRepository
     */
    private $chimpRep;

    /**
     * @var array
     */
    private $listCampaigns;

    /**
     * @var array
     */
    private $dataCampaigns;

    /**
     * @var MailChimp
     */
    private $MailChimp;


    /**
     * @throws Exception
     */
    public function __construct(ChimpRepository $chimpRep, EntityManagerInterface $em){
        $this->em=$em;
        $this->chimpRep=$chimpRep;
        $this->MailChimp = new MailChimp('bf9fc6277705b92d1253c1fe9106cc94-us6');
    }



    /**
     * @Route("/chimp", name="chimp")
     */
    public function index(): Response
    {
        return $this->render('chimp/index.html.twig', [
            'controller_name' => 'ChimpController',
        ]);
    }

    /**
     * @throws NonUniqueResultException
     * @throws Exception
     */
    public function updateDataChimp(): void {

        $idx=0;

        $listCampaigns = $this->MailChimp->get('campaigns');

        foreach ($listCampaigns as $campaign) {

            if (is_array($campaign))
            {
                foreach ($campaign as $info) {

                    if (isset($info["id"])) {

                        [
                            "id"                => $id,
                            "status"            => $status,
                            "emails_sent"       => $emailSent,
                            "send_time"         => $sendTime,
                            "settings"          => $settings
                        ]= $info;

                        if ($status === "sent")
                        {
                            $sendDateTime = new \DateTimeImmutable($sendTime);
                            $sentDates= explode('T', $sendTime);
                            $subject= $settings["subject_line"];
                            $clicks=0;
                            $opens =0;
                            if (isset($info["report_summary"]))
                            {
                                [
                                    "clicks"        => $clicks,
                                    "opens"         => $opens,
                                    "open_rate"     => $openRate,
                                    "click_rate"    => $clickRate
                                ]= $info["report_summary"];
                            }
                            $chimp=$this->chimpRep->findOneBySomeField("chimp_Id",$id);
                            if (!$chimp)
                                $chimp = new Chimp();

                            $chimp  ->setChimpId($id)
                                    ->setEmailsSent($emailSent)
                                    ->setSendAt($sendDateTime)
                                    ->setSubject($subject)
                                    ->setOpens($opens)
                                    ->setClicks($clicks)
                                    ->setClickRate($clickRate*100/$openRate)
                                    ->setOpenRate($openRate*100)
                                    ->setType('FP');
                            $campaign=[];
                            $campaign['emailSent']=$emailSent;
                            $campaign['sentAt']=date_format(date_create($sentDates[0]),"j F Y");;
                            $campaign['subject']=$subject;
                            $campaign['opens']=$opens;
                            $campaign['click']=$clicks;
                            $campaign['datetime']=strtotime(date($sentDates[0]));
                            $this->dataCampaigns[]=$campaign;
                            $this->em->persist($chimp);
                        }


                    }


                }
            }



        }
        $this->em->flush();
    }
}
