<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\Slider;
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 Image;
use File;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
class Games extends Controller
{

    
    public function indexGame()
    {
        $adaction=DB::table('btn_action')->where('cat','ad')->get();
        $data = DB::table('games')->where('game_type',0)->orderBy('id', 'DESC')->paginate();
        return view('pages/game', ['data'=>$data,'ad'=>$adaction]);
    }
    
    public function indexTaskGame()
    {
        $data = DB::table('games')->where('game_type',1)->orderBy('id', 'DESC')->paginate();
        return view('pages/game-task', compact('data'));
    }

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

        $validate = Validator::make($request->all(), [
            'icon' => "required|mimes:jpeg,png,jpg",
        ],[
            'icon'=>'Please Select valid Image Supported Jpeg/Png'
            ]);
        if ($validate->fails()) {
            return redirect('/games')->with('error', $validate->errors()->first());
        }

        $image = $request->icon;
        $filenameWithExt = $image->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $filename = preg_replace("/[^A-Za-z0-9 ]/", '', $filename);
        $filename = preg_replace("/\s+/", '-', $filename);
        $extension = $image->getClientOriginalExtension();
        $fileNameToStore = $filename . '_' . time() . '.' . $extension;
        $image_resize = Image::make($image->getRealPath());
        $image_resize->resize(200, 200);
        $save = $image_resize->save('images/games/' . $fileNameToStore);

