<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\Video;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class VideoZone extends Controller
{
    public function index()
    {
        $data = Video::where('status','=',0)->orwhere('status','=',2)->orderBy('id','DESC')->paginate();
        return view('video.video-management', compact('data'));
    }

    public function indexComplete()
    {
        $data = Video::where('status','=',1)->orderBy('id','DESC')->paginate();
        return view('video.complete', compact('data'));
    }


    public function pendingApproval()
    {
        $data = Video::where('status','=',3)->paginate();
        return view('promotion.pending-video', compact('data'));
    }


    public function create(){
        $ad=DB::table('btn_action')->where('cat','ad')->orderBy('type','ASC')->get();
        return view('video.add',['ad'=>$ad]);
    }

    public function store(Request $req){
        if(auth()->user()->role_create=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }


        preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $req->url, $match);

        $validator = Validator::make($req->all(), [
            'title' => ['required'],
            'timer' => ['required'],
            'point' => ['required'],
            'country' => ['required'],
            'thumb' => ($match) ? '' : ['required'],
            'url' => ['required'],
            'task_limit' => ['required'],
        ]);

        if($validator->fails()){
            return back()->withErrors($validator->errors())->withInput();
        }

        $thumb="";

        if($match){
            $thumb = 'http://img.youtube.com/vi/'.$match[1].'/sddefault.jpg';
        }else if($req->thumb!=null){
            $thumb = $req->thumb;
        }

        $video= new Video;
        $video->title=$req->title;
        $video->thumb=$thumb;
        $video->timer=$req->timer;
        $video->point=$req->point;
        $video->country=$req->country;
        $video->ad_type=$req->ad_type;
        $video->action_type=$req->action_type;
        $video->expire_at=$req->expired_at;
        $video->task_limit=$req->task_limit;
        $video->url=$req->url;
        $res=$video->save();
        if($res){
            return redirect('/videozone/active')->with('success', ' Video Task Added Successfully!');
        }else{
            return redirect('/videozone/add')->with('error', 'Technical Error!');
        }
    }

    public function edit(Video $id){
        $ad=DB::table('btn_action')->where('cat','ad')->orderBy('type','ASC')->get();
        return view('video/edit',['data'=>$id,'ad'=>$ad]);
    }

    public function update(Request $req){

        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }

        preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $req->url, $match);

        $validator = Validator::make($req->all(), [
            'title' => ['required'],
            'timer' => ['required'],
            'point' => ['required'],
            'country' => ['required'],
            'thumb' => ($match) ? '' : ['required'],
            'url' => ['required'],
            'task_limit' => ['required'],
        ]);

        if($validator->fails()){
            return back()->withErrors($validator->errors())->withInput();
        }

        $thumb="";

        if($match){
            $thumb = 'http://img.youtube.com/vi/'.$match[1].'/sddefault.jpg';
        }else if($req->thumb!=null){
            $thumb = $req->thumb;
        }


        $video= Video::find($req->id);
        $video->title=$req->title;
        $video->thumb=$thumb;
        $video->timer=$req->timer;
        $video->point=$req->point;
        $video->country=$req->country;
        $video->ad_type=$req->ad_type;
        $video->action_type=$req->action_type;
        $video->task_limit=$req->task_limit;
        $video->expire_at=$req->expired_at;
        $video->url=$req->url;
        $res=$video->save();
        if($res){
            return redirect('/videozone/active')->with('success', ' Video Update Successfully!');
        }else{
            return redirect('/videozone/add')->with('error', 'Technical Error!');
        }
    }


    public function destroy($id){
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        video::where('id',$id)->delete();
        return 1;
    }

    public function action(Request $req){

        if($req->status=="delete"){
            if(auth()->user()->role_delete=='false'){
                return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
            }
            $update =video::whereIn('id',explode(",",$req->id))->delete();
            if($update){
                return 1;
            }else{
                return "not updated";
            }
        }
        else{

        if(auth()->user()->role_edit=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }

        if($req->status=="enable"){
            $update =video::whereIn('id',explode(",",$req->id))->update(['status'=>0]);
            if($update){
                return 1;
            }else{
                return "not updated";
            }
        }
        else if($req->status=="disable"){
            $update =video::whereIn('id',explode(",",$req->id))->update(['status'=>2]);
            if($update){
                return 1;
            }else{
                return "not updated";
            }
        }else if($req->status=="approve"){
            $update =video::whereIn('id',explode(",",$req->id))->update(['status'=>0]);
            if($update){
                return 1;
            }else{
                return "not updated";
            }
        }else if($req->status=="delete"){
            $update =video::whereIn('id',explode(",",$req->id))->delete();
            if($update){
                return 1;
            }else{
                return "not updated";
            }
        }
        }
    }


    // public function notifyUser($type,$id,$reason){
    //     $token=Users::find($id);
    //     $userId=$token->p_token;
    //     $name=$token->name;

    //     if($type=="Reject"){
    //        $title= $name." Your Redeem Request has been Rejected";
    //         $message =$reason;

    //     }else if($type=="Success"){
    //        $title=$name." Your Redeem Request has been Approved";
    //         $message =$reason;
    //     }

    // if($userId){
    //   $res=  OneSignal::sendNotificationToUser(
    //         $message,
    //         $userId,
    //         $url = null,
    //         $data = null,
    //         $buttons = null,
    //         $schedule = null,
    //         $headings = $title,
    //         $subtitle = null
    //     );
    // }
    // }

}
