<?php

namespace App\Http\Controllers\Admin\Board\Board;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Board;
use App\Models\BoardMeta;
use Exception;

class CommentController extends Controller
{
    private Board $boardModel;
    private BoardMeta $boardMetaModel;

    public function __construct(Board $board, BoardMeta $boardMeta)
    {
        $this->boardModel = $board;
        $this->boardMetaModel = $boardMeta;
    }

    /**
     * 게시판 수정 - 댓글
     * @method GET
     * @see /admin/board/board/comment/{pk}
     */
    public function show(int $boardID)
    {
        return view('admin.board.board.comment', [
            'boardID' => $boardID,
            'actionURL' => route('admin.board.board.comment.store'),

            // 게시판 정보
            'boardData' => $this->boardModel->find($boardID),

            // 게시판 메타 정보
            'boardMetaData' => $this->boardMetaModel->getAllMeta($boardID),

            // 모든 게시판
            'boardAllData' => $this->boardModel->all()
        ]);
    }

    /**
     * 게시판 수정 - 작성 저장
     * @method POST
     * @see /admin/board/board/comment/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'use_comment' => 'required|numeric',
            'comment_per_page' => 'required|numeric|min:0|max:20',
            'comment_page_count' => 'required|numeric|min:0|max:10',
            'use_comment_like' => 'required|numeric',
            'use_comment_dislike' => 'required|numeric',
            'show_user_thumb_in_comment' => 'required|numeric|in:0,1',
            'show_user_icon_in_comment' => 'required|numeric|in:0,1',
            'update_order_on_comment' => 'required|numeric',
            'comment_default_content' => 'string|nullable|max:1000',
            'comment_min_length' => 'required|numeric|min:0',
            'comment_max_length' => 'required|numeric|min:0|max:99999999',
            'use_comment_secret' => 'nullable|numeric|in:1,2',
            'use_comment_secret_selected' => 'required|numeric|in:0,1',
            'show_comment_ip' => 'nullable|numeric',
            'use_comment_blame' => 'required|numeric|in:0,1',
            'comment_blame_blind_count' => 'required|numeric|min:0',
            'protect_delete_comment' => 'required|numeric|in:0,1',
            'protect_update_comment' => 'required|numeric|in:0,1',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'use_comment' => '댓글 사용 여부',
            'comment_per_page' => '댓글 목록 수',
            'comment_page_count' => '댓글 페이지 수',
            'use_comment_like' => '댓글 추천 기능',
            'use_comment_dislike' => '댓글 비추천 기능',
            'show_user_thumb_in_comment' => '회원 프로필 이미지',
            'show_user_icon_in_comment' => '회원 아이콘 이미지',
            'update_order_on_comment' => '댓글 작성시 글 수정 시각 갱신',
            'comment_default_content' => '댓글 기본 내용',
            'comment_min_length' => '최소 글수 제한',
            'comment_max_length' => '최대 글수 제한',
            'use_comment_secret' => '비밀글 사용',
            'use_comment_secret_selected' => '비밀글 기본 선택',
            'show_comment_ip' => 'IP 보이기',
            'use_comment_blame' => '댓글 신고 기능',
            'comment_blame_blind_count' => '댓글 신고 시 숨김',
            'protect_delete_comment' => '댓글 보호 기능 (삭제 시)',
            'protect_update_comment' => '댓글 보호 기능 (수정 시)',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

        $posts = $this->validate($request, $rules, [], $attributes);
        $boardID = $posts['board_id'];

        $defaultData = [ // 그룹, 전체 적용 값
            'use_comment', 'comment_per_page', 'comment_page_count', 'use_comment_like', 'use_comment_dislike',
            'show_user_thumb_in_comment', 'show_user_icon_in_comment', 'update_order_on_comment',
            'comment_default_content', 'comment_min_length', 'comment_max_length',
            'use_comment_secret', 'use_comment_secret_selected', 'show_comment_ip',
            'use_comment_blame', 'comment_blame_blind_count', 'protect_delete_comment', 'protect_update_comment'
        ];

        // 게시판 정보 조회
        $boardData = $this->boardModel->find($boardID);

        // 메타 정보 저장
        $metaData = [
            'use_comment' => $posts['use_comment'],
            'comment_per_page' => $posts['comment_per_page'],
            'comment_page_count' => $posts['comment_page_count'],
            'use_comment_like' => $posts['use_comment_like'],
            'use_comment_dislike' => $posts['use_comment_dislike'],
            'show_user_thumb_in_comment' => $posts['show_user_thumb_in_comment'],
            'show_user_icon_in_comment' => $posts['show_user_icon_in_comment'],
            'update_order_on_comment' => $posts['update_order_on_comment'],
            'comment_default_content' => $posts['comment_default_content'],
            'comment_min_length' => $posts['comment_min_length'],
            'comment_max_length' => $posts['comment_max_length'],
            'use_comment_secret' => $posts['use_comment_secret'],
            'use_comment_secret_selected' => $posts['use_comment_secret_selected'],
            'show_comment_ip' => $posts['show_comment_ip'],
            'use_comment_blame' => $posts['use_comment_blame'],
            'comment_blame_blind_count' => $posts['comment_blame_blind_count'],
            'protect_delete_comment' => $posts['protect_delete_comment'],
            'protect_update_comment' => $posts['protect_update_comment']
        ];

        DB::beginTransaction();

        try
        {
            $this->boardMetaModel->save($boardID, $metaData);

            /*
             * 그룹, 전체 적용
             */
            $groupData = []; // 그룹적용
            $allData = []; // 전체적용

            foreach ($defaultData as $field) {
                if (isset($posts['grp'][$field])) {
                    $groupData[$field] = $posts[$field];
                }
                if (isset($posts['all'][$field])) {
                    $allData[$field] = $posts[$field];
                }
            }

            if ($groupData) {
                $brdGroupData = $this->boardModel->findByGroup($boardData->board_group_id);
                foreach ($brdGroupData as $bKey => $bVal) {
                    if ($bVal->id === $boardID) {
                        continue;
                    }
                    $this->boardMetaModel->save($bVal->id, $groupData);
                }
            }
            if ($allData) {
                $brdAllData = $this->boardModel->all();
                foreach ($brdAllData as $bKey => $bVal) {
                    if ($bVal->id === $boardID) {
                        continue;
                    }
                    $this->boardMetaModel->save($bVal->id, $allData);
                }
            }

            $message = '게시판 - 댓글 정보가 저장되었습니다.';
            DB::commit();
        } catch (Exception $e) {
            $message = $e->getMessage();
            DB::rollBack();
        }

        return redirect()->route('admin.board.board.comment.show', $boardID)->with('message', $message);
    }
}
