<?php

namespace Template\Controller;

use League\Plates\Engine;
use Template\Entity\Bond;
use Template\Entity\Brand;
use Template\Entity\Image;
use Template\Entity\Leads;
use Template\Entity\Statu;
use Template\Entity\Config;
use Template\Entity\Record;
use Template\Entity\Filters;
use CoffeeCode\Router\Router;
use CoffeeCode\Uploader\File;
use CoffeeCode\Uploader\Send;
use Template\Entity\Qualidade;
use Template\Entity\Simulator;
use Template\Controller\Records;
use Template\Helper\FlashMessageTrait;
use Doctrine\ORM\EntityManagerInterface;

class Lead 
{
    use FlashMessageTrait;

    private $view;
    private $router;
    private $repository;
    private $repositoryFilter;
    private $repositorySimulator;
    private $repositoryBrand;
    private $repositoryConfig;
    private $repositoryStatus;
    private $repositoryRecord;
    private $repositoryQ;
    private $repositoryBond;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/admin/');
        $this->entityManager = $entityManager;
        $this->repository = $entityManager->getRepository(Leads::class);
        $this->repositoryFilter = $entityManager->getRepository(Filters::class);
        $this->repositorySimulator = $entityManager->getRepository(Simulator::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->repositoryStatus = $entityManager->getRepository(Statu::class);
        $this->repositoryRecord = $entityManager->getRepository(Record::class);
        $this->repositoryQ = $entityManager->getRepository(Qualidade::class);
        $this->repositoryBond = $entityManager->getRepository(Bond::class);
        $this->controller = new Records($entityManager);
        $this->router = new Router(URL_BASE);
    }

    public function index()
    {
        $url = explode('/', $_SERVER["REQUEST_URI"]);
        if (in_array('leads', $url)) {
            $type = '0';
        } elseif (in_array('whatsapps', $url)) {
            $type = '1';
        }

        echo $this->view->render('leads', [
            'leads' => $this->repository->findBy(['type' => $type]),
            'filters' => $this->repositoryFilter->findAll(),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'type' => $type
        ]);
    }

    public function view($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

        echo $this->view->render('lead', [
            'lead' => $this->repository->findOneBy(['id' => $id]),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'status' => $this->repositoryStatus->findAll(),
            'record' => $this->repositoryRecord->findBy(['request' => $id]),
            'motivos' => $this->repositoryQ->findAll(),
            'qualidade' => $this->repositoryBond->findBy(['lead' => $id])
        ]);
    }

    public function persist($data)
    {

        $answers = [];
        foreach ($data['steps'] as $key => $value) {
            $question = $this->repositorySimulator->findOneBy(['id' => $key]);
            if ($value == 'file' && $_FILES["steps"]['size'][$key] > 0) {
                $file = [
                    'name' => $_FILES["steps"]['name'][$key],
                    'type' => $_FILES["steps"]['type'][$key],
                    'tmp_name' => $_FILES["steps"]['tmp_name'][$key],
                    'error' => $_FILES["steps"]['error'][$key],
                    'size' => $_FILES["steps"]['size'][$key]
                ];
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);

                $upload = new Send("file", $ext, [$file['type']], [$ext]);
                $upload = $upload->upload($file, $file['name']);
                
                $answers[] = "{$question->getName()} - <a href='$upload' target='_blank' rel='noopener noreferrer'>Clique para acessar o arquivo</a>";
            } else {
                $answers[] = "{$question->getName()} - $value";
            }
        }
        $responseBefore = $answers;
        $answers = implode(',', $answers);
        $response = $answers;

        $origin = filter_var($data['origin'], FILTER_SANITIZE_STRING);
        $url = filter_var($data['url'], FILTER_SANITIZE_STRING);
        $code = filter_var($data['code'], FILTER_SANITIZE_STRING);
        $campanha = filter_var($data['historico_descricao'] , FILTER_SANITIZE_STRING);
        $config =  $this->repositoryConfig->findOneBy(['id' => 1]);
   
        if(isset($config) && !is_null($config->getIdHelpkim())&& !is_null($config->getTitle())){

            $data['franquia'] = $config->getIdHelpkim();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"https://www.helpkim.com.br/lead/sellerpost");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $seller = curl_exec($ch);
            $seller = json_decode($seller);;
            curl_close($ch);
            
