<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\_Ads;
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\Str;
use File,Image;
use Illuminate\Support\Facades\Validator;

class Ads extends Controller
{
    public function indexNative()
    {
        $data = _Ads::where('ad_type','native')->paginate(20);
        return view('setting/ads/native-ad', compact('data'));
    }
    
    public function indexBanner()
    {
        $data = _Ads::where('ad_type','banner')->paginate(20);
        return view('setting/ads/banner-ad', compact('data'));
    }
    
    public function indexInter()
    {
        $data = _Ads::where('ad_type','inter')->paginate(20);
        return view('setting/ads/inter-ad', compact('data'));
    }
    
    public function edit(_Ads $id)
    {
        switch($id->ad_type){
            
            case 'banner':
                    return $id;
                break;
                
            case 'inter':
                    return $id;
                break;           
            
            case 'native':
                    return view('setting/ads/edit-native',['data'=>$id]);
                break;
        }
        
    }
    
    public function createNative()
    {
        return view('setting/ads/add-native');
    }


    public function indexAds()
    {
        $data = DB::table('tbl_setting')->where('id', 1)->first();
        $adcount=DB::table('ad_count')->where('date',date('Y-m-d'))->first();
        $adlimit=DB::table('ad_limit')->where('id',1)->first();
        return view('setting/ads/ads', ['ad' => $data, 'adcount' => $adcount,'adlimit'=>$adlimit]);
    }
    
    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]);
        }

        $validate = Validator::make($req->all(), [
            'image' => "required|mimes:jpeg,png,jpg",
        ],[
            'image'=>'Please Select valid Image Supported Jpeg/Png'
            ]);
        if ($validate->fails()) {
            return redirect()->back()->withErrors(['msgError' =>$validate->errors()->first()]);
        }
        
        if($req->ad_type == 'banner'){
  
            $file = $req->file('image');
            $thumb = uniqid().time().'.'.$file->getClientOriginalExtension();
            $location = public_path('images/');
            $file->move($location,$thumb); 
            
            $ad= new _Ads;
            $ad->image=$thumb;
            $ad->ad_type=$req->ad_type;
            $ad->url=$req->url;
            $res=$ad->save();
            
            if($res){
                  return redirect('/ads/banner')->with('success', 'Banner Ad Added Successfully!');
            }else{
                return redirect('/ads/banner')->with('error', 'Something went wrong!');
            }
        }
        else if($req->ad_type == 'inter'){
  
            $file = $req->file('image');
            $thumb = uniqid().time().'.'.$file->getClientOriginalExtension();
            $location = public_path('images/');
            $file->move($location,$thumb); 
            
            $ad= new _Ads;
            $ad->image=$thumb;
            $ad->ad_type=$req->ad_type;
            $ad->timer=$req->timer;
            $ad->url=$req->url;
            $res=$ad->save();
            
            if($res){
                  return redirect('/ads/interstital')->with('success', 'Banner Ad Added Successfully!');
            }else{
                return redirect('/ads/interstital')->with('error', 'Something went wrong!');
            }
        }
        else if($req->ad_type == 'native'){
        
            $validator = Validator::make($req->all(), [
                'title' => ['required'],
                'description' => ['required'],
                'icon' => ['required|mimes:jpeg,png,jpg'],
                'image' => ['required|mimes:jpeg,png,jpg'],
                'btn_name' => ['required'],
                'url' => ['required'],
            ]);
            
            if($validator->fails()){
                return back()->withErrors($validator->errors())->withInput();
            }
            
            $image = $req->icon;
            $extension = $image->getClientOriginalExtension();
            $fileNameToStore = uniqid() . '_' . time() . '.' . $extension;
            $image_resize = Image::make($image->getRealPath());
            $image_resize->resize(100,100);
            $image_resize->save('images/' . $fileNameToStore);
            
            $file = $req->file('image');
            $thumb = uniqid().time().'.'.$file->getClientOriginalExtension();
            $location = public_path('images/');
            $file->move($location,$thumb); 
            
            $ad= new _Ads;
            $ad->title=$req->title;
            $ad->description=$req->description;
            $ad->icon=$fileNameToStore;
            $ad->image=$thumb;
            $ad->btn_name=$req->btn_name;
            $ad->url=$req->url;
            $res=$ad->save();
            
            if($res){
                  return redirect('/ads/native')->with('success', 'Native Ad Added Successfully!');
            }else{
                return redirect('/ads/native')->with('error', 'Something went wrong!');
            }
        }
    }
    
    public function updateAd(Request $req){
        
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }

        if($req->file('image')){
            $validate = Validator::make($req->all(), [
                'image' => "required|mimes:jpeg,png,jpg",
            ],[
                'image'=>'Please Select valid Image Supported Jpeg/Png'
                ]);
            if ($validate->fails()) {
                return redirect()->back()->withErrors(['msgError' =>$validate->errors()->first()]);
            }
        }
        
        if($req->ad_type == 'banner'){
            
            if($req->file('image')){
                $file = $req->file('image');
                 $thumb = uniqid().time(). '.' . $file->getClientOriginalExtension();
                 $location = public_path('images/');
                 $file->move($location,$thumb); 
                 
                $image_path = "/images/" . $req->oldimage;
                if (File::exists($image_path)) {
                    File::delete($image_path);
                }
            }else{
                $thumb=$req->oldimage;
            }
            
            $ad= _Ads::find($req->id);
            $ad->image=$thumb;
            $ad->url=$req->url;
            $res=$ad->save();
            
            if($res){
                  return redirect('/ads/banner')->with('success', 'Banner Ad Update Successfully!');
            }else{
                return redirect('/ads/banner')->with('error', 'Something went wrong!');
            }
        }
        
        else if($req->ad_type == 'inter'){
            
            if($req->file('image')){
                $file = $req->file('image');
                 $thumb = uniqid().time(). '.' . $file->getClientOriginalExtension();
                 $location = public_path('images/');
                 $file->move($location,$thumb); 
                 
                $image_path = "/images/" . $req->oldimage;
                if (File::exists($image_path)) {
                    File::delete($image_path);
                }
            }else{
                $thumb=$req->oldimage;
            }
            
            $ad= _Ads::find($req->id);
            $ad->image=$thumb;
            $ad->ad_type=$req->ad_type;
            $ad->timer=$req->timer;
            $ad->url=$req->url;
            
            if($res){
                  return redirect('/ads/interstital')->with('success', 'Interstital Ad Update Successfully!');
            }else{
                return redirect('/ads/interstital')->with('error', 'Something went wrong!');
            }
        }
        
        else if($req->ad_type == 'native'){
            $validator = Validator::make($req->all(), [
                'title' => ['required'],
                'description' => ['required'],
                'oldicon' => ['required'],
                'oldimage' => ['required'],
                'btn_name' => ['required'],
                'url' => ['required'],
            ]);
        
            if($validator->fails()){
                return back()->withErrors($validator->errors())->withInput();
            }
            
            if($req->icon){
                
                $validate = Validator::make($req->all(), [
                    'icon' => "required|mimes:jpeg,png,jpg",
                ],[
                    'icon'=>'Please Select valid Image Supported Jpeg/Png'
                    ]);
                if ($validate->fails()) {
                    return redirect()->back()->withErrors(['msgError' =>$validate->errors()->first()]);
                }

                $image = $req->icon;
                $extension = $image->getClientOriginalExtension();
                $fileNameToStore = uniqid() . '_' . time() . '.' . $extension;
                $image_resize = Image::make($image->getRealPath());
                $image_resize->resize(100, 100);
                $image_resize->save('images/' . $fileNameToStore);
                $icon=$fileNameToStore;
                 $image_path = "/images/" . $req->oldicon;
                if (File::exists($image_path)) {
                    File::delete($image_path);
                }
            }else{
             $fileNameToStore=$req->oldicon; 
            }
            
            if($req->file('image')){
                $file = $req->file('image');
                 $thumb = uniqid().time(). '.' . $file->getClientOriginalExtension();
                 $location = public_path('images/');
                 $file->move($location,$thumb); 
                 
                $image_path = "/images/" . $req->oldimage;
                if (File::exists($image_path)) {
                    File::delete($image_path);
                }
            }else{
                $thumb=$req->oldimage;
            }
            
            $ad= _Ads::find($req->id);
            $ad->title=$req->title;
            $ad->description=$req->description;
            $ad->icon=$fileNameToStore;
            $ad->image=$thumb;
            $ad->btn_name=$req->btn_name;
            $ad->url=$req->url;
            $res=$ad->save();
            
            if($res){
                  return redirect('/ads/native')->with('success', 'Native Ad Update Successfully!');
            }else{
                return redirect('/ads/native')->with('error', 'Something went wrong!');
            }
            
        }

        
    }
    

    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]);
        }
        
    //   
    
        switch($req->type){
          
            case 'banner':
                
                $adsConfig=[
                    'banner_type' => $req->banner_type,
                    'banner_id' => $req->banner_id,
                    'native_type' => $req->native_type,
                    'native_id' => $req->native_id,
                    'native_count' => $req->native_count,
                    'interstital_count' => $req->interstital_count,
                    'interstital_type' => $req->interstital_type,
                    'backup_interstital_type' => $req->backup_interstital_type,
                    'direct_credit' => $req->direct_credit];
                    
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;
                
            
            case 'admob':
                
                $adsConfig=[
                    'admob_app_id' => $req->admob_app_id,
                    'admob_inter' => $req->admob_inter,
                    'admob_reward' => $req->admob_reward,
                    'admob_inter_id' => $req->admob_inter_id,
                    'admob_reward_id' => $req->admob_reward_id];
                    
                $adLimit=[
                    'admob_inter' => $req->limit_admob_inter,
                    'admob_reward' => $req->limit_admob_reward,
                    ];
                    
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;
                
            
            case 'applovin':
                
                $adsConfig=[
                    'applovin_inter' => $req->applovin_inter,
                    'applovin_reward' => $req->applovin_reward,
                    'applovin_inter_id' => $req->applovin_inter_id,
                    'applovin_reward_id' => $req->applovin_reward_id];
                    
                $adLimit=[
                    'applovin_inter' => $req->limit_applovin_inter,
                    'applovin_reward' => $req->limit_applovin_reward,
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;
                
                
            case 'fb':
                
                $adsConfig=[
                    'fb_inter' => $req->fb_inter,
                    'fb_reward' => $req->fb_reward,
                    'fb_inter_id' => $req->fb_inter_id,
                    'fb_reward_id' => $req->fb_reward_id];
                    
                $adLimit=[
                    'fb_inter' => $req->limit_fb_inter,
                    'fb_reward' => $req->limit_fb_reward,
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;    
            
            case 'ironsource':
                
                $adsConfig=[
                    'irons_key' => $req->irons_key,
                    'irons_inter' => $req->irons_inter,
                    'irons_reward' => $req->irons_reward];
                    
                $adLimit=[
                    'irons_inter' => $req->limit_irons_inter,
                    'irons_reward' => $req->limit_irons_reward,
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;  
                
                
            case 'unity':
                
                $adsConfig=[
                    'unity_game_id' => $req->unity_game_id,
                    'unity_inter' => $req->unity_inter,
                    'unity_reward' => $req->unity_reward,
                    'unity_inter_id' => $req->unity_inter_id,
                    'unity_reward_id' => $req->unity_reward_id];
                    
                $adLimit=[
                    'unity_inter' => $req->limit_unity_inter,
                    'unity_reward' => $req->limit_unity_reward,
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;    
                
                
            case 'wortise':
                
                $adsConfig=[
                    'wortise_key' => $req->wortise_key,
                    'wortise_inter' => $req->wortise_inter,
                    'wortise_reward' => $req->wortise_reward,
                    'wortise_inter_id' => $req->wortise_inter_id,
                    'wortise_reward_id' => $req->wortise_reward_id];
                    
                $adLimit=[
                    'wortise_inter' => $req->limit_wortise_inter,
                    'wortise_reward' => $req->limit_wortise_reward,
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;   
                
                
            case 'startio':
                
                $adsConfig=[
                    'startapp_appid' => $req->startapp_appid,
                    'start_auto_ad' => $req->start_auto_ad];
                    
                $adLimit=[
                    'startio' => $req->limit_startio
                    ];
                    
                DB::table('ad_limit')->where('id',1)->update($adLimit);  
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;
                
            case 'custom':
                
                $adsConfig=[
                    'custom_ad' => $req->custom_ad];
               
                DB::table('tbl_setting')->where('id', 1)->update($adsConfig);
                
                break;    
                
        }
        
        
        
        
        return redirect('/ads/setting#'.$req->type)->with('success', 'Update Successfully!');
       

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

        $ad =_Ads::find($id);
        
        $image_path = "/images/" . $ad->icon;
        if (File::exists($image_path)) {
            File::delete($image_path);
        }
        
        $image_path = "/images/" . $ad->image;
        if (File::exists($image_path)) {
            File::delete($image_path);
        }
        
        $ad->delete();
        return 1;
        
    }
    
    public function action(Request $req){
        
        if(auth()->user()->role_edit=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }

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

    public static function updateData($key, $value)
    {
        $path = base_path('.env');

        if (file_exists($path)) {

            file_put_contents($path, str_replace(
                $key . '=' . env($key),
                $key . '=' . $value,
                file_get_contents($path)
            ));
        }
    }
}
