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

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

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

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

    /**
     * 게시판 수정 - 작성 저장
     * @method GET
     * @see /admin/board/board/write/store
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'write_header_content' => 'string|nullable',
            'mobile_write_header_content' => 'string|nullable',
            'post_default_subject' => 'string|nullable',
            'post_default_content' => 'string|nullable',
            'use_post_dhtml' => 'required|numeric|in:0,1',
            'save_external_image' => 'required|numeric|in:0,1',
            'post_subject_min_length' => 'required|numeric|min:0',
            'post_subject_max_length' => 'required|numeric|min:0|max:255',
            'post_content_min_length' => 'required|numeric|min:0',
            'post_content_max_length' => 'required|numeric|min:0|max:4000',
            'use_category_required' => 'nullable|numeric|in:1,0',
            'use_post_secret' => 'nullable|numeric|in:1,2',
            'use_post_secret_selected' => 'required|numeric|in:0,1',
            'use_post_tag' => 'required|numeric|in:0,1',
            'link_num' => 'required|numeric|min:0|max:10',
            'use_upload_file' => 'required|numeric|in:0,1',
            'upload_file_num' => 'required|numeric|min:0|max:10',
            'upload_file_max_size' => 'required|numeric',
            'upload_only_img_file' => 'string|numeric|in:0,1',
            'upload_file_extension' => 'string|nullable|max:255',
            'use_only_one_post' => 'required|numeric|in:0,1',
            'use_post_captcha' => 'required|numeric|in:0,1',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'write_header_content' => '작성폼 상단 내용',
            'mobile_write_header_content' => '모바일 작성폼 상단 내용',
            'post_default_subject' => '글쓰기 시 기본 제목',
            'post_default_content' => '글쓰기 시 기본 내용',
            'use_post_dhtml' => '본문 에디터 사용',
            'save_external_image' => '외부 이미지 가져오기',
            'post_subject_min_length' => '최소 글수 제한 (제목)',
            'post_subject_max_length' => '최대 글수 제한 (제목)',
            'post_content_min_length' => '최소 글수 제한 (내용)',
            'post_content_max_length' => '최대 글수 제한 (내용)',
            'use_category_required' => '분류 필수 선택',
            'use_post_secret' => '비밀글 사용',
            'use_post_secret_selected' => '비밀글 기본 선택',
            'use_post_tag' => '태그 사용',
            'link_num' => 'URL Link 개수',
            'use_upload_file' => '첨부파일 사용',
            'upload_file_num' => '첨부파일 개수 제한',
            'upload_file_max_size' => '첨부파일 용량 제한',
            'upload_only_img_file' => '첨부파일 이미지 허용',
            'upload_file_extension' => '첨부파일 허용 확장자',
            'use_only_one_post' => '하루에 한 글만 작성',
            'use_post_captcha' => 'Captcha 사용',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

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

        $defaultData = [ // 그룹, 전체 적용 값
            'write_header_content', 'mobile_write_header_content', 'post_default_subject', 'post_default_content',
            'use_post_dhtml', 'save_external_image', 'post_subject_min_length', 'post_subject_max_length',
            'post_content_min_length', 'post_content_max_length', 'use_category_required', 'use_post_secret', 'use_post_secret_selected',
            'use_post_tag', 'link_num', 'use_upload_file', 'upload_file_num', 'upload_file_max_size',
            'upload_only_img_file', 'upload_file_extension', 'use_only_one_post', 'use_post_captcha'
        ];

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

        // 메타 정보 저장
        $metaData = [
            'write_header_content' => $posts['write_header_content'],
            'mobile_write_header_content' => $posts['mobile_write_header_content'],
            'post_default_subject' => $posts['post_default_subject'],
            'post_default_content' => $posts['post_default_content'],
            'use_post_dhtml' => $posts['use_post_dhtml'],
            'save_external_image' => $posts['save_external_image'],
            'post_subject_min_length' => $posts['post_subject_min_length'],
            'post_subject_max_length' => $posts['post_subject_max_length'],
            'post_content_min_length' => $posts['post_content_min_length'],
            'post_content_max_length' => $posts['post_content_max_length'],
            'use_category_required' => $posts['use_category_required'],
            'use_post_secret' => $posts['use_post_secret'],
            'use_post_secret_selected' => $posts['use_post_secret_selected'],
            'link_num' => $posts['link_num'],
            'use_post_tag' => $posts['use_post_tag'],
            'use_upload_file' => $posts['use_upload_file'],
            'upload_file_num' => $posts['upload_file_num'],
            'upload_file_max_size' => $posts['upload_file_max_size'],
            'upload_only_img_file' => $posts['upload_only_img_file'],
            'upload_file_extension' => $posts['upload_file_extension'],
            'use_only_one_post' => $posts['use_only_one_post'],
            'use_post_captcha' => $posts['use_post_captcha']
        ];

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