<?php

namespace App\Http\Controllers\Admin\Board;

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

class TagController extends Controller
{
    private Board $boardModel;
    private PostTag $postTagModel;

    public function __construct(Board $board, PostTag $postTag)
    {
        $this->boardModel = $board;
        $this->postTagModel = $postTag;
    }

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

        $postTagData = $this->postTagModel->data($params);

        if ($postTagData->rows > 0) {
            $num = listNum($postTagData->total, $params->page, $params->perPage);
            foreach ($postTagData->list as $i => $row) {
                $row->num = $num--;
                $row->postURL = route('board.post.view', [$row->code, $row->post_id]);

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

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

    /**
     * 게시판 > 태그 삭제
     * @method DELETE
     * @see /admin/board/tag/destroy
     */
    public function destroy(Request $request, Post $postModel)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $tagID) {
                    $postTag = $this->postTagModel->findOrNew($tagID);

                    if (!$postTag->exists) {
                        throw new Exception($tagID . '번 태그는 존재하지 않습니다.');
                    }

                    if (!$postTag->delete()) {
                        throw new Exception($tagID . "번 태그를 삭제할 수 없습니다.");
                    }

                    // 게시글 태그 수 갱신
                    $postModel->updateTagRows($postTag->post_id);
                }
            }

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