<?php

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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\AgentTrait;
use App\Models\Board;
use App\Models\Comment;
use App\Models\CommentLike;
use App\Models\DTO\SearchData;

class CommentController extends Controller
{
    use AgentTrait;

    private Board $boardModel;
    private CommentLike $commentLikeModel;

    public function __construct(Board $board, CommentLike $commentLike)
    {
        $this->boardModel = $board;
        $this->commentLikeModel = $commentLike;
    }

    /**
     * 댓글 > 추천/비추 조회
     * @method GET
     * @see /admin/board/like/comment
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->boardID = $request->post('board_id');

        $likeData = $this->commentLikeModel->data($params);

        if ($likeData->rows > 0) {
            $num = listNum($likeData->total, $params->page, $params->perPage);
            foreach ($likeData->list as $i => $row) {
                $row->num = $num--;
                $row->status = ($row->type == 1 ? '추천' : '비추천');
                $row->postURL = route('board.post.view', [$row->code, $row->post_id]);
                $row->editURL = route('admin.board.like.comment.edit', $row->id);

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

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

    /**
     * 댓글 > 추천/비추 삭제
     * @method DELETE
     * @see /admin/board/like/comment/destroy
     */
    public function destroy(Request $request, Comment $commentModel)
    {
        $chk = $request->post('chk');

        if ($chk) {
            foreach ($chk as $i => $likeID) {
                $like = $this->commentLikeModel->find($likeID);

                // 추천 수 감소
                if($like->type == 1) {
                    $commentModel->decreaseLike($like->comment_id);
                }else{
                    $commentModel->decreaseDisLike($like->comment_id);
                }

                if(!$like->delete()) {
                    return back()->withErrors("{$i}번 추천/비추 기록을 삭제할 수 없습니다.")->withInput();
                }
            }
        }

        $message = '댓글 추천/비추 기록이 삭제되었습니다.';
        return redirect()->route('admin.board.like.comment.index')->with('message', $message);
    }

    /**
     * 댓글 > 추천/비추천 상세 보기
     * @method GET
     * @see /admin/board/like/{pk}/edit
     */
    public function edit(int $likeID)
    {
        $like = $this->commentLikeModel->findOrFail($likeID);
        $like->device = $this->device($like->user_agent);
        $like->platform = $this->platform($like->user_agent);
        $like->browser = $this->browser($like->user_agent);

        return view('admin.board.like.comment.edit', [
            'like' => $like
        ]);
    }
}