            $questionResps = explode(',', $answers);
            $data['content']=[];
            foreach($responseBefore as $value){
    
                $responseArray = explode(' - ', $value);
                $label = $responseArray[0]; 
                $answer = $responseArray[1];
                if (str_contains(strtolower($label), 'nome')) {
                    $nome = $answer;
                    $_SESSION['name'] = $answer;
                    $hashName = hash('sha256', $nome);
                }
                elseif (str_contains(strtolower($label), 'whatsapp')) {
                    $whatsapp = $answer;
                    $_SESSION['whatsapp'] = $answer;
                    $whatsapphash = preg_replace('/[()\s-]/', '', $answer);
                    $whatsapphash = hash('sha256', $whatsapphash);
                }
                elseif (str_contains(strtolower($label), 'telefone')) {
                    $telefone = $answer;
                    $_SESSION['phone'] = $answer;
                    $hashPhone = preg_replace('/[()\s-]/', '', $answer);
                    $hashPhone = hash('sha256', $hashPhone);
                }
                
                elseif (str_contains(strtolower($label), 'e-mail')) {
                    $email = $answer;
                    $_SESSION['email'] = $answer;
                    $hashEmail = hash('sha256', $email);
                }else{
                    $data['content'][$label] = $answer;
                }
            }
            $data['content'] = array_merge($data['content'], [
                'Nome' => $nome,
                'Origem:' => $origin,
                'Telefone' => $telefone,
                'Whatsapp' => $whatsapp,
                'E-mail' => $email, 
                'campaign' => $campanha
            ]);
            $data['franquia'] = $config->getIdHelpkim();
            $data['page'] = $config->getTitle();
            $data['utm_source'] = $data['utm_source'];
            $data['utm_campaign'] = $data['utm_campaign'];
            $data['utm_medium'] = $data['utm_medium'];
            $data['utm_term'] = $data['utm_term'];
            $data['utm_adGroup'] = $data['utm_adGroup'];
            $data['utm_network'] = $data['utm_network'];
            $data['utm_partner'] = $data['utm_partner'];
            $data['utm_device'] = $data['utm_device'];
            $data['utm_device_model'] = $data['utm_device_model'];
            $data['utm_ads'] = $data['utm_ads'];
            $data['utm_local'] = $data['utm_local'];
            $data['utm_referrer'] = $data['utm_referrer'];
            $data['utm_placement'] = $data['utm_placement'];
            $data['gclid'] = $data['gclid'];
            $data['fbclid'] = $data['fbclid'];
            $data['li_fat_id'] = $data['li_fat_id'];
            $data['ttclid'] = $data['ttclid'];
            $data['msclkid'] = $data['msclkid'];
            $data['twclid'] = $data['twclid'];
            $data['pinterest_ct'] = $data['pinterest_ct'];
            $data['scclid'] = $data['scclid'];
            $data['utm_p1'] = $data['utm_p1'];
            $data['utm_p2'] = $data['utm_p2'];
            $data['utm_p3'] = $data['utm_p3'];

   
            if (isset($seller) && !is_null($seller)) {
                $data['seller'] = $seller->id;
            }
            $mensagem = "<table>";
            foreach($questionResps as $questionResp){
    
                $responseArray = explode(' - ', $questionResp);
                $label = $responseArray[0]; 
                $answer = $responseArray[1];
                $mensagem .= "
                <tr>
                <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
                <strong>$label:</strong> $answer
                </td>
                </tr>";
               
            }
    
           
            if (isset($origin) && $origin == 'Google Ads'){
                $orige = 'Google Ads';
                $data['origin'] = 1;
                $data['code'] = $code;
            } elseif (isset($origin) && $origin == 'Facebook Ads'){
                $orige = 'Facebook Ads';
                $data['origin'] = 3;
                $data['code'] =  $code;
            } else {
                $orige = 'Orgânica';
                $data['origin'] = 2;
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"https://www.helpkim.com.br/lead/create");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
    
