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

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

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

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

    /**
     * 게시판 수정 - 일반 저장
     * @method POST
     * @see /admin/board/board/general/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'block_delete' => 'required|numeric|in:0,1',
            'protect_post_day' => 'required|numeric|min:0|max:365',
            'protect_comment_day' => 'required|numeric|min:0|max:365',
            'protect_delete_post' => 'required|numeric|in:0,1',
            'protect_update_post' => 'required|numeric|in:0,1',
            'use_category' => 'required|numeric|in:0,1',
            'use_personal' => 'required|numeric|in:0,1',
            'use_anonymous' => 'required|numeric|in:0,1',
            'anonymous_except_admin' => 'required|numeric|in:0,1',
            'anonymous_name' => 'required|string|max:100',
            'use_download_log' => 'required|numeric|in:0,1',
            'use_post_history' => 'required|numeric|in:0,1',
            'use_link_click_log' => 'required|numeric|in:0,1',
            'use_comment_history' => 'required|numeric|in:0,1',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'block_delete' => '관리자만 삭제',
            'protect_post_day' => '게시글 수정/삭제 금지 기간',
            'protect_comment_day' => '댓글 수정/삭제 금지 기간',
            'protect_delete_post' => '게시글 보호 기능 (삭제 시)',
            'protect_update_post' => '게시글 보호 기능 (수정 시)',
            'use_category' => '분류 기능',
            'use_personal' => '1:1 게시판',
            'use_anonymous' => '익명 게시판',
            'anonymous_except_admin' => '관리자 익명 제외',
            'anonymous_name' => '익명 이름',
            'use_download_log' => '다운로드 기록',
            'use_post_history' => '게시물 변경 기록',
            'use_link_click_log' => 'Link 클릭 기록',
            'use_comment_history' => '댓글 변경 기록',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

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

        $defaultData = [ // 그룹, 전체 적용 값
            'block_delete', 'protect_post_day', 'protect_comment_day', 'protect_delete_post', 'protect_update_post',
            'use_category', 'use_personal', 'use_anonymous', 'anonymous_except_admin', 'anonymous_name',
            'use_download_log', 'use_post_history', 'use_link_click_log', 'use_comment_history'
        ];

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

        // 메타 정보 저장
        $metaData = [
            'block_delete' => $posts['block_delete'],
            'protect_post_day' => $posts['protect_post_day'],
            'protect_comment_day' => $posts['protect_comment_day'],
            'protect_delete_post' => $posts['protect_delete_post'],
            'protect_update_post' => $posts['protect_update_post'],
            'use_category' => $posts['use_category'],
            'use_personal' => $posts['use_personal'],
            'use_anonymous' => $posts['use_anonymous'],
            'anonymous_except_admin' => $posts['anonymous_except_admin'],
            'anonymous_name' => $posts['anonymous_name'],
            'use_download_log' => $posts['use_download_log'],
            'use_post_history' => $posts['use_post_history'],
            'use_link_click_log' => $posts['use_link_click_log'],
            'use_comment_history' => $posts['use_comment_history']
        ];

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