<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Video;
use App\User;
use App\Log;
use Illuminate\View\View;
use App\CountryDescription;
use App\VideoDescription;
use Illuminate\Http\Request;
use App\CategoryVideo;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\VideoRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class VideoController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/dashboard/videos';
    /** View folder */
    private $viewDirectory= 'admin.videos.';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('videos.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Video::latest()
            ->join('video_descriptions AS ad', 'videos.id', 'ad.video_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.name', 'videos.*']);

        if ($request->date_from) {
            $query->whereDate('videos.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('videos.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('ad.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->country) {
            $query->where('country_id', countryid($request->country));
        }
       

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $videos= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('videos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('videos.store');
        
        $head= __('videos.new');
        $users = User::cursor();
        return view( $this->viewDirectory.'form', compact('action', 'head','users') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param VideoRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(VideoRequest $request) :RedirectResponse
    {
        $video = Video::create($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'اضافة']);

        
        $this->saveData($request, $video->id);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Country $video
     * @return View
     */
    public function edit(Video $video) :View
    {
        $action= route('videos.update', $video->id);

        $query = VideoDescription::where('video_id', $video->id)
            ->join('languages', 'languages.id', 'video_descriptions.language_id')
            ->select(['video_descriptions.*', 'languages.local']);

        $videoDescription= $query->get();
        $users = User::cursor();
        foreach ($videoDescription as $row) {
            $video[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', compact('video', 'action','users') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param VideoRequest $request
     * @param Country $video
     * @return RedirectResponse|Redirector
     */
    public function update(VideoRequest $request, Video $video) :RedirectResponse
    {

        // Update image and category id if request has it
        $video->update($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'تعديل']);

        // update image to youtube api thumbnail if request have not image
       

        // Delete old description
        VideoDescription::where('video_id', $video->id)->delete();


        // Insert new description
        $this->saveData( $request, $video->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param VideoRequest $request
     * @param int $video_id
     * @return void
     */

    private function saveData(VideoRequest $request, int $video_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'video_id'=> $video_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                
            ];
            VideoDescription::create($data);
        }

        

    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $video = Video::withTrashed()->find($id);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'حذف']);
        if ($video) {
            if ($video->deleted_at) {
                $video->forceDelete();
            } else {
                $video->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'حذف']);
        if ($request->force) {
            Video::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Video::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $video = Video::withTrashed()->find($id);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'استرجاع']);

        if ($video){
            $video->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $video = Video::whereIn('id', $request->ids)->onlyTrashed();
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الفيديوهات','action'=>'استرجاع']);
        if ($video){
            $video->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