        if ($save) {
            $res = DB::table('games')->insert([
                'title' => $request->title,
                'link' => $request->link,
                'image' => $fileNameToStore,
                'game_type' => 0,
                'description' => $request->description,
                'time' => $request->time,
                'game_coin' => $request->game_coin,
                'ad_type' => $request->ad_type,
                'created_at' => Carbon::now()
            ]);

            if ($res) {
                return redirect('/games')->with('success', 'Added Successfully!');
            } else {
                return redirect('/games')->with('error', 'Technical Error!');
            }
        } else {
            return redirect('/games')->with('error', 'Imagem not uploaded!');
        }
    }
    
    
    public function storeTaskGame(Request $request)
    {
        if(auth()->user()->role_create=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }

        $validate = Validator::make($request->all(), [
            'icon' => "required|mimes:jpeg,png,jpg",
        ],[
            'icon'=>'Please Select valid Image Supported Jpeg/Png'
            ]);
        if ($validate->fails()) {
            return redirect('/games')->with('error', $validate->errors()->first());
        }

        $image = $request->icon;
        $filenameWithExt = $image->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $filename = preg_replace("/[^A-Za-z0-9 ]/", '', $filename);
        $filename = preg_replace("/\s+/", '-', $filename);
        $extension = $image->getClientOriginalExtension();
        $fileNameToStore = uniqid(). '_' . time() . '.' . $extension;
        $image_resize = Image::make($image->getRealPath());
        $image_resize->resize(200, 200);
        $save = $image_resize->save('images/games/' . $fileNameToStore);
        
        if($request->background){
            $image1 = $request->background;
            $filenameWithExt1 = $image->getClientOriginalName();
            $filename1 = pathinfo($filenameWithExt1, PATHINFO_FILENAME);
            $filename1 = preg_replace("/[^A-Za-z0-9 ]/", '', $filename1);
            $filename1 = preg_replace("/\s+/", '-', $filename1);
            $extension1 = $image1->getClientOriginalExtension();
            $fileNameToStore1 = uniqid() . '_' . time() . '.' . $extension1;
            $image_resize1 = Image::make($image1->getRealPath());
            $image_resize1->resize(400,800);
            $image_resize1->save('images/games/' . $fileNameToStore1);
        }
        

        if ($save) {
            $res = DB::table('games')->insert([
                'title' => $request->title,
                'image' => $fileNameToStore,
                'background' => $fileNameToStore1,
                'game_type' => 1,
                'ad_type' => $request->ad_type,
                'anim_off' => $request->anim_off,
                'anim_play' => $request->anim_play,
                'game_limit' => $request->game_limit,
                'game_coin' => $request->game_coin,
                'created_at' => Carbon::now()
            ]);

            if ($res) {
                return redirect('/games/task')->with('success', 'Task Game Added Successfully!');
            } else {
                return redirect('/games/task')->with('error', 'Technical Error!');
            }
        } else {
            return redirect('/games/task')->with('error', 'Imagem not uploaded!');
        }
    }

    public function editGame($id)
    {
        return DB::table('games')->where('id', $id)->get();
    }

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

        $fileNameToStore="";
        $fileNameToStore1="";
        if($request->icon){

            $validate = Validator::make($request->all(), [
                'icon' => "required|mimes:jpeg,png,jpg",
            ],[
                'icon'=>'Please Select valid Image Supported Jpeg/Png'
                ]);
            if ($validate->fails()) {
                return redirect('/games')->with('error', $validate->errors()->first());
            }

            $image = $request->icon;
            $filenameWithExt = $image->getClientOriginalName();
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $filename = preg_replace("/[^A-Za-z0-9 ]/", '', $filename);
            $filename = preg_replace("/\s+/", '-', $filename);
            $extension = $image->getClientOriginalExtension();
            $fileNameToStore = uniqid(). '_' . time() . '.' . $extension;
            $image_resize = Image::make($image->getRealPath());
            $image_resize->resize(200, 200);
            $image_resize->save('images/games/' . $fileNameToStore);
        }else{
            $fileNameToStore=$request->old_icon;

        }

        if($request->background){

            $validate = Validator::make($request->all(), [
                'background' => "required|mimes:jpeg,png,jpg",
            ],[
                'background'=>'Please Select valid Image Supported Jpeg/Png'
                ]);
            if ($validate->fails()) {
                return redirect('/games')->with('error', $validate->errors()->first());
            }

            $image1 = $request->background;
            $filenameWithExt1 = $image->getClientOriginalName();
            $filename1 = pathinfo($filenameWithExt1, PATHINFO_FILENAME);
            $filename1 = preg_replace("/[^A-Za-z0-9 ]/", '', $filename1);
            $filename1 = preg_replace("/\s+/", '-', $filename1);
            $extension1 = $image1->getClientOriginalExtension();
            $fileNameToStore1 = uniqid() . '_' . time() . '.' . $extension1;
            $image_resize1 = Image::make($image1->getRealPath());
            $image_resize1->resize(400,800);
            $image_resize1->save('images/games/' . $fileNameToStore1);
        }else{
            $fileNameToStore1=$request->old_background;
        }
        

            $res = DB::table('games')->where('id', $request->id)->update([
                'title' => $request->title,
                'image' => $fileNameToStore,
                'background' => $fileNameToStore1,
                'game_type' => 1,
                'ad_type' => $request->ad_type,
                'anim_off' => $request->anim_off,
                'anim_play' => $request->anim_play,
                'game_limit' => $request->game_limit,
                'game_coin' => $request->game_coin,
                'created_at' => Carbon::now()
            ]);

            if ($res) {
                return redirect('/games/task')->with('success', 'Game Update Successfully!');
            } else {
                return redirect('/games/task')->with('error', 'Technical Error!');
            }
       
    }
    
    public function updateGame(Request $request){
        
            if(auth()->user()->role_edit=='false'){
                return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
            }

          if ($request->icon) {

            $validate = Validator::make($request->all(), [
                'icon' => "required|mimes:jpeg,png,jpg",
            ],[
                'icon'=>'Please Select valid Image Supported Jpeg/Png'
                ]);
            if ($validate->fails()) {
                return redirect('/games')->with('error', $validate->errors()->first());
            }

            $image = $request->icon;
            $filenameWithExt = $image->getClientOriginalName();
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $filename = preg_replace("/[^A-Za-z0-9 ]/", '', $filename);
            $filename = preg_replace("/\s+/", '-', $filename);
            $extension = $image->getClientOriginalExtension();
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            $image_resize = Image::make($image->getRealPath());
            $image_resize->resize(200, 200);
            $save = $image_resize->save('images/games/' . $fileNameToStore);
            $image_path = "/images/" . $request->oldicon;
            if (File::exists($image_path)) {
                File::delete($image_path);
            }

            $icon = $fileNameToStore;
        } else {
            $icon = $request->oldicon;
        }


        if ($icon) {
            $res = DB::table('games')->where('id', $request->id)->update([
                'title' => $request->title,
                'link' => $request->link,
                'image' => $icon,
                'game_type' => 0,
                'description' => $request->description,
                'time' => $request->time,
                'game_coin' => $request->game_coin,
                'ad_type' => $request->ad_type,
                'created_at' => Carbon::now()
            ]);

            if ($res) {
                return redirect('/games')->with('success', 'Update Successfully!');
            } else {
                return redirect('/games')->with('error', 'Technical Error!');
            }
        } else {
            return redirect('/games')->with('error', 'Imagem not uploaded!');
        }
        
    }


    public function destroyGame($id)
    {
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        $banner = DB::table('games')->where('id', $id)->get()->first()->image;
        $image_path = "/images/games/" . $banner;
        if (File::exists($image_path)) {
            File::delete($image_path);
        }
        DB::table('games')->where('id', $id)->delete();
        return 1;
    }

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

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




}