<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\_Onboarding;
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 App\Http\Controllers\Fun;
use Illuminate\Support\Facades\Validator;
class Setting extends Controller
{


    public function indexFraud()
    {
        $data = DB::table('fraud_prevention')->where('id', 1)->get();
        return view('setting/security', compact('data'));
    }

    public function indexAdmin()
    {
        $data = DB::table('users')->where('id', 1)->get();
        return view('setting/admin', compact('data'));
    }

    public function indexConfiguration()
    {
            $key=DB::table('admin_key')->where('id',1)->select('cron_secret','offer_secret')->get();
        if($key[0]->cron_secret==null && $key[0]->offer_secret==null){
            DB::table('admin_key')->where('id',1)->update(['cron_secret'=>Str::random(15),'offer_secret'=>Str::random(15)]);
            
            $key=DB::table('admin_key')->where('id',1)->select('cron_secret','offer_secret')->get();

        }

        return view('setting/config',['key'=>$key]);
    }

    public function indexAds()
    {
        $data = DB::table('tbl_setting')->where('id', 1)->get();
        return view('setting/ads/ads', ['data' => $data]);
    }

    public function indexApp()
    {
        $data = DB::table('tbl_app_setting')->where('id', 1)->get();
        $social = DB::table('links')->paginate();

        $spin = DB::table('spin_wheel')->get();
        $setting = DB::table('tbl_setting')->where('id', 1)->get();
        $mission = DB::table('daily_mission')->get();
        $ads=DB::table('btn_action')->where('cat','ad')->get();
        $task=DB::table('subscriptions')->where('id','1')->first();

        $daily = json_decode($data[0]->dailybonus);
        $db = DB::table('admin_key')->where('id',1)->select('ads_txt','privacy_policy')->get();


        return view('/setting/app', [
            'data' => $data,
            'daily' => $daily,
            'spin' => $spin,
            'setting' => $setting,
            'social' => $social,
            'mission' => $mission,
            'ads'=>$ads,
            'db'=>$db,
            'task'=>$task
        ]);
    }

    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]);
        }
       

        if ($req->type == "daily") {
            $dailybonus = array([
                'd1' => $req->day1,
                'd2' => $req->day2,
                'd3' => $req->day3,
                'd4' => $req->day4,
                'd5' => $req->day5,
                'd6' => $req->day6,
                'd7' => $req->day7
            ]);

            DB::table('tbl_app_setting')->where('id', 1)->update(['dailybonus' => json_encode($dailybonus)]);

            return redirect('/setting/app#daily')->with('success', 'Update Successfully!');
        } else if ($req->type == "spin") {

            DB::table('tbl_app_setting')->where('id', 1)->update([
                'spin_interval' => $req->spin_interval,
                'spin_adinterval' => $req->spin_adinterval,
                'spin_ad' => $req->spin_ad
            ]);

            return redirect('/setting/app#lucky')->with('success', 'Update Successfully!');
        } else if ($req->type == "security") {

            DB::table('fraud_prevention')->where('id', 1)->update([
                'block_vpn' => ($req->block_vpn == 'on') ? 'true' : 'false',
                'vpn_monitor' => ($req->vpn_monitor == 'on') ? 'true' : 'false',
                'auto_banVpn' => ($req->auto_banVpn == 'on') ? 'true' : 'false',
                'block_root_device' => ($req->block_root_device == 'on') ? 'true' : 'false',
                'auto_banroot' => ($req->auto_banroot == 'on') ? 'true' : 'false',
                'onedevice' => ($req->onedevice == 'on') ? 'true' : 'false',
                'app_clonning' => ($req->app_clonning == 'on') ? 'true' : 'false',
                'block_emulator' => ($req->block_emulator == 'on') ? 'true' : 'false',
                'block_termux' => ($req->block_termux == 'on') ? 'true' : 'false',
                'block_devMode' => ($req->block_devMode == 'on') ? 'true' : 'false',
                'vpn_required' => ($req->vpn_required == 'on') ? 'true' : 'false',
                'block_country' => ($req->block_country == 'on') ? 'true' : 'false',
                'oneip_device' => $req->oneip_device,
                'vpn_required_msg' => $req->vpn_required_msg,
                'block_country_msg' => $req->block_country_msg,
                'block_country_iso' => $req->block_country_iso
            ]);

            return redirect('/setting/fraud-prevention')->with('success', 'Update Successfully!');
        } else if ($req->type == "admin") {

            $admin = DB::table('users')->where('id', 1)->get();

            if (!Hash::check($req->oldpass, $admin[0]->password)) {
                return redirect()->back()->withErrors(['msgError' => 'Old Password not Matched.']);
            }

            if ($req->newpass != $req->cnpass) {
                return redirect()->back()->withErrors(['msgError' => 'Old Password and New Password Matched.']);
            }

            DB::table('users')->where('id', 1)->update([
                'email' => $req->email,
                'password' => Hash::make($req->newpass)
            ]);

            return redirect('/setting/admin-profile')->with('success', 'Update Successfully!');
        } else if ($req->type == "package") {

            $licence = base64_encode($req->licence);
            $package = base64_encode($req->package);


            $curl_handle = curl_init();
            curl_setopt($curl_handle, CURLOPT_URL, base64_decode('aHR0cHM6Ly9saWNlbmNlLnRlY2huaWNhbHN1bWVyLmNvbS9nZXRkYXRhbmFtZS5waHA/Y3BuPQ==') . $req->licence);
            curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
            $query = curl_exec($curl_handle);
            $data = json_decode($query, true);
            curl_close($curl_handle);


            $pac = $data["lists"][0]["package"];
            $lice = $data["lists"][0]["purchase_code"];

            if ($pac == $req->package && $lice == $req->licence) {

                $res = DB::table('users')->where('id', 1)->update([
                    'license' => $req->package,
                    'status' => 1,
                    'purchase_code' => $req->licence
                ]);

                if ($res) {
                    return redirect('/setting/admin-profile')->with('success', 'Purchase Detail Verify Successfully!');
                } else {
                    return redirect()->back()->withErrors(['msgError' => 'Error While Update Data !!!.']);
                }
            } else {
                return redirect()->back()->withErrors(['msgError' => 'Purchase Details Not Found!!.']);
            }
        } else if ($req->type == "smtp") {

            $this->updateData('MAIL_MAILER', $req->MAIL_MAILER);
            $this->updateData('MAIL_HOST', $req->MAIL_HOST);
            $this->updateData('MAIL_PORT', $req->MAIL_PORT);
            $this->updateData('MAIL_USERNAME', $req->MAIL_USERNAME);
            $this->updateData('MAIL_PASSWORD', $req->MAIL_PASSWORD);
            $this->updateData('MAIL_ENCRYPTION', $req->MAIL_ENCRYPTION);
            $this->updateData('MAIL_FROM_ADDRESS', $req->MAIL_USERNAME);

            \Artisan::call('config:clear');

            return redirect('/setting/app-configuration')->with('success', 'Update Successfully!');
        } else if ($req->type == "notification") {

            $this->updateData('ONESIGNAL_APP_ID', $req->ONESIGNAL_APP_ID);
            $this->updateData('ONESIGNAL_REST_API_KEY', $req->ONESIGNAL_REST_API_KEY);
            \Artisan::call('config:clear');

            return redirect('/setting/app-configuration')->with('success', 'Update Successfully!');
        } else if ($req->type == "server") {

            if ($req->APP_ENV == "local") {
                $this->updateData('APP_DEBUG', 'true');
                $this->updateData('APP_ENV', 'local');
            } else {
                $this->updateData('APP_DEBUG', 'false');
                $this->updateData('APP_ENV', 'production');
            }
            
            $this->updateData('APP_URL', $req->APP_URL);

            \Artisan::call('config:clear');

            return redirect('/setting/app-configuration')->with('success', 'Update Successfully!');
        } else if ($req->type == "scratch") {
            DB::table('tbl_app_setting')->where('id', 1)->update([
                'scratch_coin' => $req->scratch_coin,
                'scratch_interval' => $req->scratch_interval,
                'scratch_adinterval' => $req->scratch_adinterval,
                'scratch_ad' => $req->scratch_ad
            ]);

            return redirect('/setting/app#scratch')->with('success', 'Update Successfully!');
        } else if ($req->type == "quiz") {
            DB::table('tbl_app_setting')->where('id', 1)->update([
                'quiz_coin' => $req->quiz_coin,
                'quiz_interval' => $req->quiz_interval,
                'quiz_adinterval' => $req->quiz_adinterval,
                'quiz_ad' => $req->quiz_ad
            ]);

            return redirect('/setting/app#quiz')->with('success', 'Update Successfully!');
        } else if ($req->type == "promotion") {
            DB::table('tbl_app_setting')->where('id', 1)->update([
                'video_promotecoin' => $req->video_promotecoin,
                'max_promote' => $req->max_promote,
                'promote_time' => $req->promote_time,
                'promo_videocoin' => $req->promo_videocoin,
                'promo_webcoin' => $req->promo_webcoin
            ]);

            return redirect('/setting/app#promotion')->with('success', 'Update Successfully!');
        } else if ($req->type == "update") {
            DB::table('tbl_setting')->where('id', 1)->update([
                'up_version' => $req->up_version,
                'up_mode' => $req->up_mode,
                'up_msg' => $req->up_msg,
                'up_link' => $req->up_link,
                'up_btn' => $req->up_btn,
                'up_status' => $req->up_status,
            ]);

            return redirect('/setting/app#update')->with('success', 'Update Successfully!');
        } else if ($req->type == "home") {
            DB::table('tbl_setting')->where('id', 1)->update([
                'homeMsg' => $req->homeMsg,
                'snowfall_effect' => $req->snowfall_effect
            ]);

            return redirect('/setting/app#home')->with('success', 'Update Successfully!');
        } else if ($req->type == "general") {
            if ($req->icon) {
                $image_path = "/images/favicon.png";
                if (File::exists($image_path)) {
                    File::delete($image_path);
                }

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

                $image = $req->icon;

                $fileNameToStore = 'favicon.png';
                $image_resize = Image::make($image->getRealPath());
                $image_resize->resize(76, 76);
                $save = $image_resize->save('images/' . $fileNameToStore);
            }


            DB::table('tbl_setting')->where('id', 1)->update([
                'app_description' => $req->app_description,
            ]);

            return redirect('/setting/app#general')->with('success', 'Update Successfully!');
        } else if ($req->type == "referral") {

            DB::table('tbl_setting')->where('id', 1)->update([
                'refer_msg' => $req->refer_msg
            ]);

            DB::table('tbl_app_setting')->where('id', 1)->update([
                'welcome_bonus' => $req->welcome_bonus,
                'refer_mode' => $req->refer_mode,
                'refer_join_bonus' => $req->refer_join_bonus,
                'refer_bonus' => $req->refer_bonus
            ]);


            return redirect('/setting/app#referral')->with('success', 'Update Successfully!');
        } else if ($req->type == "social") {

            if ($req->icon) {
                $filename =  Fun::StoreImage("image", 200, 200, $req, "icon", true);
                if ($filename == null) {
                    return redirect('/setting/app#social')->with('error', 'Technical Error in Image Upload');
                }
            } else {
                $filename = $req->oldicon;
            }

            $res = DB::table('links')->where('id', $req->id)->update([
                'title' => $req->title,
                'image' => $filename,
                'url' => $req->url,
                'roworder' => $req->roworder
            ]);

            if ($res) {
                return redirect('/setting/app#social')->with('success', 'Social Link Update Successfully!');
            } else {
                return redirect('/setting/app#social')->with('success', 'Social Link Cant\'t Update!');
            }
        } else if ($req->type == "lang") {
            if ($req->icon) {
                $filename =  Fun::StoreImage("image", 100, 100, $req, "icon", true);
                if ($filename == null) {
                    return redirect('/setting/app#lang')->with('error', 'Technical Error in Image Upload');
                }
            } else {
                $filename = $req->oldicon;
            }

            $res = DB::table('app_lang')->where('id', $req->id)->update([
                'title' => $req->title,
                'image' => $filename,
                'lang_code' => $req->lang_code,
            ]);

            if ($res) {
                return redirect('/setting/app#lang')->with('success', 'Language Update Successfully!');
            } else {
                return redirect('/setting/app#lang')->with('success', 'Language Cant\'t Update!');
            }
        }else if ($req->type == "daily_mission") {
            
            if ($req->icon) {
                $filename =  Fun::StoreImage("image", 100, 100, $req, "icon", true);
                if ($filename == null) {
                    return redirect('/setting/app#daily_mission')->with('error', 'Technical Error in Image Upload');
                }
            } else {
               $filename=$req->oldicon;
            }

            DB::table('daily_mission')->where('id',$req->id)->update([
                'title' => $req->title,
                'image' => $filename,
                'btn_name' => $req->btn_name,
                'coin' => $req->coin,
                'promo_coin' => $req->promocoin
            ]);

            return redirect('/setting/app#daily_mission')->with('success', 'Language Added Successfully!');
        }else if ($req->type == "privacy_policy") {
            
           $db = DB::table('admin_key')->where('id',1)->update(['privacy_policy'=>$req->privacy_policy]);
           
           return redirect('/setting/app#privacy_policy')->with('success', 'Update Successfully!');
           
        }else if ($req->type == "ads_txt") {
            
           $db = DB::table('admin_key')->where('id',1)->update(['ads_txt'=>$req->ads_txt]);
           
           return redirect('/setting/app#ads_txt')->with('success', 'Update Successfully!');
           
        }else if ($req->type == "leaderboard") {
            
           $db = DB::table('tbl_app_setting')->where('id',1)->update([
               'daily_leaderboard1'=>$req->daily_leaderboard1,
               'daily_leaderboard2'=>$req->daily_leaderboard2,
               'daily_leaderboard3'=>$req->daily_leaderboard3,
               'weekly_leaderboard1'=>$req->weekly_leaderboard1,
               'weekly_leaderboard2'=>$req->weekly_leaderboard2,
               'weekly_leaderboard3'=>$req->weekly_leaderboard3
           ]);
           return redirect('/setting/app#leaderboard')->with('success', 'Update Successfully!');
        }else if ($req->type == "task") {
            
           $db = DB::table('subscriptions')->where('id',1)->update([
               'task_web'=>$req->task_web,
               'task_video'=>$req->task_video,
               'task_videozone'=>$req->task_videozone,
               'task_quiz'=>$req->task_quiz,
               'task_daily_offer'=>$req->task_daily_offer,
               'task_spin'=>$req->task_spin,
               'task_scratch'=>$req->task_scratch
           ]);
           return redirect('/setting/app#task')->with('success', 'Update Successfully!');
        }
        else{
            
            if ($req->icon) {
                $filename =  Fun::StoreImage("image", null, null, $req, "icon", true);
                if ($filename == null) {
                    return redirect('/setting/onboarding')->with('error', 'Technical Error in Image Upload');
                }
            } else {
               $filename=$req->oldicon;
            }
        
            $onboarding = _Onboarding::find($req->id);
            $onboarding->title = $req->title;
            $onboarding->subtitle = $req->subtitle;
            $onboarding->lang = $req->lang;
            $onboarding->image = $filename;
            $res = $onboarding->save();
            if ($res) {
                return redirect('/setting/onboarding')->with('success', 'Added Successfully!');
            } else {
                return redirect('/setting/onboarding')->with('error', 'Technical Error!');
            }
        }
    }

    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]);
        }

        if ($req->type == "social") {
            if ($req->icon) {
                $filename =  Fun::StoreImage("image", 150, 150, $req, "icon", false);
                if ($filename == null) {
                    return redirect('/setting/app#social')->with('error', 'Technical Error in Image Upload');
                }
            } else {
                return redirect('/setting/app#social')->with('error', 'Please Select Valid Image!');
            }

            DB::table('links')->insert([
                'title' => $req->title,
                'image' => $filename,
                'url' => $req->url,
                'roworder' => $req->roworder
            ]);

            return redirect('/setting/app#social')->with('success', 'Social Link Added Successfully!');
        } else if ($req->type == "lang") {
            if ($req->icon) {
                $filename =  Fun::StoreImage("image", 100, 100, $req, "icon", false);
                if ($filename == null) {
                    return redirect('/setting/app#lang')->with('error', 'Technical Error in Image Upload');
                }
            } else {
                return redirect('/setting/app#lang')->with('error', 'Please Select Valid Image!');
            }

            DB::table('app_lang')->insert([
                'title' => $req->title,
                'image' => $filename,
                'lang_code' => $req->lang_code,
            ]);

            return redirect('/setting/app#lang')->with('success', 'Language Added Successfully!');
        }
        else{
            
          if ($req->icon) {
            $filename =  Fun::StoreImage("image", null, null, $req, "icon", false);
            if ($filename == null) {
                return redirect('/setting/onboarding')->with('error', 'Technical Error in Image Upload');
            }
        }

        $onboarding = new _Onboarding;
        $onboarding->title = $req->title;
        $onboarding->subtitle = $req->subtitle;
        $onboarding->lang = $req->lang;
        $onboarding->image = $filename;
        $res = $onboarding->save();
        if ($res) {
            return redirect('/setting/onboarding')->with('success', 'Added Successfully!');
        } else {
            return redirect('/setting/onboarding')->with('error', 'Technical Error!');
        }  
            
        }
    }

    public function edit($type, $id)
    {
        if ($type == "social") {
            $data = DB::table('links')->where('id', $id)->get();
        } else if ($type == "lang") {
            $data = DB::table('app_lang')->where('id', $id)->get();
        } else if ($type == "mission") {
            $data = DB::table('daily_mission')->where('id', $id)->get();
        } else if ($type == "payment_gateway") {
            $res = DB::table('payment_gateway')->where('id', $id)->get();

            $network = array();
            foreach (json_decode($res[0]->config) as $item) {
                array_push($network, ['name' => $item->key, 'value' => $item->value]);
            }

            return view('pages/edit-gatyeway', ['data' => $res, 'network' => $network]);
        }else{
            $data=_Onboarding::find($id);
        }
        return $data;
    }

    public function updateGateway(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->icon) {
            $filename =  Fun::StoreImage("image", 150, 150, $req, "icon", true);
            if ($filename == null) {
                return redirect('/setting/app#payment_gateway')->with('error', 'Technical Error in Image Upload');
            }
        } else {
            $filename = $req->oldicon;
        }

        $config = DB::table('payment_gateway')->where('id', $req->id)->get();
        $ofr = json_decode($config[0]->config);
        $data = array();
        $val = $req->keyval;
        $cnt =  count($val);
        for ($i = 0; $i < $cnt; $i++) {
            array_push($data, ['key' => $ofr[$i]->key, 'slug' => $ofr[$i]->slug, 'value' => $val[$i]]);
        }

        DB::table('payment_gateway')->where('id', $req->id)->update([
            'title' => $req->title,
            'test_mode' => $req->test_mode,
            'country' => $req->country,
            'config' => $data,
            'image' => $filename
        ]);

        return redirect('/setting/app#payment_gateway')->with('success', 'Gateway Update Successfully');
    }

    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)
            ));
        }
    }

    public function destroy($type, $id)
    {
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        if ($type == "social") {
            $social = DB::table('links')->where('id', $id)->get();
            $image_path = "/images/" . $social[0]->image;
            if (File::exists($image_path)) {
                File::delete($image_path);
            }
            $social = DB::table('links')->where('id', $id)->delete();
            return 1;
        }else if ($type == "onboarding") {
           $banner = _Onboarding::where('id', $id)->get()->first()->image;

         _Onboarding::find($id)->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->type == "social") {
            $table = "links";
        } else if ($req->type == "lang") {
            $table = "lang";
        }else if ($req->type == "gateway") {
            $table = "payment_gateway";
        }else if ($req->type == "onboarding") {
            $table = "tbl_onboarding";
        }

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