<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Models\Video;

use Auth, Toastr;
use App\Http\Requests\Admin\VideoRequest;

class VideoController extends CommonController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $videos = Video::paginate(20);
        return view('admin.video.index', compact('videos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.video.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(VideoRequest $request)
    {
        if ($data = $request->all()) {
            $video = Video::create($data);
            if ($video) {
                return redirect(route('admin.video'));
            } else {
                return back()->with('errors', ['视频添加失败!']);
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $video = Video::find($id);

        if(!$video) {
            Toastr::error('视频不存在');
            return redirect(route('admin.video'));
        }

        return view('admin.video.edit', compact('video'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(VideoRequest $request, $id)
    {
        $video = Video::find($id);
        if(!$video) {
            Toastr::error('视频不存在');
            return redirect(route('admin.video'));
        }

        if ($data = $request->all()) {
            $result = $video->update($data);
            if ($result) {
                return redirect()->route('admin.video');
            } else {
                return back()->with('errors', ['视频编辑失败!']);
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $video = Video::find($id);
        if(!$video) {
            return redirect()->route('admin.video')->with('errors', ['视频未找到!']);
        }
        $err = '视频删除成功';
        if(!$video->delete()){
            $err = '视频删除失败!';
        }
        return redirect()->route('admin.video')->with('errors', [$err]);
    }
}
