<?php

/**
 * AdminConfig.class [_MODELS ADMIN]
 * Responsável por gerenciar os confs no admin do sistema!
 * 
 * @copyright (c) year, Welton Thierree TagPage
 */
class AdminConfig {

    private $Data;
    private $ConfId;
    private $Error;
    private $Result;

    //Nome da tabela no banco de dados
    const Entidy = 'tp_configuracao';

    public function ExeCreate(array $Data) {
        $this->Data = $Data;

        if (in_array('', $this->Data)):
            $this->Error = ["Erro ao cadastrar: Para cadastrar um conf, favor preencha os campos obrigatórios!", WS_ALERT];
            $this->Result = false;
        else:
            $this->setData();
            $this->setName();

            if (isset($this->Data['conf_img']['tmp_name'])):
                $upload = new Upload;
                $upload->Image($this->Data['conf_img'], $this->Data['conf_nome']);
            endif;

            if (isset($upload) && $upload->getResult()):
                $this->Data['conf_img'] = $upload->getResult();
                $this->Create();
            else:
                $this->Data['conf_img'] = null;
                $this->Create();
            endif;
        endif;
    }

    public function ExeUpdate($ConfigId, array $Data) {
        $this->ConfId = (int) $ConfigId;
        $this->Data = $Data;

        if (in_array('', $this->Data)):
            $this->Error = ["Para atualizar as configurações, preencha todos os campos", WS_ALERT];
            $this->Result = false;
        elseif (!Check::Email($this->Data['config_email']) || !filter_var($this->Data['config_email'], FILTER_VALIDATE_EMAIL)):
            $this->Result = false;
            $this->Error = ['<b>Erro ao atualizar</b> informe um e-mail válido', WS_ALERT];
        else:
            //$this->setData();

//            if (is_array($this->Data['config_logo'])):
//                $readCapa = new Read;
//                $readCapa->ExeRead(self::Entidy, "WHERE config_id = :id", "id={$this->ConfId}");
//                $capa = '../uploads/' . $readCapa->getResult()[0]['config_logo'];
//
//                if (file_exists($capa) && !is_dir($capa)):
//                    unlink($capa);
//                endif;
//
//                $uploadCapa = new Upload;
//                $uploadCapa->Image($this->Data['conf_img'], $this->Data['conf_titulo']);
//            endif;
//
//            if (isset($uploadCapa) && $uploadCapa->getResult()):
//                $this->Data['conf_logo'] = $uploadCapa->getResult();
//                $this->Update();
//            else:
//                unset($this->Data['conf_logo']);
                $this->Update();
            //endif;

        endif;
    }

    public function ExeDelete($ConfigId) {
        $this->ConfId = (int) $ConfigId;
        $ReadConfig = new Read;
        $ReadConfig->ExeRead(self::Entidy, "WHERE conf_id = :id", "id={$this->ConfId}");

        if (!$ReadConfig->getResult()):
            $this->Error = ["O conf que você tentou deletar não existe no sistema!", WS_ERROR];
            $this->Result = false;
        else:
            $ConfigDelete = $ReadConfig->getResult()[0];
            if (file_exists('../uploads/' . $ConfigDelete['conf_img']) && !is_dir('../uploads/' . $ConfigDelete['conf_img'])):
                unlink('../uploads/' . $ConfigDelete['conf_img']);
            endif;

            $readGallery = new Read;
            $readGallery->ExeRead("tp_conf_images", "WHERE conf_id = :id", "id={$this->ConfId}");
            if ($readGallery->getResult()):
                foreach ($readGallery->getResult() as $gbdel):
                    if (file_exists('../uploads/' . $gbdel['conf_img']) && !is_dir('../uploads/' . $gbdel['conf_img'])):
                        unlink('../uploads/' . $gbdel['conf_img']);
                    endif;
                endforeach;
            endif;

            $deleta = new Delete;
            $deleta->ExeDelete("tp_conf_images", "WHERE conf_id = :gbconf", "gbconf={$this->ConfId}");
            $deleta->ExeDelete(self::Entidy, "WHERE conf_id = :confid", "confid={$this->ConfId}");

            $this->Error = ["O conf <b>{$ConfigDelete['conf_titulo']}</b> foi removido do sistema!", WS_ACCEPT];
        endif;
    }

    public function ExeStatus($ConfigId, $ConfigStatus) {
        $this->ConfId = (int) $ConfigId;
        $this->Data['conf_status'] = (string) $ConfigStatus;

        $Update = new Update;
        $Update->ExeUpdate(self::Entidy, $this->Data, "WHERE conf_id = :id", "id={$this->ConfId}");
    }

    function getResult() {
        return $this->Result;
    }

    function getError() {
        return $this->Error;
    }

    //PRIVATE
    private function setData() {
        $Cover = $this->Data['conf_img'];
        $Content = $this->Data['conf_descricao'];
        $Departamento = $this->Data['conf_departamento_id'];
        unset($this->Data['conf_img'], $this->Data['conf_descricao'], $this->Data['conf_departamento_id']);

        $this->Data = array_map('strip_tags', $this->Data);
        $this->Data = array_map('trim', $this->Data);

        $this->Data['conf_nome'] = Check::Name($this->Data['conf_titulo']);
        $this->Data['conf_img'] = $Cover;
        $this->Data['conf_descricao'] = $Content;
    }


    private function Create() {
        $cadastra = new Create;
        $cadastra->ExeCreate(self::Entidy, $this->Data);
        if ($cadastra->getResult()):
            $this->Error = ["O conf <b>{$this->Data['config_tag_title']}</b> foi cadastrado com sucesso no sistema!", WS_ACCEPT];
            $this->Result = $cadastra->getResult();
        endif;
    }

    private function Update() {
        $Update = new Update;
        $Update->ExeUpdate(self::Entidy, $this->Data, "WHERE config_id = :id", "id={$this->ConfId}");
        if ($Update->getResult()):
            $this->Error = ["O conf <b>{$this->Data['config_tag_title']}</b> foi atualizado com sucesso no sistema!", WS_ACCEPT];
            $this->Result = true;
        endif;
    }

}
