<?php

namespace App\Http\Middleware\Prepare;

use Closure;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Cache;
use App\Models\Menu;
use App\Models\Visit;

class Front
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle($request, Closure $next)
    {
        // 사용자 메뉴 설정
        $menuModel = new Menu();
        $menuData = $menuModel->data();

        // 현재 메뉴 위치 조회
        if (!$ret = Cache::get($menuModel->cacheName_2)) {
            if ($menuData->rows > 0) {
                $ret = [
                    'topMenu' => [],
                    'subMenu' => []
                ];
                foreach ($menuData->list as $row) {
                    if (DEVICE_TYPE == DEVICE_TYPE_1) { // PC
                        if (!$row->desktop) {
                            continue;
                        }
                    } else { // MO
                        if (!$row->mobile) {
                            continue;
                        }
                    }
                    $row = $menuModel->findCategory($row->id);
                    $row->hasChildren = $row->children->count();
                    $row->isRoot = $row->isRoot();
                    $row->isLeaf = $row->isLeaf();
                    $row->url = url($row->link);
                    $row->target = ($row->target ? '_blank' : '_self');

                    $ret['topMenu'][$row->parent_id][] = $row;
                    $ret['subMenu'][$row->id] = $row;
                }
            }
            Cache::put($menuModel->cacheName_2, $ret, $menuModel->cacheTime);
        }

        View::share('topMenu', $ret['topMenu']);
        View::share('subMenu', $ret['subMenu']);

        // 평점·후기 index 확인값
        View::share('isReviewIndex', $request->routeIs('movie.review.index'));

        $visit = new Visit();
        $visit->register($request); // 방문자 수 기록

        View::share('visitorTodayCount', $visit->todayCount());  // 오늘
        View::share('visitorYesterdayCount', $visit->yesterdayCount()); // 어제
        View::share('visitorTotalCount', $visit->totalCount()); // 누적

        unset($menuData, $ret, $visit, $menuModel);

        return $next($request);
    }
}
