<?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 ViewController 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/view/{pk}
     */
    public function show(int $boardID)
    {
        return view('admin.board.board.view', [
            'boardID' => $boardID,
            'actionURL' => route('admin.board.board.view.store'),

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

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

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

    /**
     * 게시판 수정 - 열람 저장
     * @method POST
     * @see /admin/board/board/view/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'use_bookmark' => 'required|numeric|in:0,1',
            'use_post_like' => 'required|numeric|in:0,1',
            'use_post_dislike' => 'required|numeric|in:0,1',
            'use_print' => 'required|numeric|in:0,1',
            'use_sns' => 'required|numeric|in:0,1',
            'use_prev_next_post' => 'required|numeric|in:0,1',
            'use_blame' => 'required|numeric|in:0,1',
            'blame_blind_count' => 'required|numeric',
            'show_post_ip' => 'nullable|numeric',
            'content_target_blank' => 'required|numeric|in:0,1',
            'use_auto_url' => 'required|numeric|in:0,1',
            'use_copy_post_url' => 'required|numeric|in:0,1',
            'use_url_qrcode' => 'required|numeric|in:0,1',
            'use_attached_url_qrcode' => 'required|numeric|in:0,1',
            'need_like_for_download' => 'required|numeric|in:0,1',
            'need_comment_for_download' => 'required|numeric|in:0,1',
            'show_user_thumb_in_post' => 'required|numeric|in:0,1',
            'show_user_icon_in_post' => 'required|numeric|in:0,1',
            'use_post_user_regdate' => 'required|numeric|in:0,1',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'use_bookmark' => '즐겨찾기 기능',
            'use_post_like' => '추천 기능',
            'use_post_dislike' => '비추천 기능',
            'use_print' => '본문 인쇄 기능',
            'use_sns' => 'SNS 보내기 기능',
            'use_prev_next_post' => '이전글, 다음글 버튼',
            'use_blame' => '신고 기능',
            'blame_blind_count' => '신고 시 숨김',
            'show_post_ip' => 'IP 보이기',
            'content_target_blank' => 'Link 새창',
            'use_auto_url' => '본문 URL Link 생성',
            'use_copy_post_url' => '주소 복사 버튼',
            'use_url_qrcode' => '글 주소 QR 코드',
            'use_attached_url_qrcode' => '첨부된 링크 QR 코드 ',
            'need_like_for_download' => '다운로드 제한 (추천 필수)',
            'need_comment_for_download' => '다운로드 제한 (댓글 필수)',
            'show_user_thumb_in_post' => '회원 프로필 이미지',
            'show_user_icon_in_post' => '회원 아이콘 이미지',
            'use_post_user_regdate' => '회원 가입일',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

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

        $defaultData = [ // 그룹, 전체 적용 값
            'use_bookmark', 'use_post_like', 'use_post_dislike', 'use_print', 'use_sns',
            'use_prev_next_post', 'use_blame', 'blame_blind_count', 'show_post_ip',
            'content_target_blank', 'use_auto_url', 'use_copy_post_url', 'use_url_qrcode',
            'use_attached_url_qrcode', 'need_like_for_download', 'need_comment_for_download',
            'show_user_thumb_in_post', 'show_user_icon_in_post', 'use_post_user_regdate'
        ];

        // 게시판 정보 조회
        $boardData = $this->boardModel->find($posts['board_id']);

        // 메타 정보 저장
        $metaData = [
            'use_bookmark' => $posts['use_bookmark'],
            'use_post_like' => $posts['use_post_like'],
            'use_post_dislike' => $posts['use_post_dislike'],
            'use_print' => $posts['use_print'],
            'use_sns' => $posts['use_sns'],
            'use_prev_next_post' => $posts['use_prev_next_post'],
            'use_blame' => $posts['use_blame'],
            'blame_blind_count' => $posts['blame_blind_count'],
            'show_post_ip' => $posts['show_post_ip'],
            'content_target_blank' => $posts['content_target_blank'],
            'use_auto_url' => $posts['use_auto_url'],
            'use_copy_post_url' => $posts['use_copy_post_url'],
            'use_url_qrcode' => $posts['use_url_qrcode'],
            'use_attached_url_qrcode' => $posts['use_attached_url_qrcode'],
            'need_like_for_download' => $posts['need_like_for_download'],
            'need_comment_for_download' => $posts['need_comment_for_download'],
            'show_user_thumb_in_post' => $posts['show_user_thumb_in_post'],
            'show_user_icon_in_post' => $posts['show_user_icon_in_post'],
            'use_post_user_regdate' => $posts['use_post_user_regdate']
        ];

        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.view.show', $boardID)->with('message', $message);
    }
}
