<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Video;
use App\Models\Setting;
use App\Models\VideoCate;

class VideoController extends FrontendController
{
    use \App\Traits\ControllerTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $pageNum  = Setting::get('video_paginate') ?: 20;
        $video = Video::flag()->latest()->paginate($pageNum);

        $title = self::title('videos', 'system');
        $seo = self::meta($title);
 
        return view('theme::video', compact('video', 'seo'));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function lists($cid)
    {
        $cate = VideoCate::with('description')->flag()->where('slug', $cid)->first();

        if (!$cate) {
            return response()->view('theme::404', ['message' => 'Page not found !'], 404);
        }
        if (!$cate->isRoot()) {
            $root   = $cate->getRoot();
            $rootId = $root->id;
        } else {
            $rootId = $cate->id;
        }
        $pageNum  = Setting::get('video_paginate') ?: 20;
        $idArr    = $cate->getDescendantsAndSelf(['id'])->pluck('id')->toArray();
        $video    = Video::with(['cates', 'description'])->flag()->whereIn('pid', $idArr)->latest()->paginate($pageNum);

        $title = '';
        if ($cate->description) {
            $title = $cate->description->seo_title ?: $cate->description->cname;
        }

        $seo = self::meta($title, $cate->description);

        return view('theme::video_list', compact('video', 'seo', 'cate', 'rootId'));
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function details($id)
    {
        $video = Video::with(['cates.description', 'description'])->flag()->where('slug', $id)->first();

        if (!$video) {
            return response()->view('theme::404', ['message' => 'Page not found !'], 404);
        }

        if (!$video->cates->isRoot()) {
            $root   = $video->cates->getRoot();
            $rootId = $root->id;
        } else {
            $rootId = $video->cates->id;
        }

        $tags = $video->tags()->with('description')->get();

        $result  = Video::find($video->id)->update(['hits' => $video->hits + 1]);

        $title = '';
        if ($video->description) {
            $title = $video->description->seo_title ?: $video->description->title;
        }
        
        $seo = self::meta($title, $video->description);

        return view('theme::video_detail', compact('video', 'seo', 'tags', 'rootId'));
    }

   
}
