<?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\Movie\MovieReview;
use App\Models\DTO\SearchData;
use App\Services\BoardService;

class MainController extends Controller
{
    use CommonTrait;

    private BoardService $boardService;
    private Popup $popupModel;
    private MovieReview $movieReviewModel;

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

    /**
     * 메인 페이지
     * @method GET
     * @see /
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        // 팝업
        $popups = $this->popupModel->list();

        // 현재 상영작
        $nowPlaying = $this->_nowPlaying();

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

        // 평점·후기
        $review = $this->_review($request);

        // 인기 영화
        $trending = $this->_trending();

        return view(layout('main'), [
            'popups' => $popups,
            'nowPlaying' => $nowPlaying,
            'notice' => $notice,
            'review' => $review,
            'trending' => $trending
        ]);
    }

    /**
     * 현재 상영작
     */
    private function _nowPlaying(): object
    {
        return $this->_requestTMDB(TMDB_HOST . TMDB_GET_NOW_PLAYING);
    }

    /**
     * 최근 평점·후기 목록
     */
    private function _review(Request $request): object
    {
        $cacheName = 'latest-review';
        if (!$latest = Cache::get($cacheName)) {
            $params = SearchData::fromRequest($request);
            $params->sort = 2;
            $latest = $this->movieReviewModel->list($params);

            if ($latest->total) {
                $num = listNum($latest->total, $params->page, $params->perPage);
                foreach ($latest->list as $i => $row) {
                    $row->num = $num--;
                    $row->viewURL = route('movie.review.show', base64_encode($row->movie_cd));
                    $row->createdAt = $this->dateFormat($row->created_at, 'Y.m.d');
                    $latest->list[$i] = $row;
                }
                $latest->list->filter();
                $latest->pagination = null;
                Cache::tags('latest-review')->put($cacheName, $latest, CACHE_EXPIRE_TIME);
            }
        }
        return $latest;
    }

    /**
     * 최신 트랜딩
     */
    private function _trending(): object
    {
        return $this->_requestTMDB(sprintf(TMDB_HOST . TMDB_TRENDING, 'movie', 'day'));
    }

    /**
     * 최신 트랜딩
     */
    private function _requestTMDB(string $host): object
    {
        if (!$ret = Cache::get($host)) {
            // 곧 개봉 예정
            $response = Http::get($host, [
                'api_key' => TMDB_API_KEY,
                'language' => 'ko',
                'region' => 'kr'
            ]);

            $list = [];

            if ($response->ok()) {
                foreach (json_decode($response->body())->results as $row) {
                    $row->posterURL = ('https://image.tmdb.org/t/p/original' . $row->poster_path);
                    $row->backdropURL = ('https://image.tmdb.org/t/p/original' . $row->backdrop_path);
                    $row->releaseDate = date('Y.m.d', strtotime($row->release_date));
                    $row->voteAverage = round($row->vote_average, 2);
                    $list[] = $row;
                }
            }

            $ret = (object) ['total' => count($list), 'list' => $list];

            Cache::put($host, $ret, CACHE_EXPIRE_TIME);
        }

        return $ret;
    }
}
