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

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

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

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

            // 권한 종류
            'authorityType' => [
                '' => '모든 사용자',
                '1' => '로그인 사용자',
                '100' => '관리자',
            ]
        ]);
    }

    /**
     * 게시판 수정 - 권한 저장
     * @method POST
     * @see /admin/board/board/authority/{pk}
     */
    public function store(Request $request)
    {
        $rules = [
            'board_id' => 'required|numeric|exists:tb_board,id',
            'access_post_list' => 'nullable|numeric',
            'access_post_view' => 'nullable|numeric',
            'access_post_write' => 'nullable|numeric',
            'access_comment_list' => 'nullable|numeric',
            'access_comment_write' => 'nullable|numeric',
            'access_image_upload' => 'nullable|numeric',
            'access_file_download' => 'nullable|numeric',
            'grp' => 'array',
            'all' => 'array'
        ];

        $attributes = [
            'board_id' => '게시판 PK',
            'access_post_list' => '목록',
            'access_post_view' => '글 열람',
            'access_post_write' => '글 작성',
            'access_comment_list' => '댓글 목록',
            'access_comment_write' => '댓글 작성',
            'access_image_upload' => '이미지 첨부',
            'access_file_download' => '파일 다운로드',
            'grp' => '그룹 적용',
            'all' => '전체 적용'
        ];

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

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

        // 메타 정보 저장
        $metaData = [];

        $selectArr = [
            'access_post_list',
            'access_post_view',
            'access_post_write',
            'access_comment_list',
            'access_comment_write',
            'access_image_upload',
            'access_file_download'
        ];

        foreach($selectArr as $name) {
            $metaData[$name] = $posts[$name];
        }

        DB::beginTransaction();

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

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

            $groupKeys = $posts['grp'] ?? [];
            $allKeys = $posts['all'] ?? [];

            if ($groupKeys) {
                $brdGroupData = $this->boardModel->findByGroup($boardData->board_group_id);
                foreach ($brdGroupData as $bKey => $bVal) {
                    if ($bVal->id === $boardID) {
                        continue;
                    }
                    foreach ($groupKeys as $gk => $gv) {
                        $groupData[$gk] = $metaData[$gk];
                    }
                    $this->boardMetaModel->save($bVal->id, $groupData);
                }
            }

            if ($allKeys) {
                $brdAllData = $this->boardModel->all();
                foreach ($brdAllData as $bKey => $bVal) {
                    if ($bVal->id === $boardID) {
                        continue;
                    }
                    foreach ($allKeys as $ak => $av) {
                        $allData[$ak] = $metaData[$ak];
                    }
                    $this->boardMetaModel->save($bVal->id, $allData);
                }
            }

            $message = '게시판 - 권한 정보가 저장되었습니다.';
            DB::commit();
        } catch (Exception $e) {
            $message = $e->getMessage();
            DB::rollBack();
        }

        return redirect()->route('admin.board.board.authority.show', $boardID)->with('message', $message);
    }
}
