<?php

namespace App\Models;

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

class CommentDeleted extends Model
{
    protected $table = 'tb_comment_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(): Board
    {
        return $this->hasOne(Board::class)->withDefault();
    }

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

    public function comment(): Comment
    {
        return $this->hasOne(Comment::class)->withDefault();
    }

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

    /**
     * 댓글 조회
     */
    public function data(SearchData $params): object
    {
        $query = $this->query();
        $query->select(
            'tb_board.name AS boardName',
            'tb_comment_deleted.*',
            'tb_comment.*',
            'tb_post.subject',
            'users.sid',
            'users.name',
            'users.email'
        );

        if($params->keyword) {
            switch ($params->field) {
                case 'tb_post.subject' :
                case 'tb_comment.content' :
                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 'tb_comment.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_comment_deleted.created_at', '>=', $params->startDate . ' 00:00:00');
            }
            if($params->endDate) {
                $query->where('tb_comment_deleted.created_at', '<=', $params->endDate . ' 23:59:59');
            }
        }

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

        $query->join('tb_post', 'tb_post.id', '=', 'tb_comment_deleted.post_id');
        $query->join('tb_comment', 'tb_comment.id', '=', 'tb_comment_deleted.comment_id');
        $query->join('tb_board', 'tb_board.id', '=', 'tb_comment.board_id');
        $query->leftjoin('users', 'users.id', '=', 'tb_comment_deleted.user_id');
        $query->orderByDesc('tb_comment_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) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 댓글 삭제
     */
    public function remove(int $deletedID): bool
    {
        $boardModel = new Board();
        $postModel = new Post();
        $commentModel = new Comment();
        $commentBlameModel = new CommentBlame();
        $commentHistoryModel = new CommentHistory();
        $commentLikeModel = new CommentLike();
        $commentMetaModel = new CommentMeta();
        $editorImageModel = new EditorImage();

        DB::beginTransaction();

        try
        {
            $deleteInfo = $this->find($deletedID);

            $boardID = $deleteInfo->board_id;
            $postID = $deleteInfo->post_id;
            $commentID = $deleteInfo->comment_id;

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

            $commentModel->where($where)->delete();                     // 댓글 삭제
            $commentBlameModel->where($where)->delete();                // 댓글 신고 기록 삭제
            $commentHistoryModel->where($where)->delete();              // 댓글 변경 이력 삭제
            $commentLikeModel->where($where)->delete();                 // 추천/비추천 기록 삭제
            $commentMetaModel->deleteMeta($commentID);     // 댓글 메타 정보 삭제

            // 게시글 이미지 삭제
            $editorImageModel->truncate(EDITOR_IMG_TYPE_2, ($postID . DIRECTORY_SEPARATOR . $commentID));

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

            // 게시글 댓글 수 갱신
            $postModel->updateCommentRows($postID);

            // 댓글 삭제 완료
            $deleteInfo->delete();

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

    /**
     * 댓글 복원
     */
    public function recovery(int $deletedID): bool
    {
        $commentModel = new Comment();

        DB::beginTransaction();

        try
        {
            $deleteInfo = $this->find($deletedID);

            // 댓글 삭제 복구
            $commentModel->where([
                ['board_id', $deleteInfo->board_id],
                ['post_id', $deleteInfo->post_id],
                ['comment_id', $deleteInfo->comment_id],
                ['is_delete', 1]
            ])->update([
                'is_delete' => 0,
                'deleted_at' => null
            ]);

            // 댓글 삭제 기록 제거
            $deleteInfo->delete();

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

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