<?php

namespace App\Http\Controllers\Admin\Board\Group;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\BoardGroupAdmin;

class ManagerController extends Controller
{
    private BoardGroupAdmin $boardGroupAdminModel;
    private User $userModel;

    public function __construct(BoardGroupAdmin $boardGroupAdmin, User $user)
    {
        $this->boardGroupAdminModel = $boardGroupAdmin;
        $this->userModel = $user;
    }

    /**
     * 게시판 그룹 관리자
     * @method GET
     * @see /admin/board/group/manager
     */
    public function show(int $boardGroupID)
    {
        $boardGroupAdminData = $this->boardGroupAdminModel->data();

        if ($boardGroupAdminData->rows > 0) {
            foreach ($boardGroupAdminData->list as $i => $row) {
                $boardGroupAdminData->list[$i] = $row;
            }
        }

        return view('admin.board.group.manager', [
            'actionURL' => route('admin.board.group.manager.store'),
            'boardGroupAdminData' => $boardGroupAdminData,
            'boardGroupID' => $boardGroupID
        ]);
    }

    /**
     * 게시판 그룹 관리자 등록 저장
     * @method POST
     * @see /admin/board/group/manager
     */
    public function store(Request $request)
    {
        $rules = [
            'board_group_id' => 'required|numeric|exists:tb_board_group,id',
            'sid' => 'required|exists:users,sid'
        ];

        $attributes = [
            'board_group_id' => '게시판 그룹 PK',
            'sid' => '회원 ID'
        ];

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

        $boardGroupID = $posts['board_group_id'];
        $sid = $posts['sid'];
        $userID = $this->userModel->where('sid', $sid)->value('id');

        // 이미 등록된 관리자인지 확인
        $isBoardAdmin = $this->boardGroupAdminModel->where('user_id', $userID)->count();
        if($isBoardAdmin) {
            return back()->withErrors(['sid' => "{$sid}는 이미 등록된 관리자 입니다."])->withInput();
        }

        $this->boardGroupAdminModel->insert([
            'board_group_id' => $boardGroupID,
            'user_id' => $userID,
            'created_at' => now()
        ]);

        $message = '게시판 그룹 관리자가 새로 등록되었습니다.';
        return redirect()->route('admin.board.group.manager.show', $boardGroupID)->with('message', $message);
    }

    /**
     * 게시판 그룹 관리자 삭제
     * @method DELETE
     * @see /admin/board/group/manager/destroy
     */
    public function destroy(Request $request)
    {
        $boardGroupID = $request->post('board_group_id');
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $boardGroupAdminID) {
                $this->boardGroupAdminModel->find($boardGroupAdminID)->delete();
            }
        }

        $message = '게시판 그룹 관리자 정보가 삭제되었습니다.';
        return redirect()->route('admin.board.group.manager.show', $boardGroupID)->with('message', $message);
    }
}
