<?php

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

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

class ListController extends Controller
{
    private Board $boardModel;
    private PostLink $postLinkModel;

    public function __construct(Board $board, PostLink $postLink)
    {
        $this->boardModel = $board;
        $this->postLinkModel = $postLink;
    }

    /**
     * 게시판 > URL 클릭 > 목록
     * @method GET
     * @see /admin/board/link/list
     */
    public function index(Request $request)
    {
        $params = SearchData::fromRequest($request);
        $params->boardID = $request->get('board_id');

        $postLinkData = $this->postLinkModel->data($params);

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

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

        return view('admin.board.link.list', [
            'postLinkData' => $postLinkData,
            'params' => $params,
            'boardData' => $this->boardModel->all()
        ]);
    }

    /**
     * 게시판 > URL 클릭 > 목록 삭제
     * @method DELETE
     * @see /admin/board/link/list/destroy
     */
    public function destroy(Request $request)
    {
        try {

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

            if ($chk) {
                foreach ($chk as $postLinkID) {
                    $postLink = $this->postLinkModel->findOrNew($postLinkID);

                    if(!$postLink->exists) {
                        throw new Exception($postLinkID . '번 URL은 존재하지 않습니다.');
                    }

                    if(!$postLink->remove($postLinkID)) {
                        throw new Exception($postLinkID . "번 URL은 삭제할 수 없습니다.");
                    }
                }
            }

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