<?php

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

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

class CommentController extends Controller
{
    private Board $boardModel;
    private CommentHistory $commentHistoryModel;

    public function __construct(Board $board, CommentHistory $commentHistory)
    {
        $this->boardModel = $board;
        $this->commentHistoryModel = $commentHistory;
    }

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

        $commentHistoryData = $this->commentHistoryModel->data($params);

        if ($commentHistoryData->rows > 0) {
            $num = listNum($commentHistoryData->total, $params->page, $params->perPage);
            foreach ($commentHistoryData->list as $i => $row) {
                $row->num = $num--;
                $row->createdAt = dateBr($row->created_at, '-');

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

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

    /**
     * 게시판 > 댓글 변경 이력 삭제
     * @method DELETE
     * @see /admin/board/history/comment/destroy
     */
    public function destroy(Request $request)
    {
        try {
            $chk = $request->post('chk');

            if ($chk) {
                foreach ($chk as $i => $historyID) {

                    $commentHistory = $this->commentHistoryModel->findOrNew($historyID);

                    if(!$commentHistory->exists) {
                        throw new Exception($i . "번 변경 이력이 존재하지 않습니다.");
                    }

                    if(!$commentHistory->delete()) {
                        throw new Exception($i . "번 변경 이력을 삭제할 수 없습니다.");
                    }
                }
            }

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