            curl_close($ch);
        }

        $headers =  'MIME-Version: 1.0' . "\r\n"; 
        $headers .= "From: {$config->getTitle()} <{$config->getEmail()}>" . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        
        $emailDestiny=$config->getEmail();
        $mensagem .= "
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Campanha:</strong> $campanha
        </td>
        </tr>
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Origin:</strong> $origin
        </td>
        </tr>
        </table>";
   
        try {
            mail("marketing@mazukim.com.br", "Contato do cliente - {$config->getTitle()} ", $mensagem, $headers);
            mail($emailDestiny, "Contato do cliente - {$config->getTitle()} ", $mensagem, $headers);
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "{$th->getMessage()}");
            echo "<script>history.go(-1);</script>";
        }
        
        $leads = new Leads();
        $leads->setAnswers($answers);
        $leads->setOrigin($origin);
        $leads->setCode($code);
        $leads->setUrl($url);
            $leads->setCampaign($campanha);
        $leads->setStatus(0);
        $leads->setType(0);
        $leads->setDate();

        try {
            $this->entityManager->persist($leads);
            $this->entityManager->flush();
            if ($origin == 'Google Ads') {
                $this->controller->excel();
            }
            $this->router->redirect("/thank-you");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Ops aconteceu algo errado. Erro: {$th->getMessage()}");
            $this->router->redirect("/");
        }
    
  
      

        
     
    }

    public function whatsapp($data)
    {

        $answers = [];
        $name = filter_var($data['name'], FILTER_SANITIZE_STRING);
        $answers[] = "Nome: - $name";
        $email = filter_var($data['email'], FILTER_SANITIZE_STRING);
        $answers[] = "E-mail: - $email";
        $telefone = filter_var($data['whatsapp'], FILTER_SANITIZE_STRING);
        $answers[] = "Telefone: - $telefone";
        $mensagem = filter_var($data['mensagem'], FILTER_SANITIZE_STRING);
        $answers[] = "Mensagem: - $mensagem";
        $answers = implode(',', $answers);

        $origin = filter_var($data['origin'], FILTER_SANITIZE_STRING);
        $url = filter_var($data['url'], FILTER_SANITIZE_STRING);
        $code = filter_var($data['code'], FILTER_SANITIZE_STRING);
        $campanha = filter_var($data['historico_descricao'] , FILTER_SANITIZE_STRING);

        $config =  $this->repositoryConfig->findOneBy(['id' => 1]);

        if(isset($config) && !is_null($config->getIdHelpkim())&& !is_null($config->getTitle())){

            $data['franquia'] = $config->getIdHelpkim();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"https://www.helpkim.com.br/lead/sellerpost");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $seller = curl_exec($ch);
            $seller = json_decode($seller);;
            curl_close($ch);
        

            $data = [
                'content' => [
                    'Nome' => $name,
                    'Origem:' => $origin,
                    'Telefone' => $telefone,
                    'E-mail' => $email
                ],
                'franquia' => $config->getIdHelpkim(),
                'page' => $config->getTitle(), 
                'campaign' => $campanha,
                'utm_source' => $data['utm_source'],
                'utm_campaign' => $data['utm_campaign'],
                'utm_medium' => $data['utm_medium'],
                'utm_term' => $data['utm_term'],
                'utm_adGroup' => $data['utm_adGroup'],
                'utm_network' => $data['utm_network'],
                'utm_partner' => $data['utm_partner'],
                'utm_device' => $data['utm_device'],
                'utm_device_model' => $data['utm_device_model'],
                'utm_ads' => $data['utm_ads'],
                'utm_local' => $data['utm_local'],
                'utm_referrer' => $data['utm_referrer'],
                'utm_placement' => $data['utm_placement'],
                'gclid' => $data['gclid'],
                'fbclid' => $data['fbclid'],
                'li_fat_id' => $data['li_fat_id'],
                'ttclid' => $data['ttclid'],
                'msclkid' => $data['msclkid'],
                'twclid' => $data['twclid'],
                'pinterest_ct' => $data['pinterest_ct'],
                'scclid' => $data['scclid'],
                'utm_p1' => $data['utm_p1'],
                'utm_p2' => $data['utm_p2'],
                'utm_p3' => $data['utm_p3']

            ];
            if (isset($seller) && !is_null($seller)) {
                $data['seller'] = $seller->id;
            }

        
            if (isset($origin) && $origin == 'Google Ads'){
                $orige = 'Google Ads';
                $data['origin'] = 1;
                $data['code'] = $code;
            } elseif (isset($origin) && $origin == 'Facebook Ads'){
                $orige = 'Facebook Ads';
                $data['origin'] = 3;
                $data['code'] =  $code;
            } else {
                $orige = 'Orgânica';
                $data['origin'] = 2;
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL,"https://www.helpkim.com.br/lead/create");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);

            curl_close($ch);
        }
        
        $emailDestiny= $config->getEmail();
        $headers =  'MIME-Version: 1.0' . "\r\n"; 
        $headers .= "From: {$config->getTitle()} <{$config->getEmail()}>" . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        
        $mensagem = "<table>";
        
      

        $mensagem .= "
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Nome :</strong> $name
        </td>
        </tr>
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong> Email :</strong> $email
        </td>
        </tr>
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Telefone :</strong> $telefone
        </td>
        </tr>";



        $mensagem .= "
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Campanha:</strong> $campanha
        </td>
        </tr>
        <tr>
        <td  align='center' style='border-bottom:1px solid #DDDDDD;'>
        <strong>Origin:</strong> $origin
        </td>
        </tr>
        </table>";
        
    
            try {
                mail("marketing@mazukim.com.br", "Contato do cliente - {$config->getTitle()} ", $mensagem, $headers);
                mail($emailDestiny, "Contato do cliente - {$config->getTitle()} ", $mensagem, $headers);
            } catch (\Throwable $th) {
                $this->defineMensagem('error', "{$th->getMessage()}");
                echo "<script>history.go(-1);</script>";
            }
            
            $leads = new Leads();
            $leads->setAnswers($answers);
            $leads->setOrigin($origin);
            $leads->setCode($code);
            $leads->setUrl($url);
            $leads->setCampaign($campanha);
            $leads->setStatus(0);
            $leads->setType(1);
            $leads->setDate();

            $config = $this->repositoryConfig->findOneBy(['id' => 1]);
            $phone = '55' . preg_replace('/[^\d]/i', '', $config->getWhatsapp());
            $message = "Olá, tudo bem? \nMeu nome é $name e gostaria de mais Informações";

            // Não editar o codigo abaixo
            $message = urlencode($message);
            $message = str_replace('+','%20',$message);
            $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
            $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
            $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
            $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
            $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

            try {
                $this->entityManager->persist($leads);
                $this->entityManager->flush();
                if ($origin == 'Google Ads') {
                    $this->controller->excel();
                }
                // Verifica se é um celular
                if ($iphone || $android || $palmpre || $ipod || $berry == true){
                    header("location: whatsapp://send?phone=$phone&text=$message");
                    echo "<script>window.location='whatsapp://send?phone='.$phone.'&text='.$message</script>";
                }
                header("location: https://web.whatsapp.com/send?phone=$phone&text=$message");
                echo "<script>window.location='https://web.whatsapp.com/send?phone='.$phone.'&text='.$message</script>";
            } catch (\Throwable $th) {
                $this->defineMensagem('error', "Ops aconteceu algo errado. Erro: {$th->getMessage()}");
                $this->router->redirect("/");
            }
        
   
    }

    public function filter($data)
    {
        $name = filter_var($data['name'], FILTER_SANITIZE_STRING);
        
        $filters = new Filters();
        $filters->setName($name);
        $filters->setActive(0);

        $this->entityManager->persist($filters);
        $this->entityManager->flush();

        $filters = $this->repositoryFilter->findAll();
        foreach ($filters as $key => $item) {
            echo "
            <p>
                <strong>
                    <input id='check-$key' name='filter[]' type='checkbox' ";
                    echo ($item->getActive() == 1) ? ' checked ' : '';
                    echo " value='{$item->getId()}' />
                    <label for='check-$key'>{$item->getName()}</label>
                </strong>
                <a href='{$item->getId()}' class='remove'><span class='far fa-trash-alt'></span></a>
            </p>
            ";
        }
    }

    public function change($data)
    {
        foreach ($data['all'] as $value) {
            $qb = $this->entityManager->createQueryBuilder();
            $q = $qb->update('Template\Entity\Filters', 'f')
            ->set('f.active', $qb->expr()->literal((in_array($value, $data['filter'])) ? 1 : 0))
            ->where('f.id = ?1')
            ->setParameter(1, $value)
            ->getQuery();
            $q->execute();
        }
    }

    public function qualidade($data)
    {

        if(!isset($data['type'])):
            $this->defineMensagem('error', "Você não escolheu nenhuma opção de Qualidade de Lead.");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        endif;

        $lead = filter_var($data['lead'], FILTER_VALIDATE_INT);
        $type = filter_var($data['type'], FILTER_VALIDATE_INT);
        $motivos1 = filter_var($data['motivos1'], FILTER_VALIDATE_INT);
        $motivos2 = filter_var($data['motivos2'], FILTER_VALIDATE_INT);

        $bond = new Bond();
        $bond->setLead($lead);
        $bond->setType($type);
        $bond->setQualidade(($type == 0) ? $motivos1 : $motivos2);
        $bond->setDate();

        try {
            $this->entityManager->persist($bond);
            $this->entityManager->flush();
            $this->defineMensagem('success', "Lead Qualificado com Sucesso");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel criar o motivo. Erro: {$th->getMessage()}");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        }
    }

    public function delete($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

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

    public function remove($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

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

}
