<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Http\Traits\CommonTrait;
use App\Models\Popup;
use App\Models\DTO\SearchData;
use App\Services\BoardService;

class MainController extends Controller
{
    use CommonTrait;

    private BoardService $boardService;
    private Popup $popupModel;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(BoardService $boardService, Popup $popupModel)
    {
        $this->middleware('front');
        $this->boardService = $boardService;
        $this->popupModel = $popupModel;
    }

    /**
     * Show the application dashboard.
     * @method GET
     * @see /
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        // 팝업
        $popups = $this->popupModel->list();

        // 최근 게시글
        $recent = $this->boardService->latest(null, 1, DEFAULT_LIST_PER_PAGE);

        // 공지사항
        $notice = $this->boardService->latest('notice', 1, DEFAULT_LIST_PER_PAGE);

        // 사진게시판
        $photo = $this->boardService->latest('photo', 1, DEFAULT_LIST_PER_PAGE);

        // 최신 뉴스
        $news = $this->_news();

        return view(layout('main'), [
            'popups' => $popups,
            'recent' => $recent,
            'notice' => $notice,
            'photo' => $photo,
            'news' => $news
        ]);
    }

    /**
     * 최신글 보기
     * @method GET
     * @see /recently
     */
    public function recently(Request $request)
    {
        $params = SearchData::fromRequest($request);

        $listURL = route('recently');

        // 최근 게시글
        if ($params->category || $params->keyword) {
            $recent = $this->boardService->search($params);
        } else {
            $recent = $this->boardService->latest(null, $params->page, $params->perPage);
        }

        return view(layout('recently'), [
            'recent' => $recent,
            'params' => $params,
            'listURL' => $listURL
        ]);
    }

    /**
     * 최신 뉴스 조회
     */
    private function _news()
    {
        // 뉴스
        if (!$news = Cache::get('mainNews')) {
            $response = Http::get('https://serpapi.com/search', [
                'q' => '주요 뉴스',
                'tbm' => 'nws',
                'api_key'=> SERP_API_KEY
            ]);

            if($response->ok()) {
                $news = $response->json('news_results');
                Cache::put('mainNews', $news, 86400);
            }
        }
        return $news;
    }
}
