<?php

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

    private $Data;
    private $Id;
    private $Error;
    private $Result;

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

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

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

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

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

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

        if (in_array('', $this->Data)):
            $this->Error = ["Para atualizar este cliente, preencha todos os campos (Capa não precisa ser enviada)", WS_ALERT];
            $this->Result = false;
        else:
            $this->setData();
            $this->setName();

            if (is_array($this->Data['image'])):
                $readCapa = new Read;
                $readCapa->ExeRead(self::Entidy, "WHERE cliente_id = :cliente", "cliente={$this->Id}");
                $capa = '../uploads/' . $readCapa->getResult()[0]['image'];

                if (file_exists($capa) && !is_dir($capa)):
                    unlink($capa);
                endif;

                $uploadCapa = new Upload;
                $uploadCapa->Image($this->Data['image'], $this->Data['cliente_nome']);
            endif;

            if (isset($uploadCapa) && $uploadCapa->getResult()):
                $this->Data['image'] = $uploadCapa->getResult();
                $this->Update();
            else:
                unset($this->Data['image']);
                $this->Update();
            endif;

        endif;
    }

    public function ExeDelete($ClienteId) {
        $this->Id = (int) $ClienteId;
        $ReadCliente = new Read;
        $ReadCliente->ExeRead(self::Entidy, "WHERE cliente_id = :id", "id={$this->Id}");

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

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

            $deleta = new Delete;
            $deleta->ExeDelete("tp_cliente_images", "WHERE cliente_id = :gbcliente", "gbcliente={$this->Id}");
            $deleta->ExeDelete(self::Entidy, "WHERE cliente_id = :clienteid", "clienteid={$this->Id}");

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

    public function ExeStatus($ClienteId, $ClienteStatus) {
        $this->Id = (int) $ClienteId;
        $this->Data['cliente_status'] = (string) $ClienteStatus;

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

    public function gbSend(array $Images, $ClienteId) {
        $this->Id = (int) $ClienteId;
        $this->Data = $Images;

        $ImageName = new Read;
        $ImageName->ExeRead(self::Entidy, "WHERE cliente_id = :id", "id={$this->Id}");
        if (!$ImageName->getResult()):
            $this->Error = ["Erro ao enviar galeria. O índice {$this->Id} não foi encontrado no banco!", WS_ERROR];
            $this->Result = false;
        else:
            $ImageName = $ImageName->getResult()[0]['cliente_nome'];

            $gbFiles = array();
            $gbCount = count($this->Data['tmp_name']);
            $gbKeys = array_keys($this->Data);

            for ($gb = 0; $gb < $gbCount; $gb++):
                foreach ($gbKeys as $Keys):
                    $gbFiles[$gb][$Keys] = $this->Data[$Keys][$gb];
                endforeach;
            endfor;

            $gbSend = new Upload;
            $i = 0;
            $u = 0;

            foreach ($gbFiles as $gbUpload):
                $i++;
                $ImageName = "{$ImageName}-gb-{$this->Id}-" . (substr(md5(time() + $i), 0, 5));
                $gbSend->Image($gbUpload, $ImageName);

                if ($gbSend->getResult()):
                    $gbImage = $gbSend->getResult();
                    $gbCreate = ['cliente_id' => $this->Id, "cliente_img" => $gbImage];
                    $insertGb = new Create;
                    $insertGb->ExeCreate("tp_cliente_images", $gbCreate);
                    $u++;
                endif;
            endforeach;

            if ($u > 1):
                $this->Error = ["Galeria Atualizada: Foram enviadas {$u} imagens para galeria deste cliente!", WS_ACCEPT];
                $this->Result = true;
            endif;

        endif;
    }

    public function gbRemove($GbImageId) {
        $this->Id = (int) $GbImageId;
        $readGb = new Read;
        $readGb->ExeRead("ws_clientes_gallery", "WHERE gallery_id = :gb", "gb={$this->Id}");
        if ($readGb->getResult()):
            $Imagem = '../uploads/' . $readGb->getResult()[0]['gallery_image'];

            if (file_exists($Imagem) && !is_dir($Imagem)):
                unlink($Imagem);
            endif;

            $Deleta = new Delete;
            $Deleta->ExeDelete("ws_clientes_gallery", "WHERE gallery_id = :id", "id={$this->Id}");
            if ($Deleta->getResult()):
                $this->Error = ["A imagem foi removida com sucesso da galeria! ", WS_ACCEPT];
                $this->Result = true;

            endif;
        endif;
    }

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

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

    //PRIVATE
    private function setData() {
        $Cover = $this->Data['image'];
        unset($this->Data['image']);

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

        $this->Data['image'] = $Cover;
    }

    private function getCatParent() {
        $rCat = new Read;
        $rCat->ExeRead("ws_categories", "WHERE category_id = :id", "id={$this->Data['cliente_category']}");
        if ($rCat->getResult()):
            return $rCat->getResult()[0]['category_parent'];
        else:
            return null;
        endif;
    }

    private function setName() {
        $where = (isset($this->Id) ? "id != {$this->Id} AND" : '');

        $readName = new Read;
        $readName->ExeRead(self::Entidy, "WHERE {$where} name = :t", "t={$this->Data['name']}");
        if ($readName->getResult()):
            $this->Data['cliente_nome'] = $this->Data['name'] . '-' . $readName->getRowCount();
        endif;
    }

    private function Create() {
        $cadastra = new Create;
        $cadastra->ExeCreate(self::Entidy, $this->Data);
        if ($cadastra->getResult()):
            $this->Error = ["O cliente <b>{$this->Data['name']}</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 cliente_id = :id", "id={$this->Id}");
        if ($Update->getResult()):
            $this->Error = ["O cliente <b>{$this->Data['cliente_titulo']}</b> foi atualizado com sucesso no sistema!", WS_ACCEPT];
            $this->Result = true;
        endif;
    }

}
