<?php

namespace App\Http\Controllers\Admin\Board;

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

class PostController extends Controller
{
    private Board $boardModel;
    private BoardCategory $boardCategoryModel;
    private Post $postModel;

    public function __construct(Board $board, BoardCategory $boardCategory, Post $post)
    {
        $this->boardModel = $board;
        $this->boardCategoryModel = $boardCategory;
        $this->postModel = $post;
    }

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

        $postData = $this->postModel->data($params);

        if ($postData->rows > 0) {
            $num = listNum($postData->total, $params->page, $params->perPage);
            foreach ($postData->list as $i => $row) {
                $row->num = $num--;
                $row->postURL = route('board.post.view', [$row->code, $row->id]);
                $row->hits = number_format($row->hit);
                $row->hvFile = ($row->file_rows > 0);
                $row->hvImage = ($row->image_rows > 0);
                $row->device = MAP_DEVICE_ICON_TYPE[$row->device_type];
                $row->secret = ($row->is_secret > 0);

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

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

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

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

            if ($chk) {

                $user = $request->user();
                foreach ($chk as $postID) {
                    $post = $this->postModel->findOrNew($postID);

                    if(!$post->exists) {
                        throw new Exception($postID . '번 게시물은 존재하지 않습니다.');
                    }

                    if (!$this->postModel->remove($post, $user)) {
                        throw new Exception($postID . "번 게시물을 삭제할 수 없습니다.");
                    }
                }
            }

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