<?php

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

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

class PostController extends Controller
{
    private Board $boardModel;
    private PostHistory $postHistoryModel;

    public function __construct(Board $board, PostHistory $postHistory)
    {
        $this->boardModel = $board;
        $this->postHistoryModel = $postHistory;
    }

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

        $postHistoryData = $this->postHistoryModel->data($params);

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

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

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

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

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

                    $postHistory = $this->postHistoryModel->findOrNew($historyID);

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

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

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