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

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

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

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

    /**
     * 게시판 수정 - 경험치 저장
     * @method POST
     * @see /admin/board/board/exp/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'use_exp' => 'required|numeric|in:0,1',
            'use_exp_info' => 'required|numeric|in:0,1',
            'exp_write' => 'required|numeric',
            'exp_comment' => 'required|numeric',
            'exp_post_delete' => 'required|numeric',
            'exp_admin_post_delete' => 'required|numeric',
            'exp_comment_delete' => 'required|numeric',
            'exp_admin_comment_delete' => 'required|numeric',
            'exp_file_upload' => 'required|numeric',
            'exp_file_download' => 'required|numeric',
            'exp_file_download_uploader' => 'required|numeric',
            'exp_read' => 'required|numeric',
            'exp_post_like' => 'required|numeric',
            'exp_post_dislike' => 'required|numeric',
            'exp_post_liked' => 'required|numeric',
            'exp_post_disliked' => 'required|numeric',
            'exp_comment_like' => 'required|numeric',
            'exp_comment_dislike' => 'required|numeric',
            'exp_comment_liked' => 'required|numeric',
            'exp_comment_disliked' => 'required|numeric'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'use_exp' => '경험치 기능 사용',
            'use_exp_info' => '경험치 안내',
            'exp_write' => '원글 작성',
            'exp_comment' => '댓글 작성',
            'exp_post_delete' => '작성자 본인이 원글 삭제',
            'exp_admin_post_delete' => '관리자가 원글 삭제',
            'exp_comment_delete' => '작성자 본인이 댓글 삭제',
            'exp_admin_comment_delete' => '관리자가 댓글 삭제',
            'exp_file_upload' => '파일 업로드',
            'exp_file_download' => '파일 다운로드',
            'exp_file_download_uploader' => '파일 다운로드 시 업로더에게',
            'exp_read' => '게시글 조회',
            'exp_post_like' => '원글 추천함',
            'exp_post_dislike' => '원글 비추천함',
            'exp_post_liked' => '원글 추천 받음',
            'exp_post_disliked' => '원글 비추천 받음',
            'exp_comment_like' => '댓글 추천함',
            'exp_comment_dislike' => '댓글 비추천함',
            'exp_comment_liked' => '댓글 추천 받음',
            'exp_comment_disliked' => '댓글 비추천 받음'
        ];

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

        $defaultData = [ // 그룹, 전체 적용 값
            'use_exp', 'use_exp_info', 'exp_write', 'exp_comment', 'exp_post_delete', 'exp_admin_post_delete',
            'exp_comment_delete', 'exp_admin_comment_delete', 'exp_file_upload', 'exp_file_download',
            'exp_file_download_uploader', 'exp_read', 'exp_post_like', 'exp_post_dislike', 'exp_post_liked',
            'exp_post_disliked', 'exp_comment_like', 'exp_comment_dislike', 'exp_comment_liked', 'exp_comment_disliked'
        ];

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

        // 메타 정보 저장
        $metaData = [
            'use_exp' => $posts['use_exp'],
            'use_exp_info' => $posts['use_exp_info'],
            'exp_write' => $posts['exp_write'],
            'exp_comment' => $posts['exp_comment'],
            'exp_post_delete' => $posts['exp_post_delete'],
            'exp_admin_post_delete' => $posts['exp_admin_post_delete'],
            'exp_comment_delete' => $posts['exp_comment_delete'],
            'exp_admin_comment_delete' => $posts['exp_admin_comment_delete'],
            'exp_file_upload' => $posts['exp_file_upload'],
            'exp_file_download' => $posts['exp_file_download'],
            'exp_file_download_uploader' => $posts['exp_file_download_uploader'],
            'exp_read' => $posts['exp_read'],
            'exp_post_like' => $posts['exp_post_like'],
            'exp_post_dislike' => $posts['exp_post_dislike'],
            'exp_post_liked' => $posts['exp_post_liked'],
            'exp_post_disliked' => $posts['exp_post_disliked'],
            'exp_comment_like' => $posts['exp_comment_like'],
            'exp_comment_dislike' => $posts['exp_comment_dislike'],
            'exp_comment_liked' => $posts['exp_comment_liked'],
            'exp_comment_disliked' => $posts['exp_comment_disliked']
        ];

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