<?php

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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\AgentTrait;
use App\Models\Board;
use App\Models\PostLinkClickLog;
use App\Models\DTO\SearchData;
use Exception;

class LogController extends Controller
{
    use AgentTrait;

    private Board $boardModel;
    private PostLinkClickLog $postLinkClickLogModel;

    public function __construct(Board $board, PostLinkClickLog $postLinkClickLog)
    {
        $this->boardModel = $board;
        $this->postLinkClickLogModel = $postLinkClickLog;
    }

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

        $postLinkClickLogData = $this->postLinkClickLogModel->data($params);

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

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

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

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

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

            if ($chk) {
                foreach ($chk as $postLinkClickLogID) {
                    $postLinkClickLog = $this->postLinkClickLogModel->findOrNew($postLinkClickLogID);

                    if(!$postLinkClickLog->exists) {
                        throw new Exception($postLinkClickLogID . "번 URL 클릭 기록은 존재하지 않습니다.");
                    }

                    if(!$postLinkClickLog->delete()) {
                        throw new Exception($postLinkClickLogID . '번 URL 클릭 기록을 삭제할 수 없습니다.');
                    }
                }
            }

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