<?php

namespace App\Http\Controllers\Admin\Board;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Board;
use App\Models\Comment;
use App\Models\DTO\SearchData;
use Exception;

class CommentController extends Controller
{
    private Board $boardModel;
    private Comment $commentModel;

    public function __construct(Board $board, Comment $comment)
    {
        $this->boardModel = $board;
        $this->commentModel = $comment;
    }

    /**
     * 게시판 관리 > 댓글 관리
     * @method GET
     * @see /admin/board/comment
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->boardID = $request->get('board_id');

        $commentData = $this->commentModel->data($params);

        if ($commentData->rows > 0) {
            $num = listNum($commentData->total, $params->page, $params->perPage);
            foreach ($commentData->list as $i => $row) {
                $row->num = $num--;
                $row->postURL = route('board.post.view', [$row->code, $row->post_id]);
                $row->page = $row->findPageNumber($row->board_id, $row->post_id, $row->id);
                $row->device = (MAP_DEVICE_ICON_TYPE[$row->device_type] ?? '');

                $commentData->list[$i] = $row;
            }
        }

        return view('admin.board.comment.index', [
            'commentData' => $commentData,
            'boardData' => $this->boardModel->all(),
            'params' => $params
        ]);
    }

    /**
     * 게시판 관리 > 댓글 삭제
     * @method DELETE
     * @see /admin/board/comment/destroy
     */
    public function destroy(Request $request)
    {
        try {

            $chk = $request->post('chk');

            if ($chk) {

                $user = $request->user();
                foreach ($chk as $commentID) {
                    $comment = $this->commentModel->findOrNew($commentID);

                    if(!$comment->exists) {
                        throw new Exception($commentID . '번 댓글은 존재하지 않습니다.');
                    }

                    if (!$this->commentModel->remove($comment, $user)) {
                        throw new Exception($commentID . "번 댓글을 삭제할 수 없습니다.");
                    }
                }
            }

            $message = '댓글이 삭제되었습니다.';
            return redirect()->route('admin.board.comment.index')->with('message', $message);
        } catch (Exception $e) {
            return back()->withErrors($e->getMessage())->withInput();
        }
    }
}
