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

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

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

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

    /**
     * 게시판 수정 - 목록 저장
     * @method POST
     * @see /admin/board/board/post/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'board_layout_type' => 'required|numeric|in:0,1,2',
            'list_sort_type' => 'required|numeric|in:1,2,3,4',
            'list_per_page' => 'required|numeric|between:0,50',
            'list_mobile_per_page' => 'required|numeric|between:0,50',
            'list_page_count' => 'required|numeric|between:0,50',
            'list_page_mobile_count' => 'required|numeric|between:0,50',
            'always_show_write_button' => 'required|in:0,1',
            'show_list_from_view' => 'required|in:0,1',
            'new_icon_hour' => 'required|numeric|between:0,24',
            'hot_icon_hit' => 'required|numeric|between:0,999999',
            'hot_icon_day' => 'required|numeric|between:0,365',
            'subject_length' => 'required|max:255',
            'subject_mobile_length' => 'required|max:255',
            'except_notice' => 'required|numeric',
            'except_speaker' => 'required|numeric',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'board_layout_type' => '게시판 종류',
            'list_sort_type' => '기본 정렬 순',
            'list_per_page' => 'PC - 목록 수',
            'list_mobile_per_page' => '모바일 - 목록 수',
            'list_page_count' => 'PC - 페이지 수',
            'list_page_mobile_count' => '모바일 - 페이지 수',
            'always_show_write_button' => '글쓰기 버튼 보이기',
            'show_list_from_view' => '하단 목록 보이기',
            'new_icon_hour' => 'NEW 아이콘 - 시간',
            'hot_icon_hit' => 'HOT 아이콘 - 조회 수',
            'hot_icon_day' => 'HOT 아이콘 - 일',
            'subject_length' => 'PC - 제목',
            'subject_mobile_length' => 'PC - 모바일',
            'except_notice' => '공지사항 제외',
            'except_speaker' => '전체공지 제외',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

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

        $defaultData = [ // 그룹, 전체 적용 값
            'board_layout_type', 'list_sort_type', 'list_per_page', 'list_mobile_per_page',
            'list_page_count', 'list_page_mobile_count', 'always_show_write_button', 'show_list_from_view', 'new_icon_hour',
            'hot_icon_hit', 'hot_icon_day', 'subject_length', 'subject_mobile_length', 'except_notice', 'except_speaker'
        ];

        $mapMobileData = [ // 모바일 값
            'list_per_page' => 'list_mobile_per_page',
            'list_page_count' => 'list_page_mobile_count',
            'subject_length' => 'subject_mobile_length'
        ];

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

        // 메타 정보 저장
        $metaData = [
            'board_layout_type' => $posts['board_layout_type'],
            'list_sort_type' => $posts['list_sort_type'],
            'list_per_page' => $posts['list_per_page'],
            'list_mobile_per_page' => $posts['list_mobile_per_page'],
            'list_page_count' => $posts['list_page_count'],
            'list_page_mobile_count' => $posts['list_page_mobile_count'],
            'always_show_write_button' => $posts['always_show_write_button'],
            'show_list_from_view' => $posts['show_list_from_view'],
            'new_icon_hour' => $posts['new_icon_hour'],
            'hot_icon_hit' => $posts['hot_icon_hit'],
            'hot_icon_day' => $posts['hot_icon_day'],
            'subject_length' => $posts['subject_length'],
            'subject_mobile_length' => $posts['subject_mobile_length'],
            'except_notice' => $posts['except_notice'],
            'except_speaker' => $posts['except_speaker']
        ];

        DB::beginTransaction();

        try
        {

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

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

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

                    if (array_key_exists($field, $mapMobileData)) {
                        $groupData[$mapMobileData[$field]] = $posts[$mapMobileData[$field]];
                    }
                }
                if (isset($posts['all'][$field])) {
                    $allData[$field] = $posts[$field];

                    if (array_key_exists($field, $mapMobileData)) {
                        $allData[$mapMobileData[$field]] = $posts[$mapMobileData[$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.post.show', $boardID)->with('message', $message);
    }
}
