<?php

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

    private $Data;
    private $Post;
    private $Error;
    private $Result;

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

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

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

            if ($this->Data['post_cover']):
                $upload = new Upload;
                $upload->Image($this->Data['post_cover'], $this->Data['post_name']);
            endif;

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

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

        if (in_array('', $this->Data)):
            $this->Error = ["Para atualizar este post, 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['post_cover'])):
                $readCapa = new Read;
                $readCapa->ExeRead(self::Entidy, "WHERE post_id = :post", "post={$this->Post}");
                $capa = '../uploads/' . $readCapa->getResult()[0]['post_cover'];

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

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

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

        endif;
    }

    public function ExeDelete($PostId) {
        $this->Post = (int) $PostId;
        $ReadPost = new Read;
        $ReadPost->ExeRead(self::Entidy, "WHERE post_id = :id", "id={$this->Post}");

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

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

            $deleta = new Delete;
            $deleta->ExeDelete("ws_posts_gallery", "WHERE post_id = :gbpost", "gbpost={$this->Post}");
            $deleta->ExeDelete(self::Entidy, "WHERE post_id = :postid", "postid={$this->Post}");

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

    public function ExeStatus($PostId, $PostStatus) {
        $this->Post = (int) $PostId;
        $this->Data['post_status'] = (string) $PostStatus;

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

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

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

            $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->Post}-" . (substr(md5(time() + $i), 0, 5));
                $gbSend->Image($gbUpload, $ImageName);

                if ($gbSend->getResult()):
                    $gbImage = $gbSend->getResult();
                    $gbCreate = ['post_id' => $this->Post, "gallery_image" => $gbImage, "gallery_date" => date("Y-m-d H:i:s")];
                    $insertGb = new Create;
                    $insertGb->ExeCreate("ws_posts_gallery", $gbCreate);
                    $u++;
                endif;
            endforeach;

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

        endif;
    }

    public function gbRemove($GbImageId) {
        $this->Post = (int) $GbImageId;
        $readGb = new Read;
        $readGb->ExeRead("ws_posts_gallery", "WHERE gallery_id = :gb", "gb={$this->Post}");
        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_posts_gallery", "WHERE gallery_id = :id", "id={$this->Post}");
            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['post_cover'];
        $Content = $this->Data['post_content'];
        unset($this->Data['post_cover'], $this->Data['post_content']);

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

        $this->Data['post_name'] = Check::Name($this->Data['post_title']);
        $this->Data['post_date'] = Check::Data($this->Data['post_date']);
        $this->Data['post_type'] = 'post';
        $this->Data['post_cover'] = $Cover;
        $this->Data['post_content'] = $Content;
        $this->Data['post_cat_parent'] = $this->getCatParent();
    }

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

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

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

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

}
