<?php

namespace Template\Controller;

use League\Plates\Engine;
use Template\Entity\Leads;
use Template\Entity\Config;
use Template\Entity\Record;
use CoffeeCode\Router\Router;
use Template\Helper\FlashMessageTrait;
use Doctrine\ORM\EntityManagerInterface;
use Exception;

class Records 
{
    use FlashMessageTrait;
    
    private $view;
    private $router;
    private $curl;
    private $token;
    private $entityManager;
    private $repository;
    private $repositoryLead;
    private $repositoryConfig;
    private $status;
    
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/admin/');
        $this->router = new Router(URL_BASE);
        $this->entityManager = $entityManager;
        $this->repository = $entityManager->getRepository(Record::class);
        $this->repositoryLead = $entityManager->getRepository(Leads::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
    }

    public function persist($data)
    { 

        $order = filter_var($data['order'], FILTER_VALIDATE_INT);
        $status = filter_var($data['status'], FILTER_VALIDATE_INT);
        $note = filter_var($data['note'], FILTER_SANITIZE_STRING);
        $repository = $this->repository;
        $repository = $repository->findOneBy(['request' => $order]);



        if(isset($repository) and $order == $repository->getRequest()):        
                


                if(!isset($data['sector']) and !isset($data['transfer'])):
                    $this->defineMensagem('error', "Opção Padrão. Escolha outra opção.");
                    $this->router->redirect("$_SERVER[HTTP_REFERER]");
                endif;
            

                if(!isset($data['transfer']) && empty($note)):
                    $this->defineMensagem('error', "Falta dados. Provavelmente você está esquecendo de escrever a nota.");
                    $this->router->redirect("$_SERVER[HTTP_REFERER]");
                endif;




        endif;
        
        
        

        if (isset($data['transfer']) && $data['transfer'] == 1):
            $transfer = filter_var($data['transfer'], FILTER_VALIDATE_INT);
            $sector = filter_var($data['sector'], FILTER_VALIDATE_INT);
            
            if (isset($data['price']) && $sector == 1):
                $price = filter_var($data['price'], FILTER_SANITIZE_STRING);
                $qb = $this->entityManager->createQueryBuilder();
                $q = $qb->update('Template\Entity\Leads', 'l')
                ->set('l.price', $qb->expr()->literal($price))
                ->where('l.id = ?1')
                ->setParameter(1, $order)
                ->getQuery();
                $q->execute();
            endif;

        endif;

        $record = new Record();
        $record->setRequest($order);
        $record->setCurrentSector($status);
        $record->setNote($note);
        $record->setUser(0);
        $record->setDate();
        
        if (isset($transfer)){
            $record->setTransferredSector($sector);
            $qb = $this->entityManager->createQueryBuilder();
            $q = $qb->update('Template\Entity\Leads', 'l')
            ->set('l.status', $qb->expr()->literal($sector))
            ->where('l.id = ?1')
            ->setParameter(1, $order)
            ->getQuery();
            $q->execute();
            if ($sector == 1) {
                $this->excel();
            }
        }

        try {
            $this->entityManager->persist($record);
            $this->entityManager->flush();
        
                if(intval($data['sector']) == 0):
                    $this->defineMensagem('error', "Valor padrão, use outro.");
                endif;

                if(intval($data['sector']) <= 2):
                    $this->defineMensagem('success', "Registro criado com sucesso.");
                endif;

                if(intval($data['sector']) > 2):
                    $this->defineMensagem('success', "Um dos dados inseridos pelo usuário foi aplicado com sucesso.");
                endif;

                $this->router->redirect("$_SERVER[HTTP_REFERER]");
        
            } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel criar o registro. Erro: {$th->getMessage()}");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        }
    }

    public function excel()
    {

        $leads = $this->repositoryLead->findAll();
        $records = $this->repository->findAll();
        $config = $this->repositoryConfig->findOneBy(['id' => 1]);
 
	    if (!empty($leads)) {
			
			// Gera arquivo CSV
			$fp = fopen("planilha.csv", "w"); // o "a" indica que o arquivo será sobrescrito sempre que esta função for executada.
			fputcsv($fp, ["Parameters:TimeZone=America/Sao_Paulo;","","","",""]);

            // Criar o cabeçalho
            fputcsv($fp , ["Google Click ID","Conversion Name","Conversion Time","Conversion Value","Conversion Currency", "Pagina de Conversão"]);
			
			foreach($leads as $registro) 
			{ 	
                $date = new \DateTime(date('Y-m-d') . '00:00:00');
                $date = $date->format('Y-m-d H:i:s');
                $record = array_filter($records, function ($elem){
                    return $elem->getCurrentSector() != 2;
                });
                $venda = array_filter($records, function ($elem){
                    return $elem->getCurrentSector() == 1;
                });
                if ($registro->getDate()->format('Y-m-d H:i:s') >= $date && empty($record) || $registro->getDate()->format('Y-m-d H:i:s') >= $date && !empty($record)) {
                    $price = (is_null($registro->getPrice())) ? "1.00"  : number_format(floatval($registro->getPrice()), 2, '.', ',');
                    fputcsv($fp, [
                        "{$registro->getCode()}",
                        "form",
                        "{$registro->getDate()->format('m/d/Y H:i')}",
                        "{$price}",
                        "BRL",
                        "{$config->getTitle()}",
                    ]);
                }  			
            }

            fclose($fp);
            
        }
		
    }

    public function reset()
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->select('l')->from('Template\Entity\Leads', 'l');
        $qb->add('orderBy', 'l.id DESC');
        $qb->andWhere("l.status = 1");
        $dateInicial = date('Y-m-d');
        $dateInicial = new \DateTime($dateInicial . '23:59:59');
        $dateInicial = $dateInicial->format('Y-m-d H:i:s');
        $qb->andWhere("l.date <= '$dateInicial'");
        $query = $qb->getQuery();
        $lead = $query->getResult();

        foreach ($lead as $value) {
            
            $record = new Record();
            $record->setRequest($value->getId());
            $record->setCurrentSector(2);
            $record->setNote('');
            $record->setUser(0);
            $record->setDate();
            $this->entityManager->persist($record);

            $qb = $this->entityManager->createQueryBuilder();
            $q = $qb->update('Template\Entity\Leads', 'l')
            ->set('l.status', 2)
            ->where('l.id = ?1')
            ->setParameter(1, $value->getId())
            ->getQuery();
            $q->execute();
        }

        $this->entityManager->flush();

        unlink(URL_BASE . 'planilha.csv');
    }
    
    public function delete($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

        $record = $this->repository->findOneBy(['id' => $id]);
        $this->entityManager->remove($record);
        $this->entityManager->flush();
    }
}