<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\DTO\SearchData;
use Exception;

class PostDeleted extends Model
{
    protected $table = 'tb_post_deleted';
    protected $primaryKey = 'id';

    public $keyType = 'int';
    public $incrementing = true;
    public $timestamps = true;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = null;

    protected $guarded = [];

    public function board()
    {
        return $this->belongsTo(Board::class)->withDefault();
    }

    public function post()
    {
        return $this->belongsTo(Post::class)->withDefault();
    }

    public function user()
    {
        return $this->belongsTo(User::class)->withDefault();
    }

    /**
     * 게시판 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_board.name AS boardName',
            'tb_post_deleted.*',
            'tb_post.subject',
            'tb_post.content',
            'tb_post.sid',
            'tb_post.username',
            'users.sid',
            'users.name'
        );

        if($params->keyword) {
            switch ($params->field) {
                case 'tb_post.subject' :
                case 'tb_post_deleted.ip_address' :
                case 'users.name' :
                case 'users.email' :
                    $query->where($params->field, 'LIKE', "%{$params->keyword}%");
                    break;
                case 'tb_post.id' :
                case 'users.id' :
                case 'users.sid' :
                    $query->where($params->field, '=', $params->keyword);
                    break;
            }
        }

        if($params->startDate || $params->endDate) {
            if($params->startDate) {
                $query->where('tb_post_deleted.created_at', '>=', $params->startDate . ' 00:00:00');
            }
            if($params->endDate) {
                $query->where('tb_post_deleted.created_at', '<=', $params->endDate . ' 23:59:59');
            }
        }

        if($params->boardID) {
            $query->where('tb_post_deleted.board_id', '=', $params->boardID);
        }

        $query->join('tb_board', 'tb_board.id', '=', 'tb_post_deleted.board_id');
        $query->join('tb_post', 'tb_post.id', '=', 'tb_post_deleted.post_id');
        $query->leftjoin('users', 'users.id', '=', 'tb_post_deleted.user_id');
        $query->orderByDesc('tb_post_deleted.id');

        $list = $query->paginate($params->perPage, ['*'], 'page', $params->page);
        $total = $this->count();
        $rows = $list->count();

        return (object)[
            'total' => $total,
            'rows' => $rows,
            'list' => $list
        ];
    }

    /**
     * 게시글 전체삭제
     */
    public function truncate(): bool
    {
        DB::beginTransaction();

        try
        {
            // 게시글 실제 삭제
            foreach ($this->select('id')->get() as $row) {
                if (!$this->remove($row->id)) {
                    throw new Exception();
                }
            }

            DB::commit();
            return true;
        }catch(Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 게시물 삭제
     */
    public function remove(int $deletedID): bool
    {
        $boardModel = new Board();
        $postModel = new Post();
        $postBlameModel = new PostBlame();
        $postBookmarkModel = new PostBookmark();
        $postFileModel = new PostFile();
        $postFileDownloadLogModel = new PostFileDownLog();
        $postHistoryModel = new PostHistory();
        $postLikeModel = new PostLike();
        $postLinkModel = new PostLink();
        $postLinkClickLogModel = new PostLinkClickLog();
        $postMetaModel = new PostMeta();
        $postTagModel = new PostTag();

        $commentModel = new Comment();
        $commentBlameModel = new CommentBlame();
        $commentHistoryModel = new CommentHistory();
        $commentLikeModel = new CommentLike();
        $editorImageModel = new EditorImage();

        DB::beginTransaction();

        try
        {
            $postDelete = $this->findOrNew($deletedID);

            if(!$postDelete->exists) {
                return false;
            }

            $boardID = $postDelete->board_id;
            $postID = $postDelete->post_id;

            $where = [
                ['board_id', $boardID],
                ['post_id', $postID]
            ];

            $postModel->find($postID)->delete();                    // 게시물 삭제
            $postBlameModel->where($where)->delete();               // 게시물 신고 기록 삭제
            $postBookmarkModel->where($where)->delete();            // 게시물 즐겨 찾기 삭제
            $postFileDownloadLogModel->where($where)->delete();     // 첨부파일 다운로드 기록 삭제
            $postHistoryModel->where($where)->delete();             // 게시물 변경 이력 삭제
            $postLikeModel->where($where)->delete();                // 추천/비추천 기록 삭제
            $postLinkModel->where($where)->delete();                // 게시물 URL 삭제
            $postLinkClickLogModel->where($where)->delete();        // 게시물 URL 클릭 로그 삭제
            $postTagModel->where($where)->delete();                 // 게시물 태그 삭제
            $postMetaModel->deleteMeta($postID);                    // 게시물 메타 정보 삭제

            // 첨부 파일 삭제
            $postFileModel->truncate($postID);

            // 게시글 이미지 전체삭제
            $editorImageModel->truncate(EDITOR_IMG_TYPE_1, $postID);

            // 댓글 이미지 전체삭제
            $editorImageModel->truncate(EDITOR_IMG_TYPE_2, $postID);

            // 댓글 삭제
            $commentModel->where($where)->delete();
            $commentBlameModel->where($where)->delete();
            $commentHistoryModel->where($where)->delete();
            $commentLikeModel->where($where)->delete();

            // 게시판 게시글 수 갱신
            $boardModel->updatePostRows($boardID);

            // 게시판 댓글 수 갱신
            $boardModel->updateCommentRows($boardID);

            // 게시물 삭제 완료
            $postDelete->delete();

            DB::commit();
            return true;
        }catch(Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 게시물 복원
     */
    public function recovery(int $deletedID): bool
    {
        DB::beginTransaction();

        try
        {
            $postDelete = $this->findOrNew($deletedID);

            if(!$postDelete->exists) {
                return false;
            }

            $where = [
                ['id', $postDelete->post_id],
                ['board_id', $postDelete->board_id],
                ['is_delete', 1]
            ];

            $updateData = [
                'is_delete' => 0,
                'deleted_at' => null
            ];

            // 게시물 삭제 복구
            (new Post)->where($where)->update($updateData);

            // 댓글 삭제 복구
            (new Comment)->where($where)->update($updateData);

            // 게시물 삭제 기록 제거
            $postDelete->delete();

            DB::commit();
            return true;
        }catch(Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 게시글 삭제 등록
     */
    public function register(array $params): int
    {
        return $this->insertGetId($params);
    }
}
