<?php

namespace Template\Controller;

use League\Plates\Engine;
use Template\Entity\Brand;
use Template\Entity\Service;
use Doctrine\ORM\EntityManagerInterface;
use Template\Entity\Banner;
use Template\Entity\Company;
use Template\Entity\Config;
use Template\Entity\Google;
use Template\Entity\Image;
use Template\Entity\Questions;
use Template\Entity\Simulator;
use Template\Entity\Social;
use Template\Entity\Testimony;
use Template\Entity\User;
use Template\Helper\FlashMessageTrait;

class Web 
{

    use FlashMessageTrait;

    private $view;
    private $entityManager;
    private $repositorySimulator;
    private $repositorioCompany;
    private $repositoryBanner;
    private $repositorioService;
    private $repositorioImage;
    private $repositoryBrand;
    private $repositoryTestimony;
    private $repositorySocial;
    private $repositoryQuestion;
    private $repositoryConfig;
    private $repositoryUser;
    private $repositoryAnalitycs;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/site/');
        $this->entityManager = $entityManager;
        $this->repositorioSimulator = $entityManager->getRepository(Simulator::class);
        $this->repositorioCompany = $entityManager->getRepository(Company::class);
        $this->repositorioBanner = $entityManager->getRepository(Banner::class);
        $this->repositorioService = $entityManager->getRepository(Service::class);
        $this->repositorioImage = $entityManager->getRepository(Image::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryTestimony = $entityManager->getRepository(Testimony::class);
        $this->repositorySocial = $entityManager->getRepository(Social::class);
        $this->repositoryQuestion = $entityManager->getRepository(Questions::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->repositoryUser = $entityManager->getRepository(User::class);
        $this->repositoryAnalitycs = $entityManager->getRepository(Google::class);
    }

    public function index()
    {
        $query_select = "SELECT s FROM Template\Entity\Simulator s ORDER BY s.position ASC";
        $query = $this->entityManager
        ->createQuery($query_select);

        $galery_select = "SELECT i FROM Template\Entity\Image i ORDER BY i.position ASC";
        $galery = $this->entityManager
        ->createQuery($galery_select);

        echo $this->view->render('index', [
            'simulator' => $query->getResult(),
            'galery' => $galery->getResult(),
            'service' => $this->repositorioService->findAll(),
            'testimony' => $this->repositoryTestimony->findAll(),
            'questions' => $this->repositoryQuestion->findAll(),
            'social' => $this->repositorySocial->findOneBy(['id' => 1]),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'company' => $this->repositorioCompany->findOneBy(['id' => 1]),
            'banner' => $this->repositorioBanner->findOneBy(['id' => 1]),
            'google' => $this->repositoryAnalitycs->findOneBy(['id' => 1])
        ]);
    }

    public function final()
    {
        echo $this->view->render('thank-you', [
            'social' => $this->repositorySocial->findOneBy(['id' => 1]),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'banner' => $this->repositorioBanner->findOneBy(['id' => 1]),
            'google' => $this->repositoryAnalitycs->findOneBy(['id' => 1])
        ]);
    }

    public function whatsapp()
    {
        $config = $this->repositoryConfig->findOneBy(['id' => 1]);
        $phone = '55' . preg_replace('/[^\d]/i', '', $config->getWhatsapp());
        $message = 'Olá, Tudo bem? Gostaria de saber mais informações sobre os seus serviços!';

        // 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");

        // 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>";
    }

    public function start()
    {
        $this->view = new Engine(__DIR__ . '/../../config/');
        echo $this->view->render('install', [
            'reset' => true
        ]);
    }

    public function drop($data)
    {
        $user = filter_var(
            $data['user'],
            FILTER_SANITIZE_STRING
        );
        
        $password = filter_var(
            $data['password'],
            FILTER_SANITIZE_STRING
        );
        
        /** @var User $user */
        $user = $this->repositoryUser->findOneBy(['user' => $user]);
        
        if (is_null($user) || !$user->verify_password($password)) {
            echo 'Usuário ou senha inválidos';
            return false;
        }
        function delTree($dir) { 
            $files = array_diff(scandir($dir), array('.','..')); 
            foreach ($files as $file) { 
                (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
            } 
            return rmdir($dir); 
        }
    
        delTree(__DIR__ . '/../../public/admin/images/images/');

        $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null);

        $this->entityManager->getConnection()->prepare("SET FOREIGN_KEY_CHECKS = 0;")->execute();

        foreach ($this->entityManager->getConnection()->getSchemaManager()->listTableNames() as $tableNames) {
                $sql = 'DROP TABLE ' . $tableNames;
                $this->entityManager->getConnection()->prepare($sql)->execute();
        }
        $this->entityManager->getConnection()->prepare("SET FOREIGN_KEY_CHECKS = 1;")->execute();
    }
}
