<?php

namespace App\Http\Controllers\Web;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Video;
use App\VideoDescription;
use App\VideoCategory;
use App\VideoCategoryDescription;
use Illuminate\Http\Request;
use \Illuminate\Support\Str;
use Illuminate\View\View;

class VideoController extends Controller
{
    private $viewDirectory = 'web.videos.';
    
    
    /**
     * Show the Videos of category.
     * @param VideoCategory $category
     * @param Request $request
     * @return View
     */
    public function index(VideoCategory $category, Request $request): View
    {
        $categoryDescription= $category->currentDescription;
        // Check Slug is the same
        if ($request->slug && $request->slug != str_slug($categoryDescription->slug)) {
            abort(404);
        }
        //
        $videos= Video::latest()
            ->where('video_category_id', $category->id)
            ->paginate(30);

        $title= $categoryDescription->name ;
        $keywords= $categoryDescription->keywords ;
        $meta_description= $categoryDescription->meta_description ;

        return view($this->viewDirectory.'index', compact( 'videos', 'title', 'keywords', 'meta_description'));
    }

    /**
     * Show the Videos of category.
     * @return View
     */
    public function categories(): View
    {
        $query= VideoCategory::latest()->with(['currentDescription'])->get();

        $categories= [];

        if ($query) {
            $categories= $query->toArray();
        }

        foreach ($query as $key => $category) {
            $query= Video::orderby('id', 'DESC')
            ->where('video_category_id', $category->id)
            ->select(['image'])->limit(1)->first();

            $video=['image'=>''];
            if ($query) {
                $video= $query->toArray();
            }
            $categories[$key]['image']= ImageHelper::get($video['image']);
            $categories[$key]['url']= $category->url;
        }
        return view($this->viewDirectory.'categories', compact( 'categories' ));
    }
}
