<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\MyAuth;
use App\Http\Controllers\Controller;
use App\Models\Slider;
use App\Models\Task;
use App\Models\TaskCount;
use App\Models\Users;
use App\Models\Video;
use App\Models\_Ads;
use App\Models\_Home;
use App\Models\_Onboarding;
use App\Models\_Subscriptions;
use App\Models\_VideoWall;
use App\User;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Image;
use JWTAuth;
use Illuminate\Support\Facades\Cookie;

class Fun extends Controller
{

    private $timestamp;

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register', 'config','configV2', 'testapp', 'cronjob', 'offer_custom', 'offer_cr']]);
        $this->guard = "api";
        $this->timestamp = Carbon::now();
    }
     public function configV2(Request $req)
    {
        try {
            $lang = (request()->header('lang') == null || request()->header('lang') == '') ? 'en' : request()->header('lang');
            if ($json = MyAuth::Validation($req->field)) {
                $reqs = json_decode(base64_decode($json), true);
                
                $data = DB::table('tbl_setting')->where('id', 1)->get();
                $refer = DB::table('tbl_app_setting')->where('id', 1)->select('refer_join_bonus','refer_bonus')->get();
                $spin = DB::table('spin_wheel')->select('coin', 'color')->get();
                
                $title='title_'.$lang;
                $subtitle='subtitle_'.$lang;
                $btn_name='btn_name_'.$lang;
        
                $cat = DB::table('home_category')->where(['status' => 0])->select('id', $title.' as title', 'cat_theme', 'view_mode', 'cat_type')->orderBy('row_order', 'ASC')->get();
                $home = _Home::where('status', 0)->select('cat', 'icon', $title.' as title', $subtitle.' as subtitle', 'background_color', $btn_name.' as btn_name', 'btn_action', 'btn_theme', 'btn_color', 'btn_background', 'url')->orderBy('roworder', 'ASC')->get();   

                $langData = DB::table('lang_text')->where('type', '!=', 'server')->where('lang', $lang)->select('txt_value')->get();
                if ($data) {
                    return response([
                        'data' => $data,
                        'spin' => $spin,
                        'onboarding' => ($reqs['onboarding'] == false) ? _Onboarding::where(['lang' => $lang, 'status' => 0])->get() : [],
                        'home' => $home,
                        'cat' => $cat,
                        'lang' => $langData,
                        'refer_join_bonus' => $refer[0]->refer_join_bonus,
                        'refer_bonus' => $refer[0]->refer_bonus,
                        'code' => 201]);
                } else {
                    return response(['data' => 'data not found!!', 'code' => 400]);
                }
            } else {
                return response(['msg' => 'Something went wrong contact to Support ']);
            }
        } catch (\Exception $e) {
            return response(['msg' => 'Something went wrong contact to Support ']);
        }
    }

    public function testapp()
    {

   
    }

    public function promoBanner()
    {
        $data = Slider::where(['status' => 0])->where(['bannertype' => 'slide'])->select('banner', 'link', 'onclick')->get();
        if ($data) {
            return response(['data' => $data, 'code' => 201]);
        } else {
            return response(['data' => 'Data Not Found', 'code' => 401]);
        }
    }

    public function getSocialLinks()
    {
        $data = DB::table('links')->where('status', 0)->orderBy('roworder', 'ASC')->get();
        return response($data);
    }

    public function customAd($type)
    {
        $data = DB::table('tbl_nativead')->where(['ad_type' => $type, 'status' => 0])->limit(1)->inRandomOrder()->get();
        return response($data);
    }

    public function getResponseMsg($key)
    {
        $lang = (request()->header('lang') == null || request()->header('lang') == '') ? 'en' : request()->header('lang');
        return DB::table('lang_text')->where(['lang' => $lang, 'txt_key' => $key])->get()->first()->txt_value;
    }

    public function popupBanner()
    {
        $data = Slider::where(['status' => 0])->where('bannertype', '!=', 'slide')->select('banner', 'link', 'onclick')->get();
        if (count($data) > 0) {
            return response(['data' => $data, 'code' => 201]);
        } else {
            return response(['data' => [], 'code' => 401]);
        }
    }

    public function ofWeb()
    {
        if ($user = JWTAuth::User()) {
            $limit = $this->getTaskLimit(1, 'task_web');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_web');

            if ($taskCount <= $limit) {
                ($limit - $taskCount > 15) ? $avil = 20 : $avil = $limit - $taskCount;
                $data = DB::select('Select weblink.id,title,url,status,point,ad_type,action_type,thumb,timer,weblink.type,country
                            from weblink left outer join task on
                        task.user_id =:ids and weblink.id = task.task_id and task.type=2 where
                        weblink.country Like :cn or weblink.country=:all and task.task_id is NULL
                        and weblink.status=0 ORDER BY weblink.type=:usr DESC limit :lim', ['ids' => $user->cust_id, 'cn' => '%' . $user->country . '%', 'all' => 'all', 'usr' => 'User', 'lim' => $avil]);
                return response()->json($data);
            } else {
                return [];
            }
        }
    }

    public function missions($id)
    {
        if ($user = JWTAuth::User()) {

            $sub = _Subscriptions::find(1);
            $db = DB::table('daily_mission')->where('status', 0)->orderBy('row_order', 'ASC')->get();
            $cnt = DB::table('task_count')->where('user_id', $user->cust_id)->get();
            $taskStatus = DB::select("SELECT user_id, COUNT(*) AS TOTAL,
    COUNT(IF(task.task='m_daily',1,null)) AS m_daily,
    COUNT(IF(task.task='m_spin',1,null)) AS m_spin,
    COUNT(IF(task.task='m_web',1,null)) AS m_web,
    COUNT(IF(task.task='m_video',1,null)) AS m_video,
    COUNT(IF(task.task='m_quiz',1,null)) AS m_quiz,
    COUNT(IF(task.task='m_scratch',1,null)) AS m_scratch
FROM task WHERE user_id=:uid and date=:dat group by user_id", ['uid' => $id, 'dat' => date('Y-m-d')]);

            $appLimit = $sub->task_daily_offer;
            $spinLimit = $sub->task_spin;
            $webLimit = $sub->task_web;
            $videoLimit = $sub->task_video;
            $videozoneLimit = $sub->task_videozone;
            $quizLimit = $sub->task_quiz;
            $scratchLimit = $sub->task_scratch;

            $total = $appLimit + $spinLimit + $webLimit + $videoLimit + $quizLimit + $scratchLimit;

            $crntApp = $cnt[0]->c_daily_offer;
            $crntSpin = $cnt[0]->c_spin;
            $crntWeb = $cnt[0]->c_web;
            $crntVideo = $cnt[0]->c_video;
            $crntQuiz = $cnt[0]->c_quiz;
            $crntScratch = $cnt[0]->c_scratch;

            $left = $crntApp + $crntSpin + $crntWeb + $crntVideo + $crntQuiz + $crntScratch;

            $data[0]['id'] = $db[0]->id;
            $data[0]['title'] = $db[0]->title;
            $data[0]['image'] = $db[0]->image;
            $data[0]['limit'] = $appLimit;
            $data[0]['count'] = $crntApp;
            $data[0]['status'] = (isset($taskStatus[0]->m_daily)) ? $taskStatus[0]->m_daily : 0;
            $data[0]['coin'] = $db[0]->coin;
            $data[0]['promo_coin'] = $db[0]->promo_coin;
            $data[0]['btn_name'] = $db[0]->btn_name;
            $data[0]['btn_action'] = $db[0]->btn_action;

            $data[1]['id'] = $db[1]->id;
            $data[1]['title'] = $db[1]->title;
            $data[1]['image'] = $db[1]->image;
            $data[1]['limit'] = $spinLimit;
            $data[1]['count'] = $crntSpin;
            $data[1]['status'] = (isset($taskStatus[0]->m_spin)) ? $taskStatus[0]->m_spin : 0;
            $data[1]['coin'] = $db[1]->coin;
            $data[1]['promo_coin'] = $db[1]->promo_coin;
            $data[1]['btn_name'] = $db[1]->btn_name;
            $data[1]['btn_action'] = $db[1]->btn_action;

            $data[2]['id'] = $db[2]->id;
            $data[2]['title'] = $db[2]->title;
            $data[2]['image'] = $db[2]->image;
            $data[2]['limit'] = $webLimit;
            $data[2]['count'] = $crntWeb;
            $data[2]['status'] = (isset($taskStatus[0]->m_web)) ? $taskStatus[0]->m_web : 0;
            $data[2]['coin'] = $db[2]->coin;
            $data[2]['promo_coin'] = $db[2]->promo_coin;
            $data[2]['btn_name'] = $db[2]->btn_name;
            $data[2]['btn_action'] = $db[2]->btn_action;

            $data[3]['id'] = $db[3]->id;
            $data[3]['title'] = $db[3]->title;
            $data[3]['image'] = $db[3]->image;
            $data[3]['limit'] = $videoLimit;
            $data[3]['count'] = $crntVideo;
            $data[3]['status'] = (isset($taskStatus[0]->m_video)) ? $taskStatus[0]->m_video : 0;
            $data[3]['coin'] = $db[3]->coin;
            $data[3]['promo_coin'] = $db[3]->promo_coin;
            $data[3]['btn_name'] = $db[3]->btn_name;
            $data[3]['btn_action'] = $db[3]->btn_action;

            $data[4]['id'] = $db[4]->id;
            $data[4]['title'] = $db[4]->title;
            $data[4]['image'] = $db[4]->image;
            $data[4]['limit'] = $quizLimit;
            $data[4]['count'] = $crntQuiz;
            $data[4]['status'] = (isset($taskStatus[0]->m_quiz)) ? $taskStatus[0]->m_quiz : 0;
            $data[4]['coin'] = $db[4]->coin;
            $data[4]['promo_coin'] = $db[4]->promo_coin;
            $data[4]['btn_name'] = $db[4]->btn_name;
            $data[4]['btn_action'] = $db[4]->btn_action;

            $data[5]['id'] = $db[5]->id;
            $data[5]['title'] = $db[5]->title;
            $data[5]['image'] = $db[5]->image;
            $data[5]['limit'] = $scratchLimit;
            $data[5]['count'] = $crntScratch;
            $data[5]['status'] = (isset($taskStatus[0]->m_scratch)) ? $taskStatus[0]->m_scratch : 0;
            $data[5]['coin'] = $db[5]->coin;
            $data[5]['promo_coin'] = $db[5]->promo_coin;
            $data[5]['btn_name'] = $db[5]->btn_name;
            $data[5]['btn_action'] = $db[5]->btn_action;

            $resp = [
                'data' => $data,
                'total' => $total,
                'left' => $left,
            ];

            return response()->json($resp);
        }
    }

    public function ofVideo()
    {
        if ($user = JWTAuth::User()) {
            $limit = $this->getTaskLimit(1, 'task_video');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_video');

            if ($taskCount <= $limit) {
                ($limit - $taskCount > 15) ? $avil = 20 : $avil = $limit - $taskCount;
                $data = DB::select('Select youtube_video.id,title,timer,status,point,url,thumb,ad_type,action_type,task_limit,youtube_video.type,country
                from youtube_video left outer join task on task.user_id =:ids
                    and youtube_video.id = task.task_id and task.type=2
                    where youtube_video.country Like :cn or youtube_video.country=:all
                    and task.task_id is NULL
                    and youtube_video.status=0 ORDER BY youtube_video.type=:usr DESC limit :lim', ['ids' => $user->cust_id, 'cn' => '%' . $user->country . '%', 'all' => 'all', 'usr' => 'User', 'lim' => $avil]);
                return response()->json($data);
            } else {
                return [];
            }
        }
    }
 
 
    public function dailyoffer()
    {
        if ($user = JWTAuth::User()) {
            $limit = $this->getTaskLimit(1, 'task_daily_offer');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_daily_offer');

            if ($taskCount <= $limit) {
                ($limit - $taskCount > 15) ? $avil = 20 : $avil = $limit - $taskCount;
                $data = DB::select('Select tbl_dailyoffer.id,title,coin,tbl_dailyoffer.image,tbl_dailyoffer.link,country,description
                            from tbl_dailyoffer left outer join data_dailyoffer on
                        data_dailyoffer.user_id =:ids and tbl_dailyoffer.id = data_dailyoffer.survey_id
                        where tbl_dailyoffer.status=0 and
                        tbl_dailyoffer.country Like :cn or tbl_dailyoffer.country=:all
                        and data_dailyoffer.survey_id is NULL and tbl_dailyoffer.status=0
                        ORDER BY tbl_dailyoffer.id DESC limit :lim', ['ids' => $user->cust_id, 'cn' => '%' . $user->country . '%', 'all' => 'all', 'lim' => $avil]);
                return response()->json($data);
            }
        }
    }
 
    // Api Start
    public function api(Request $reqs)
    {
        if ($user = JWTAuth::User()) {
            if ($json = MyAuth::Validation($reqs->data)) {
                $req = json_decode(base64_decode($json), true);
                $type = $req['type'];
                $userid = base64_decode($req['im']);
                $reward = $req['reward'];
                $tag = $req['tag'];
                $modelID = $req['id']; 

                switch ($type) {

                    case "dailycheck":
                        return $this->dailycheck($user,$req['lmt']);
                        break;

                    case "s-limit":
                        return $this->ftlimt($user, $tag);
                        break;

                    case "s-credit":
                        
                        $xml=$req['xml'];
                        
                        if($xml!=md5($userid."-".env('APP_PACKAGE_NAME')."-".$type."-".$req['lmt'])){
                            return $this->respError("Session Expired Please Login Again");
                        }
                        
                        if(DB::table('temp_data')->where(['user_id'=>$userid,'type'=>$type,'lmt'=>$req['lmt'],'date'=>date('Y-m-d')])->count()>0){
                            return $this->respError("Something went wrong");
                        }
                        
                        return $this->crMulti($user, $tag, $reward,$type,$req['lmt']);
                        break;

                    case "referBonus":
                        return $this->collectBonus($user, $reward);
                        break;

                    // video credit
                    case "video":
                        return $this->creditVideo($user, $modelID);
                        break;

                    // web credit
                    case "web":
                        return $this->creditWeb($user, $modelID);
                        break;

                    // playzone credit
                    case "playzone":
                        return $this->creditPlayzone($user, $modelID);
                        break;

                    // promo video
                    case "refreshCoin":
                        $xp=$user->xp;
                        
                        $noti=DB::table('tbl_noti')->where(['user_id' => $user->cust_id, 'noti_type' => 0, 'status' => 0])->count();
                       
                        return response(['balance' => $user->balance,'xp'=>$xp,'level'=>$user->level,'noti'=>$noti, 'code' => 201]);
                        break;

                    // read global msg
                    case "readGlobal":
                        return $this->readGlobalMsg($modelID, $user->cust_id);
                        break;

                    // read notification msg
                    case "notification":
                        return $this->readNotification($modelID, $user->cust_id);
                        break;

                    case "missionValidation":
                        return $this->validateDailyMission($user->cust_id, $modelID);
                        break;

                    case "revealScratch":
                        return $this->revealScratch($user, $modelID);
                        break;

                    case "validateContest":
                        return $this->validateContest($user, $modelID);
                        break;

                    //user,redeem id,userdata
                    case "redeem":
                        return $this->redeem($user, $modelID, $tag);
                        break;

                    case "delete-ac":
                        return $this->deleteAccount($user);
                        break;
                        
                        
                }
            } else {
                return response(['msg' => 'Invalid Response']);
            }
        } else {
            return $this->respError("Session Expired Please Login Again");
        }
    }

    public function readNotification($modelID, $userid)
    {
        DB::table('tbl_noti')->where('user_id', $userid)->update(['status' => 1]);
        return response(['msg' => 'Notification Msg Read','code'=>201]);
    }
    
    public function readGlobalMsg($modelID, $userid)
    {
        DB::table('global_msg')->where(['user_id'=>$userid,'id'=>$modelID])->update(['status' => 1]);
        return response(['msg' => 'Global Msg Read']);
    }

    public function getTaskCount($uid, $type)
    {
        $cnt = DB::table('task_count')->where('user_id', $uid)->select($type)->get();
        return $cnt[0]->$type;
    }

    public function updateTaskCount($uid, $type, $val)
    {
        DB::table('task_count')->where('user_id', $uid)->update([$type => $val]);
    }

    public function getTaskLimit($subid, $type)
    {
        $cnt = DB::table('subscriptions')->where('id', $subid)->select($type)->get();
        return $cnt[0]->$type;
    }

    public function collectBonus($user, $refid)
    {
        if ($user = JWTAuth::User()) {

            $setting = DB::table('tbl_app_setting')->where('id', 1)->select('welcome_bonus', 'refer_mode', 'refer_join_bonus', 'refer_bonus')->get();
            $bonus = $setting[0]->refer_bonus;

            if ($refid == $user->refferal_id) {
                return $this->respError($this->getResponseMsg('cant_use_own_refer_code'));
            } else if ($user->from_refferal_id > 0) {
                return $this->respError($this->getResponseMsg('bonus_already_collected'));
            } else if ($refid == null) {
                return $this->respError($this->getResponseMsg('enter_valid_refer_code'));
            } else if($checkRef=Users::where('refferal_id',$refid)->first()) {
                
                
                $user=Users::find($user->cust_id);
                $coin = $setting[0]->refer_join_bonus;
                
                $user->from_refferal_id = $refid;
                if ($setting[0]->refer_mode == "direct") {
                    
                    $fromcoin= $setting[0]->refer_bonus;
                    
                    $touser=Users::find($checkRef->cust_id);
                    $Tototal = $touser->balance + $fromcoin;
                    $touser->balance = $Tototal;

                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Invite',
                        'user_id' => $checkRef->cust_id,
                        'amount' => $fromcoin,
                        'ip' => $this->IpAddr(),
                        'remained_balance' => $Tototal,
                        'remarks' => $this->getResponseMsg('referral_bonus_credit_from').' '. $user->name,
                        'inserted_at' => Carbon::now(),
                    ]);
                    $this->updateXp($touser);
                    $touser->save();
                            
                    if($crnt=DB::table('contest_record')->where('user_id',$checkRef->cust_id)->whereDate('created_at',date('Y-m-d'))->first()){
                          DB::table('contest_record')->where('id',$crnt->id)->update([
                                        'user_id' =>$checkRef->cust_id,
                                        'to_user_id' =>$user->cust_id,
                                        'task_count' =>($crnt->task_count+1),
                                    ]);
                    }else{
                            DB::table('contest_record')->insert([
                                        'user_id' =>$checkRef->cust_id,
                                        'to_user_id' => '1',
                                        'task_count' =>1,
                                    ]);
                        }

                    DB::table('global_msg')->insert([
                        'user_id' => $checkRef->cust_id,
                        'title' => $this->getResponseMsg('congratulations'),
                        'msg' => $this->getResponseMsg('referral_bonus_credit_from').' '. $user->name,
                        'btn_name' =>$this->getResponseMsg('close'),
                        'btn_action' => 'close',
                        'error' => 'false'
                    ]);
                    
                    DB::table('tbl_noti')->insert(['user_id' =>$checkRef->cust_id, 'title' =>$this->getResponseMsg('invite_bonus') , 'msg' =>$this->getResponseMsg('referral_bonus_credit_from').' '. $checkRef->name, 'created_at' => Carbon::now()]);

                    $user->refer = true;
                    $total = $user->balance + $coin;
                    $user->balance = $total;
            
                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Refer Join',
                        'user_id' =>  $user->cust_id,
                        'amount' => $coin,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $total,
                        'remarks' => $this->getResponseMsg('refer_joining_bonus'),
                        'inserted_at' => Carbon::now()
                    ]);
                    
                    $user->save();
                }else{

                    $total = $user->balance + $coin;
                    $user->balance = $total;
            
                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Refer Join',
                        'user_id' =>  $user->cust_id,
                        'amount' => $coin,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $total,
                        'remarks' => $this->getResponseMsg('refer_joining_bonus'),
                        'inserted_at' => Carbon::now()
                    ]);
                    
                    $user->save();
                     
                }
                
                  return $this->respOk($coin." ".$this->getResponseMsg('bonus_received'), $user->balance);
            }else{
                return $this->respError($this->getResponseMsg('enter_valid_refer_code'));
            }
           
        } else {
            return $this->respError("Something went wrong");
        }
    }

    public function crMulti($user, $type, $c,$tsktype,$lmt)
    {
        if ($user = JWTAuth::User()) {

            $sub = _Subscriptions::where('id', 1)->select('task_spin', 'task_scratch', 'task_quiz')->get();
            $taskCnt = TaskCount::find($user->cust_id);

            if ($type == "spin") {

                if ($taskCnt->c_spin <= $sub[0]->task_spin) {
                    $taskCnt->c_spin += +1;
                    $tot = $user->balance + $c;
                    $taskCnt->save();
                    $user->balance = $tot;
                    $this->updateXp($user);
                    $user->save();
                    $this->intTrans("Lucky Wheel", $user->cust_id, $c, $tot, $c . " " . $this->getResponseMsg('bonus_received'));

                    $setting = DB::table('tbl_app_setting')->where('id', 1)->select('spin_interval', 'spin_adinterval', 'spin_ad')->get();
                    $interval = $setting[0]->spin_interval;
                    $adinerval = $setting[0]->spin_adinterval;
                    $ad = $setting[0]->spin_ad;
                    $coin = 0;
                    
                    DB::table('temp_data')->insert(['user_id'=>$user->cust_id,'type'=>$type,'lmt'=>$lmt,'date'=>date('Y-m-d')]);

                    return response()->json(['msg' => $c . " " . $this->getResponseMsg('bonus_received'), 'limit' => $sub[0]->task_spin - $taskCnt->c_spin, 'balance' => $tot, 'coin' => $coin, 'interval' => $interval, 'ad_interval' => $adinerval, 'adType' => $ad, 'code' => 201]);
                } else {
                    return $this->respError($this->getResponseMsg('today_no_task_left'));
                }
            } else if ($type == "scratch") {
                if ($taskCnt->c_scratch <= $sub[0]->task_scratch) {
                    $taskCnt->c_scratch += +1;
                    $taskCnt->save();
                    $tot = $user->balance + $c;
                    $user->balance = $tot;
                    $this->updateXp($user);
                    $user->save();
                    $this->intTrans("Scratch Card", $user->cust_id, $c, $tot, $c . " " . $this->getResponseMsg('bonus_received'));

                    $setting = DB::table('tbl_app_setting')->where('id', 1)->select('scratch_coin', 'scratch_interval', 'scratch_adinterval', 'scratch_ad')->get();
                    $interval = $setting[0]->scratch_interval;
                    $adinerval = $setting[0]->scratch_adinterval;
                    $ad = $setting[0]->scratch_ad;
                    $coin = $setting[0]->scratch_coin;
                    
                    DB::table('temp_data')->insert(['user_id'=>$user->cust_id,'type'=>$type,'lmt'=>$lmt,'date'=>date('Y-m-d')]);

                    return response()->json(['msg' => $c . " " . $this->getResponseMsg('bonus_received'), 'limit' => $sub[0]->task_scratch - $taskCnt->c_scratch, 'balance' => $tot, 'coin' => $coin, 'interval' => $interval, 'ad_interval' => $adinerval, 'adType' => $ad, 'code' => 201]);
                } else {
                    return $this->respError($this->getResponseMsg('today_no_task_left'));
                }
            } else if ($type == "quiz") {
                if ($taskCnt->c_quiz <= $sub[0]->task_quiz) {

                    $setting = DB::table('tbl_app_setting')->where('id', 1)->select('quiz_coin', 'quiz_interval', 'quiz_adinterval', 'quiz_ad')->get();

                    $a = explode("-", $setting[0]->quiz_coin);
                    $c = rand($a[0], $a[1]);
                    $taskCnt->c_quiz += +1;
                    $taskCnt->save();
                    $tot = $user->balance + $c;
                    $user->balance = $tot;
                    $this->updateXp($user);
                    $user->save();
                    $this->intTrans("Quiz", $user->cust_id, $c, $tot, $c . " " . $this->getResponseMsg('bonus_received'));

                    $interval = $setting[0]->quiz_interval;
                    $adinerval = $setting[0]->quiz_adinterval;
                    $ad = $setting[0]->quiz_ad;
                    $coin = $setting[0]->quiz_coin;
                    
                    DB::table('temp_data')->insert(['user_id'=>$user->cust_id,'type'=>$type,'lmt'=>$lmt,'date'=>date('Y-m-d')]);

                    return response()->json(['msg' => $c . " " . $this->getResponseMsg('bonus_received'), 'limit' => $sub[0]->task_quiz - $taskCnt->c_quiz, 'balance' => $tot, 'coin' => $coin, 'interval' => $interval, 'ad_interval' => $adinerval, 'adType' => $ad, 'code' => 201]);
                } else {
                    return $this->respError($this->getResponseMsg('today_no_task_left'));
                }
            }
        }
    }

    public function ftlimt($user, $type)
    {
        $user = JWTAuth::User();
        $sub = _Subscriptions::where('id', 1)->select('task_spin', 'task_scratch', 'task_quiz')->get();
        $taskCnt = TaskCount::find($user->cust_id);
        switch ($type) {
            case "spin":
                $t = $sub[0]->task_spin;
                $u = $taskCnt->c_spin;
                $setting = DB::table('tbl_app_setting')->where('id', 1)->select('spin_interval', 'spin_adinterval', 'spin_ad')->get();

                $interval = $setting[0]->spin_interval;
                $adinerval = $setting[0]->spin_adinterval;
                $ad = $setting[0]->spin_ad;
                $coin = 0;
                break;

            case "scratch":
                $t = $sub[0]->task_scratch;
                $u = $taskCnt->c_scratch;
                $setting = DB::table('tbl_app_setting')->where('id', 1)->select('scratch_coin', 'scratch_interval', 'scratch_adinterval', 'scratch_ad')->get();

                $interval = $setting[0]->scratch_interval;
                $adinerval = $setting[0]->scratch_adinterval;
                $ad = $setting[0]->scratch_ad;
                $coin = $setting[0]->scratch_coin;
                break;

            case "quiz":
                $t = $sub[0]->task_quiz;
                $u = $taskCnt->c_quiz;
                $setting = DB::table('tbl_app_setting')->where('id', 1)->select('quiz_coin', 'quiz_interval', 'quiz_adinterval', 'quiz_ad')->get();

                $interval = $setting[0]->quiz_interval;
                $adinerval = $setting[0]->quiz_adinterval;
                $ad = $setting[0]->quiz_ad;
                $coin = $setting[0]->quiz_coin;
                break;
        }

        if ($u <= $t) {
            return response()->json(['total' => $t, 'limit' => $t - $u, 'coin' => $coin, 'interval' => $interval, 'ad_interval' => $adinerval, 'adType' => $ad, 'code' => 201]);
        } else {
            return response()->json(['total' => $t, 'limit' => 0, 'code' => 401]);
        }
    }

    public function leaderboard($type)
    {
        $msg = "";
        $date = date('Y-m-d');
        switch ($type) {
            // 0 = daily,1=weekly,2=alltime
            case 0:
                $data = DB::select("SELECT DISTINCT(user_id), SUM(amount) as balance,customer.name,customer.level,customer.country,customer.profile FROM `transaction` left outer join customer on customer.cust_id=transaction.user_id WHERE transaction.tran_type='credit' and date(transaction.inserted_at)=:dat GROUP BY customer.name ORDER BY balance DESC LIMIT 50", ['dat' => date('Y-m-d')]);

                $app = DB::table('tbl_app_setting')->where('id', 1)->select('daily_leaderboard1', 'daily_leaderboard2', 'daily_leaderboard3')->get();
                $msg = 'Top #1 = ' . $app[0]->daily_leaderboard1 . ' Coin ,#2 =' . $app[0]->daily_leaderboard2 . ' Coin ,#3 =' . $app[0]->daily_leaderboard3 . ' will get Bonus';

                break;

            case 1:

                $data = DB::select("SELECT DISTINCT(user_id), SUM(amount) as balance,customer.name,customer.level,customer.country,customer.profile FROM transaction left outer join customer on customer.cust_id=transaction.user_id WHERE transaction.tran_type='credit' and date(transaction.inserted_at)>=:start AND date(transaction.inserted_at) <=:end GROUP BY user_id ORDER BY balance DESC LIMIT 50", ['start' => date('Y-m-d', strtotime("this week")), 'end' => date('Y-m-d', strtotime("sunday this week", strtotime($date)))]);

                $app = DB::table('tbl_app_setting')->where('id', 1)->select('weekly_leaderboard1', 'weekly_leaderboard2', 'weekly_leaderboard3')->get();
                $msg = 'Top #1 = ' . $app[0]->weekly_leaderboard1 . ' Coin ,#2 =' . $app[0]->weekly_leaderboard2 . ' Coin ,#3 =' . $app[0]->weekly_leaderboard3 . ' will get Bonus';

                break;

            case 2:
                $data = DB::table('customer')
                    ->select('customer.name', 'customer.level', 'customer.balance', 'customer.profile', 'customer.type')
                    ->orderBy('customer.balance', 'DESC')
                    ->take('50')
                    ->get();

                break;
        }

        if ($data) {
            return response()->json(['data' => $data, 'msg' => $msg, 'code' => 201]);
        } else {
            return response()->json(['data' => 'Data Not Found', 'msg' => $msg, 'code' => 404]);
        }
    }

    public function redeem($user, $id, $userdata)
    {

        $rd = DB::table('redeem')->where('id', $id)->select('title', 'points', 'refer', 'task', 'quantity', 'category')->get();
        if ($rd) {
            if ($user->status == 1) {
                return $this->respError($user->reason);
            }

            if ($user->balance >= $rd[0]->points) {

                $redeemLimit = DB::table('tbl_app_setting')->where('id', 1)->select('redeem_limit', 'refer_mode','refer_join_bonus','refer_bonus')->get();
                $rchk = DB::table('recharge_request')->where('user_id', $user->cust_id)->whereDate('date', date('Y-m-d'))->count();

                if ($rchk >= $redeemLimit[0]->redeem_limit) {
                    return $this->respError($this->getResponseMsg('oops_today_redeem_limit_completed'));
                }

                if ($rd[0]->quantity != "00" && $rd[0]->quantity == "0") {
                    return $this->respError($this->getResponseMsg('you_are_late_stock_empty'));
                }

                if ($rd[0]->refer > 0) {
                    $cref = Users::where('from_refferal_id', $user->refferal_id)->count();
                    if ($cref < $rd[0]->refer) {
                        return $this->respError($this->getResponseMsg('invite') . ' ' . $rd[0]->refer . ' ' . $this->getResponseMsg('unlock_this_redeem'));
                    }
                }

                if ($rd[0]->task > 0) {

                    $getTaskLimit = DB::table('subscriptions')->where('id', 1)->select('task_web', 'task_video', 'task_quiz', 'task_spin', 'task_scratch')->get();
                    $taskCount = DB::table('task_count')->where('user_id', $user->cust_id)->select('c_spin', 'c_scratch', 'c_quiz', 'c_video', 'c_web')->get();

                    switch ($rd[0]->task) {
                        case 1:
                            if ($taskCount[0]->c_spin < $getTaskLimit[0]->task_spin || $taskCount[0]->c_scratch < $getTaskLimit[0]->task_scratch) {
                                return $this->respError($this->getResponseMsg('to_unlock_this_redeem_you_needto_complete_spin_scratch_task'));
                            }
                            break;

                        case 2:
                            if ($taskCount[0]->c_spin < $getTaskLimit[0]->task_spin || $taskCount[0]->c_scratch < $getTaskLimit[0]->task_scratch || $taskCount[0]->c_quiz < $getTaskLimit[0]->task_quiz) {
                                return $this->respError($this->getResponseMsg('to_unlock_this_redeem_you_needto_complete_spin_scratch_math_task'));
                            }
                            break;

                        case 3:
                            if ($taskCount[0]->c_spin < $getTaskLimit[0]->task_spin || $taskCount[0]->c_scratch < $getTaskLimit[0]->task_scratch || $taskCount[0]->c_web < $getTaskLimit[0]->task_web) {
                                return $this->respError($this->getResponseMsg('to_unlock_this_redeem_you_needto_complete_spin_scratch_article_task'));
                            }
                            break;

                        case 4:
                            if ($taskCount[0]->c_spin < $getTaskLimit[0]->task_spin || $taskCount[0]->c_scratch < $getTaskLimit[0]->task_scratch || $taskCount[0]->c_web < $getTaskLimit[0]->task_web || $taskCount[0]->c_video < $getTaskLimit[0]->task_video) {
                                return $this->respError($this->getResponseMsg('to_unlock_this_redeem_you_needto_complete_spin_scratch_article_videozone_task'));
                            }
                            break;
                    }
                }

                $ins = DB::table('recharge_request')->insert([
                    'mobile_no' => $userdata,
                    'amount' => $rd[0]->points,
                    'type' => $rd[0]->title,
                    'user_id' => $user->cust_id,
                    'status' => 'Pending',
                    'c_id' => $rd[0]->category,
                    'r_id' => $id,
                    'ip' => Fun::IpAddr(),
                    'date' => Carbon::now(),
                ]);

                if ($ins) {
                    $ded = $user->balance - $rd[0]->points;
                    $user->balance = $ded;

                    if ($rd[0]->quantity != "00" && $rd[0]->quantity > 0) {
                        DB::table('redeem')->where('id', $id)->update(['quantity' => ($rd[0]->quantity - 1)]);
                    }

                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Withdrawal',
                        'user_id' => $user->cust_id,
                        'amount' => $rd[0]->points,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $ded,
                        'remarks' => $this->getResponseMsg('withdrawal_request_submit'),
                        'inserted_at' => Carbon::now(),
                    ]);

                    $this->updateXp($user);
                    
                    if ($user->refer == false & $redeemLimit[0]->refer_mode != 'direct') {

                        if ($checkRef = Users::where('from_refferal_id', $user->from_refferal_id)->first()) {

                            $fromcoin = $redeemLimit[0]->refer_bonus;
                            
                            $touser=Users::find($checkRef->cust_id);
                            $Tototal = $touser->balance + $fromcoin;
                            $touser->balance = $Tototal;
        
                            DB::table('transaction')->insert([
                                'tran_type' => 'credit',
                                'type' => 'Invite',
                                'user_id' => $checkRef->cust_id,
                                'amount' => $fromcoin,
                                'ip' => $this->IpAddr(),
                                'remained_balance' => $Tototal,
                                'remarks' => $this->getResponseMsg('referral_bonus_credit_from').' '. $checkRef->name,
                                'inserted_at' => Carbon::now(),
                            ]);
                            $this->updateXp($touser);
                            $touser->save();

                            if ($crnt = DB::table('contest_record')->where('user_id', $checkRef->cust_id)->whereDate('created_at', date('Y-m-d'))->first()) {
                                DB::table('contest_record')->where('id', $crnt->id)->update([
                                    'user_id' => $checkRef->cust_id,
                                    'to_user_id' => $user->cust_id,
                                    'task_count' => ($crnt->task_count + 1),
                                ]);
                            } else {
                                DB::table('contest_record')->insert([
                                    'user_id' => $checkRef->cust_id,
                                    'to_user_id' => '1',
                                    'task_count' => 1,
                                ]);
                            }

                            DB::table('global_msg')->insert([
                                'user_id' => $paytrans[0]->user_id,
                                'title' => $this->getResponseMsg('congratulations'),
                                'msg' => $this->getResponseMsg('referral_bonus_credit_from').' '. $checkRef->name,
                                'btn_name' =>$this->getResponseMsg('close'),
                                'btn_action' => 'close',
                                'error' => 'false',
                            ]);

                            DB::table('tbl_noti')->insert(['user_id' => $checkRef->cust_id, 'title' => $this->getResponseMsg('invite_bonus'), 'msg' => $this->getResponseMsg('referral_bonus_credit_from') . ' ' . $checkRef->name, 'created_at' => Carbon::now()]);
                           
                            $user->refer = true;
                        }
                    }

                    $user->save();
                    return $this->respOk($this->getResponseMsg('redeem_successfully_bonus_receive_48_hour'), $ded);
                } else {
                    return $this->respError('Something went wrong');
                }
            } else {
                return $this->respError($this->getResponseMsg('not_enough_coin_to_redeem'));
            }
        } else {
            return $this->respError('Error 002');
        }
    }

    public function getContest($id, $limit,$type)
    {
        if ($user = JWTAuth::User()) {
                
                 $lang = (request()->header('lang') == null || request()->header('lang') == '') ? 'en' : request()->header('lang');
                 $title='title_'.$lang;
            
                $data = DB::select('Select '.$title.' as title,contest_task.id,contest_task.type,image,expired_at,start_from,task_require,coin,contest_task.status,contest_completed.contest_status from contest_task left outer join contest_completed on contest_completed.user_id =:ids and contest_task.id = contest_completed.contest_id  where contest_completed.contest_id is NULL and contest_task.type =:type and contest_task.status=0 ORDER BY contest_task.task_require ASC limit :lim', ['ids' => $user->cust_id,'type'=>$type ,'lim' => $limit]);
                $res = array();
                
                foreach ($data as $key => $value) {
                    
                    if($type=="refer"){
                        $checkRecord = DB::select('SELECT SUM(task_count) as total FROM `contest_record` WHERE user_id=:uid and date(created_at) >=:dat', ['uid' => $user->cust_id, 'dat' => $value->start_from]);
                    }
    
                    $res[$key]['id'] = $value->id;
                    $res[$key]['title'] = $value->title;
                    $res[$key]['image'] = $value->image;
                    $res[$key]['type'] = $value->type;
                    $res[$key]['expired_at'] = $value->expired_at;
                    $res[$key]['start_from'] = $value->start_from;
                    $res[$key]['task_require'] = $value->task_require;
                    $res[$key]['coin'] = $value->coin;
                    $res[$key]['contest_status'] = $value->contest_status;
                    
                    if($type=="refer"){
                        $res[$key]['refer'] = (isset($checkRecord[0]->total)) ? $checkRecord[0]->total : 0;
                    }else{
                       $res[$key]['refer'] = $user->level;
                    }
                }
         
            return response()->json(['data' => $res, 'code' => 201]);
        } else {
            return response()->json(['code' => 404]);
        }
    }

    public function validateContest($user, $id)
    {
        $uid = $user->cust_id;
        $check = DB::table('contest_completed')->where(['user_id' => $uid, 'contest_id' => $id])->count();
        
        $lang = (request()->header('lang') == null || request()->header('lang') == '') ? 'en' : request()->header('lang');
        $title='title_'.$lang;
                 
        if ($check > 0) {
            return $this->respError($this->getResponseMsg('bonus_already_collected'));
        }

        $contest = DB::table('contest_task')->where('id', $id)->select($title.' as title','type', 'coin', 'task_require', 'start_from', 'expired_at')->get();
        if ($contest) {
            $date = date('Y-m-d');
            if ($contest[0]->type=="refer" && $contest[0]->expired_at >= $date) {
                $checkRecord = DB::select('SELECT SUM(task_count) as total FROM `contest_record` WHERE user_id=:uid and date(created_at) >=:dat', ['uid' => $uid, 'dat' => $contest[0]->start_from]);
                if (isset($checkRecord[0]->total)) {
                    if ($checkRecord[0]->total >= $contest[0]->task_require) {

                        $total = $user->balance + $contest[0]->coin;
                        $user->balance = $total;
                        $this->updateXp($user);
                        $user->save();

                        //insert contest complete
                        DB::table('contest_completed')->insert(['user_id' => $uid, 'contest_id' => $id]);
                        $this->intTrans("Contest", $user->cust_id, $contest[0]->coin, $total, $this->getResponseMsg('contest_completed'), null);

                        return $this->respOk($contest[0]->coin . " " . $this->getResponseMsg('you_ve_won'), $total);
                        //addcontest
                    } else {
                        return $this->respError($this->getResponseMsg('complete_contest_task_and_submit'));
                    }
                } else {
                    return $this->respError($this->getResponseMsg('complete_contest_task_and_submit'));
                }
            }
            else if ($contest[0]->type=="level") {
               if ($user->level >= $contest[0]->task_require) {

                        $total = $user->balance + $contest[0]->coin;
                        $user->balance = $total;
                        $this->updateXp($user);
                        $user->save();

                        DB::table('contest_completed')->insert(['user_id' => $uid, 'contest_id' => $id]);
                        $this->intTrans("Contest", $user->cust_id, $contest[0]->coin, $total, $this->getResponseMsg('contest_completed'), null);

                        return $this->respOk($contest[0]->coin . " " . $this->getResponseMsg('you_ve_won'), $total);
                        //addcontest
                    } else {
                        return $this->respError($this->getResponseMsg('complete_contest_task_and_submit'));
                    }
            
            }else {
                return $this->respError($this->getResponseMsg('contest_has_been_ended'));
            }
        } else {
            return $this->respError("Contest doesn't Exist");
        }
    }

    public function validateDailyMission($uid, $mid)
    {
        $getMission = DB::table('daily_mission')->where('id', $mid)->select('title', 'coin', 'promo_coin', 'type')->get();
        if ($getMission) {

            $checkTodayStatus = DB::table('task')->where(['user_id' => $uid, 'task' => $getMission[0]->type, 'date' => date('Y-m-d')])->count();
            if ($checkTodayStatus > 0) {
                return $this->respError($this->getResponseMsg('bonus_already_collected'));
            }

            $user = Users::find($uid);
            $total = $user->balance + $getMission[0]->coin;
            $user->balance = $total;
            $this->updateXp($user);
            if ($getMission[0]->promo_coin > 0) {
                $user->promo_balance = $user->promo_balance + $getMission[0]->promo_coin;
            }
            $user->save();

            DB::table('task')->insert(['user_id' => $uid, 'task' => $getMission[0]->type, 'date' => date('Y-m-d')]);

            $this->intTrans("Daily Mission", $user->cust_id, $getMission[0]->coin, $total, $getMission[0]->title . " " . $this->getResponseMsg('mission_completed'), null);

            return $this->respOk($getMission[0]->coin . " " . $this->getResponseMsg('bonus_received'), $total);
        } else {
            return $this->respError("Invalid Mission Type");
        }
    }

    public function creditVideo($user, $modelID)
    {
        if ($video = DB::table('youtube_video')->where('id', $modelID)->select('task_limit', 'point', 'views')->get()) {
            $limit = $this->getTaskLimit(1, 'task_video');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_video');

            if ($taskCount > $limit) {
                return $this->respError($this->getResponseMsg('today_no_task_left'));
            }

            if ($this->getTaskLog(2, $modelID, $user->cust_id) > 0) {
                return $this->respError($this->getResponseMsg('bonus_already_collected'));
            }

            $c = $video[0]->point;
            $t = $user->balance + $c;
            $user->balance = $t;
            $this->updateXp($user);
            $user->save();
            DB::table('youtube_video')->where('id', $modelID)->update(['views' => ($video[0]->views + 1)]);
            if ($video[0]->task_limit > 0) {
                if (($video[0]->views + 1) >= $video[0]->task_limit) {
                    DB::table('youtube_video')->where('id', $modelID)->update(['status' => 1]);
                }
            }
            
            $this->updateTaskCount($user->cust_id, 'c_video', $taskCount + 1);
            $this->taskLog(2, $modelID, $user->cust_id);
            $this->intTrans("Video", $user->cust_id, $c, $t, $c . " " . $this->getResponseMsg('bonus_received'));
            return $this->respOk($c . " " . $this->getResponseMsg('bonus_received'), $t);
        } else {
            return $this->respError('Video not exist');
        }
    }

    public function creditWeb($user, $modelID)
    {
        if ($web = DB::table('weblink')->where('id', $modelID)->select('task_limit', 'point', 'views')->get()) {
            $limit = $this->getTaskLimit(1, 'task_web');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_web');

            if ($taskCount > $limit) {
                return $this->respError($this->getResponseMsg('today_no_task_left'));
            }

            if ($this->getTaskLog(1, $modelID, $user->cust_id) > 0) {
                return $this->respError($this->getResponseMsg('bonus_already_collected'));
            }

            $c = $web[0]->point;
            $t = $user->balance + $c;
            $user->balance = $t;
            $this->updateXp($user);
            $user->save();
            DB::table('weblink')->where('id', $modelID)->update(['views' => ($web[0]->views + 1)]);
            if ($web[0]->task_limit > 0) {
                if (($web[0]->views + 1) >= $web[0]->task_limit) {
                    DB::table('weblink')->where('id', $modelID)->update(['status' => 1]);
                }
            }

            $this->updateTaskCount($user->cust_id, 'c_web', $taskCount + 1);
            $this->taskLog(2, $modelID, $user->cust_id);
            $this->intTrans("Article", $user->cust_id, $c, $t, $c . " " . $this->getResponseMsg('bonus_received'));
            return $this->respOk($c . " " . $this->getResponseMsg('bonus_received'), $t);
        } else {
            return $this->respError($this->getResponseMsg('today_no_task_left'));
        }
    }

    public function creditPlayzone($user, $modelID)
    {
        $game = DB::table('games')->where('id', $modelID)->get();
        if ($game) {
            $cnt = Task::where(['type' => 3, 'user_id' => $user->cust_id, 'task_id' => $modelID])->whereDate('created_at', date('Y-m-d'))->count();

            if ($this->getTaskLog(3, $modelID, $user->cust_id) > 0) {
                return $this->respError($this->getResponseMsg('bonus_already_collected'));
            }

            $c = $game[0]->game_coin;
            $t = $user->balance + $c;
            $user->balance = $t;
            $this->updateXp($user);
            $user->save();
            $this->taskLog(3, $modelID, $user->cust_id);
            $this->intTrans("Play Zone", $user->cust_id, $c, $t, $c . " " . $this->getResponseMsg('bonus_received'), null);
            return $this->respOk($c . " " . $this->getResponseMsg('bonus_received'), $t);
        } else {
            return $this->respError($this->getResponseMsg('today_no_task_left'));
        }
    }

    public function taskLog($type, $taskid, $uid)
    {
        Task::insert(['type' => $type, 'task_id' => $taskid, 'user_id' => $uid]);
    }

    public function getTaskLog($type, $taskid, $uid)
    {
        return Task::where(['type' => $type, 'task_id' => $taskid, 'user_id' => $uid])->whereDate('created_at', date('Y-m-d'))->count();
    }

    public function getLanguage()
    {
        return response(DB::table('app_lang')->where('status', 0)->orderBy('id', 'ASC')->get());
    }

    public function dailycheck($user,$day)
    {
        if ($this->getTaskCount($user->cust_id, 'c_dcheck') == date('Y-m-d')) {
            return $this->respError($this->getResponseMsg('bonus_already_collected'));
        } else {
            $data = DB::table('tbl_app_setting')->select('dailybonus')->get();
            $js = json_decode($data[0]->dailybonus, true);
            // $day = Carbon::parse(Carbon::now())->format('l');
            if ($day == "1") {
                $coin = $js[0]['d1'];
            } else if ($day == "2") {
                $coin = $js[0]['d2'];
            } else if ($day == "3") {
                $coin = $js[0]['d3'];
            } else if ($day == "4") {
                $coin = $js[0]['d4'];
            } else if ($day == "5") {
                $coin = $js[0]['d5'];
            } else if ($day == "6") {
                $coin = $js[0]['d6'];
            } else if ($day == "7") {
                $coin = $js[0]['d7'];
            }

            $this->updateTaskCount($user->cust_id, 'c_dcheck', date('Y-m-d'));
            $total = $user->balance + $coin;
            $user->balance = $total;
            $user->updated_at = $this->timestamp;
            $this->updateXp($user);
            $user->save();
            $this->intTrans("Daily Bonus", $user->cust_id, $coin, $total, $coin . " " . $this->getResponseMsg('bonus_received'));
            return $this->respOk($coin . " " . $this->getResponseMsg('bonus_received'), $total);
        }
    }

    public function intTrans($task, $id, $coin, $total, $remark)
    {
        DB::table('transaction')->insert([
            'tran_type' => 'credit',
            'type' => $task,
            'user_id' => $id,
            'amount' => $coin,
            'ip' => Fun::IpAddr(),
            'remained_balance' => $total,
            'remarks' => $remark,
            'inserted_at' => Carbon::now(),
        ]);
    }

    public function respError($msg)
    {
        return response()->json(['msg' => $msg, 'code' => 404]);
    }

    public function respOk($msg, $total)
    {
        return response()->json(['msg' => $msg, 'balance' => $total, 'code' => 201]);
    }

    public function funGame($game_type, $limit)
    {
        $data = DB::table('games')->where(['game_type' => $game_type, 'status' => 0])->orderBy('id', 'DESC')->limit(20)->get();
        return response()->json(['data' => $data, 'code' => 201]);
    }

    public function getOfferwall($type, $home)
    {
        $select=['title','offer_type','description','offerwall_url','thumb','card_color','text_color','browser_type','u_tag','advid_tag','uid_type',];

        if ($home == "1") {
            $data = DB::table('offerwall')->where(['status' => 0, 'home' => 1, 'offer_type' => $type])->select($select)->orderBy('item_order', 'ASC')->get();
        } else {
            $data = DB::table('offerwall')->where(['status' => 0, 'offer_type' => $type])->select($select)->orderBy('item_order', 'ASC')->get();
        }

        return response()->json($data);
    }

    public function funOfferwalls($type)
    {

    }

    public function funfaq()
    {
        $lang = (request()->header('lang') == null || request()->header('lang') == '') ? 'en' : request()->header('lang');
        $data = DB::table('faq')->where('lang', $lang)->orderBy('id', 'ASC')->get();
        return response()->json($data);
    }

    public function rewardCat()
    {
        $user = JWTAuth::User();
        $data = DB::select('select * from redeem_cat where status=0 and country LIKE :cn or country =:all ORDER by min_coin + 0 ASC', ['cn' => '%' . $user->country . '%', 'all' => 'all']);
        return response()->json($data);
    }

    public function funrewards($id)
    {
        $user = JWTAuth::User();
        $data = DB::select('select * from redeem where category=:cat and status=0 and country LIKE :cn or country =:all AND category=:cat1 ORDER by points + 0 ASC', ['cat' => $id, 'cn' => '%' . $user->country . '%', 'all' => 'all', 'cat1' => $id]);
        return response()->json(['data' => $data, 'code' => 201]);
    }

    public function funCoinstore()
    {
        $user = JWTAuth::User();
        $pay = DB::table('tbl_app_setting')->get()->first()->pay_info;
        $data = DB::table('coinstore')->where('status', '0')->where('country', 'LIKE', '%' . $user->country . '%')->orwhere('country', 'all')->get();
        return response()->json(['data' => $data, 'code' => 201, 'info' => $pay]);
    }

    public function isUserBanned()
    {
        if ($user = JWTAuth::User()) {
            if ($user->status == 1) {
                return response()->json(['msg' => $user->reason, 'code' => 401]);
            }
        } else {
            return response()->json(['msg' => 'Something went wrong', 'code' => 401]);
        }
    }

    public function IpAddr()
    {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        } else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_FORWARDED'])) {
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        } else {
            $ipaddress = 'UNKNOWN';
        }

        return $ipaddress;
    }

    public function updateXp($user)
    {
        if ($user->xp >= 98) {
            $user->xp = 0;
            $user->level += +1;
        } else {
            $user->xp += +2;
        }
      //  $user->save();

    }

    public function customAdImpression($type, $id, $cl)
    {
        $this->adAction($type, $id, $cl);
        
        $select=['admob_inter','admob_reward','applovin_inter','applovin_reward','fb_inter','fb_reward','unity_inter','unity_reward','irons_inter','irons_reward','wortise_inter','wortise_reward','start_auto_ad'];
        
        $adConfig=DB::table('tbl_setting')->where('id',1)->select($select)->get();
        
        return response()->json(['msg' => "Imp Count",
        'admob_inter'=>$adConfig[0]->admob_inter,
        'admob_reward'=>$adConfig[0]->admob_reward,
        'applovin_inter'=>$adConfig[0]->applovin_inter,
        'applovin_reward'=>$adConfig[0]->applovin_reward,
        'fb_inter'=>$adConfig[0]->fb_inter,
        'fb_reward'=>$adConfig[0]->fb_reward,
        'unity_inter'=>$adConfig[0]->unity_inter,
        'unity_reward'=>$adConfig[0]->unity_reward,
        'irons_inter'=>$adConfig[0]->irons_inter,
        'irons_reward'=>$adConfig[0]->irons_reward,
        'wortise_inter'=>$adConfig[0]->wortise_inter,
        'wortise_reward'=>$adConfig[0]->wortise_reward,
        'start_auto_ad'=>$adConfig[0]->start_auto_ad,
        'code' => 201]);
    }

    public function adAction($adType, $id, $cl)
    {

        $adCount = DB::table('ad_count')->where('date', date('Y-m-d'))->select($adType)->first();
        $count = $adCount->$adType + 1;

        if ($adType == "custom_ad") {
            DB::table('ad_count')->where('date', date('Y-m-d'))->update([$adType => $count]);
            $ads = _Ads::find($id);
            if ($cl == "1") {
                $ads->click += +1;
            }else{
                $ads->impression += +1;
            }
            
            
            $ads->save();

        } else {
            $adlimit = DB::table('ad_limit')->where('id', 1)->select($adType)->first();

            $count = $adCount->$adType + 1;
            if ($count >= $adlimit->$adType) {

                $data = [];

                $setting = DB::table('tbl_setting')->where('id', 1)->select('interstital_type', 'backup_interstital_type')->get();

                if ($setting[0]->interstital_type != "off" && $setting[0]->interstital_type == $this->getAdName($adType)) {

                    if ($setting[0]->backup_interstital_type != "off") {

                        $data = [$adType => 'false',
                            'interstital_type' => $setting[0]->backup_interstital_type,
                            'backup_interstital_type' => 'off'];
                    } else {

                        $data = [$adType => 'false',
                            'interstital_type' => 'off',
                            'backup_interstital_type' => 'off'];
                    }
                } else {
                    $data = [$adType => 'false'];
                }

                DB::table('tbl_setting')->where('id', 1)->update($data);
                DB::table('ad_count')->where('date', date('Y-m-d'))->update([$adType => $count]);

            } else {
                DB::table('ad_count')->where('date', date('Y-m-d'))->update([$adType => $count]);
            }
        }
    }

    public function getAdName($string)
    {
        $msg = "";
        switch ($string) {
            case 'admob_inter':
                $msg = "admob";
                break;

            case 'fb_inter':
                $msg = "fb";
                break;

            case 'applovin_inter':
                $msg = "applovin";
                break;

            case 'start_auto_ad':
                $msg = "startapp";
                break;

            case 'unity_inter':
                $msg = "unity";
                break;

            case 'irons_inter':
                $msg = "ironsource";
                break;

            case 'wortise_inter':
                $msg = "wortise";
                break;
        }

        return $msg;
    }

    public function cronjob($secret)
    {
        $db = DB::table('admin_key')->where('id', 1)->select('cron_secret', 'transaction_auto_delete')->get();
        $cronsec = $db[0]->cron_secret;
        $trans_delete = $db[0]->transaction_auto_delete;

        if ($secret == $cronsec) {
            DB::table('task_count')->update([
                'c_web' => 0,
                'c_video' => 0,
                'c_videozone' => 0,
                'c_quiz' => 0,
                'c_daily_offer' => 0,
                'c_spin' => 0,
                'c_scratch' => 0,
            ]);

            DB::table('ad_count')->insert([
                'date' => date('Y-m-d'),
                'admob_inter' => 0,
                'admob_reward' => 0,
                'applovin_inter' => 0,
                'applovin_reward' => 0,
                'startio' => 0,
                'fb_inter' => 0,
                'fb_reward' => 0,
                'irons_inter' => 0,
                'irons_reward' => 0,
                'unity_inter' => 0,
                'unity_reward' => 0,
                'wortise_inter' => 0,
                'wortise_reward' => 0,
                'custom_ad' => 0,
            ]);

            DB::table('task')->delete();

            $date = date('Y-m-d');
            $days = 7;
            DB::table('contest_task')->whereDate('created_at', '>', $date)->update(['status' => 2]);

            DB::table('global_msg')
                ->whereRaw('created_at < NOW() - INTERVAL ? DAY', [$days])
                ->delete();

            DB::table('password_reset')
                ->whereRaw('created_at < NOW() - INTERVAL ? DAY', [2])
                ->delete();

            DB::table('tbl_noti')
                ->whereRaw('created_at < NOW() - INTERVAL ? DAY', [7])
                ->delete();

            DB::table('transaction')
                ->whereRaw('inserted_at < NOW() - INTERVAL ? DAY', [$trans_delete])
                ->delete();

            $app = DB::table('tbl_app_setting')->where('id', 1)->select('daily_leaderboard1', 'daily_leaderboard2', 'daily_leaderboard3', 'weekly_leaderboard1', 'weekly_leaderboard2', 'weekly_leaderboard3')->get();

            $daily3 = DB::select("SELECT DISTINCT(user_id), SUM(amount) as balance,customer.name,customer.country,customer.profile FROM `transaction` left outer join customer on customer.cust_id=transaction.user_id WHERE transaction.tran_type='credit' and date(transaction.inserted_at)=:dat GROUP BY customer.name ORDER BY balance DESC LIMIT 3", ['dat' => date('Y-m-d')]);

            if (isset($daily3[0]->user_id)) {

                $u1 = Users::find($daily3[0]->user_id);
                $total = $u1->balance + $app[0]->daily_leaderboard1;
                $u1->balance = $total;
                $this->updateXp($u1);
                $u1->save();

                DB::table('transaction')->insert([
                    'tran_type' => 'credit',
                    'type' => 'Leaderboard',
                    'user_id' => $daily3[0]->user_id,
                    'amount' => $app[0]->daily_leaderboard1,
                    'ip' => Fun::IpAddr(),
                    'remained_balance' => $total,
                    'remarks' => $this->getResponseMsg('daily_leaderboard_top1_winner'),
                    'inserted_at' => Carbon::now(),
                ]);

                DB::table('global_msg')->insert([
                    'user_id' => $daily3[0]->user_id,
                    'title' => $this->getResponseMsg('congratulations'),
                    'msg' => $this->getResponseMsg('you_are_on_daily_leaderboard_top1_winner'),
                    'btn_name' => 'close',
                    'btn_action' => 'close',
                    'error' => 'false',
                ]);
            }

            if (isset($daily3[1]->user_id)) {

                $u1 = Users::find($daily3[1]->user_id);
                $total = $u1->balance + $app[0]->daily_leaderboard2;
                $u1->balance = $total;
                $this->updateXp($u1);
                $u1->save();

                DB::table('transaction')->insert([
                    'tran_type' => 'credit',
                    'type' => 'Leaderboard',
                    'user_id' => $daily3[1]->user_id,
                    'amount' => $app[0]->daily_leaderboard1,
                    'ip' => Fun::IpAddr(),
                    'remained_balance' => $total,
                    'remarks' => $this->getResponseMsg('daily_leaderboard_top2_winner'),
                    'inserted_at' => Carbon::now(),
                ]);

                DB::table('global_msg')->insert([
                    'user_id' => $daily3[1]->user_id,
                    'title' => $this->getResponseMsg('congratulations'),
                    'msg' => $this->getResponseMsg('you_are_on_daily_leaderboard_top2_winner'),
                    'btn_name' => 'close',
                    'btn_action' => 'close',
                    'error' => 'false',
                ]);
            }

            if (isset($daily3[2]->user_id)) {

                $u1 = Users::find($daily3[2]->user_id);
                $total = $u1->balance + $app[0]->daily_leaderboard2;
                $u1->balance = $total;
                $this->updateXp($u1);
                $u1->save();

                DB::table('transaction')->insert([
                    'tran_type' => 'credit',
                    'type' => $this->getResponseMsg('leaderboard'),
                    'user_id' => $daily3[2]->user_id,
                    'amount' => $app[0]->daily_leaderboard1,
                    'ip' => Fun::IpAddr(),
                    'remained_balance' => $total,
                    'remarks' => $this->getResponseMsg('daily_leaderboard_top3_winner'),
                    'inserted_at' => Carbon::now(),
                ]);

                DB::table('global_msg')->insert([
                    'user_id' => $daily3[2]->user_id,
                    'title' => $this->getResponseMsg('congratulations'),
                    'msg' => $this->getResponseMsg('you_are_on_daily_leaderboard_top3_winner'),
                    'btn_name' => 'close',
                    'btn_action' => 'close',
                    'error' => 'false',
                ]);
            }

            $day = Carbon::parse(Carbon::now())->format('l');
            if ($day == "Monday") {
                $weekly = DB::select("SELECT DISTINCT(user_id), SUM(amount) as balance,customer.name,customer.country,customer.profile FROM transaction left outer join customer on customer.cust_id=transaction.user_id WHERE transaction.tran_type='credit' and date(transaction.inserted_at)>=:start AND date(transaction.inserted_at) <=:end GROUP BY user_id ORDER BY balance DESC LIMIT 3", ['start' => date('Y-m-d', strtotime("this week")), 'end' => date('Y-m-d', strtotime("sunday this week", strtotime($date)))]);

                if (isset($weekly[0]->user_id)) {

                    $u1 = Users::find($weekly[0]->user_id);
                    $total = $u1->balance + $app[0]->weekly_leaderboard1;
                    $u1->balance = $total;
                    $this->updateXp($u1);
                    $u1->save();

                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Leaderboard',
                        'user_id' => $weekly[0]->user_id,
                        'amount' => $app[0]->weekly_leaderboard1,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $total,
                        'remarks' => $this->getResponseMsg('weekly_leaderboard_top1_winner'),
                        'inserted_at' => Carbon::now(),
                    ]);

                    DB::table('global_msg')->insert([
                        'user_id' => $daily3[0]->user_id,
                        'title' => $this->getResponseMsg('congratulations'),
                        'msg' => $this->getResponseMsg('you_are_on_weekly_leaderboard_top1_winner'),
                        'btn_name' => 'close',
                        'btn_action' => 'close',
                        'error' => 'false',
                    ]);
                }

                if (isset($weekly[1]->user_id)) {

                    $u1 = Users::find($weekly[1]->user_id);
                    $total = $u1->balance + $app[0]->weekly_leaderboard2;
                    $u1->balance = $total;
                    $this->updateXp($u1);
                    $u1->save();

                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Leaderboard',
                        'user_id' => $weekly[1]->user_id,
                        'amount' => $app[0]->weekly_leaderboard2,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $total,
                        'remarks' => $this->getResponseMsg('weekly_leaderboard_top2_winner'),
                        'inserted_at' => Carbon::now(),
                    ]);

                    DB::table('global_msg')->insert([
                        'user_id' => $weekly[1]->user_id,
                        'title' => $this->getResponseMsg('congratulations'),
                        'msg' => $this->getResponseMsg('you_are_on_weekly_leaderboard_top2_winner'),
                        'btn_name' => 'close',
                        'btn_action' => 'close',
                        'error' => 'false',
                    ]);
                }

                if (isset($weekly[2]->user_id)) {

                    $u1 = Users::find($weekly[2]->user_id);
                    $total = $u1->balance + $app[0]->weekly_leaderboard3;
                    $u1->balance = $total;
                    $this->updateXp($u1);
                    $u1->save();

                    DB::table('transaction')->insert([
                        'tran_type' => 'credit',
                        'type' => 'Leaderboard',
                        'user_id' => $weekly[2]->user_id,
                        'amount' => $app[0]->weekly_leaderboard3,
                        'ip' => Fun::IpAddr(),
                        'remained_balance' => $total,
                        'remarks' => $this->getResponseMsg('weekly_leaderboard_top3_winner'),
                        'inserted_at' => Carbon::now(),
                    ]);

                    DB::table('global_msg')->insert([
                        'user_id' => $weekly[2]->user_id,
                        'title' => $this->getResponseMsg('congratulations'),
                        'msg' => $this->getResponseMsg('you_are_on_weekly_leaderboard_top3_winner'),
                        'btn_name' => 'close',
                        'btn_action' => 'close',
                        'error' => 'false',
                    ]);
                }
            }

            \Artisan::call('view:clear');
            \Artisan::call('cache:clear');
            \Artisan::call('route:clear');
            \Artisan::call('config:clear');

            return response()->json(['msg' => 'Cron Job Run Successfully!!.']);
        } else {
            return 'Cron Key Not match';
        }
    }

    public function addDayinDate($day)
    {
        return Date('Y-m-d', strtotime('+' . $day . ' days'));
    }

    public function moveTaskPending($userid, $appid)
    {
        $d = DB::table('appslog')->where(['user_id' => $userid, 'appid' => $appid])->count();
        if ($d) {
            return $this->respError("offer Already in Pending");
        } else {
            DB::table('appslog')->insert([
                'user_id' => $userid,
                'appid' => $appid,
                'status' => 1,
                'created_at' => date('Y-m-d'),
            ]);

            return response()->json(['msg' => 'Offer added in pending', 'code' => 201]);
        }
    }

    public function YouTubeGetID($url)
    {
        if (stristr($url, 'youtu.be/')) {
            preg_match('/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i', $url, $final_ID);
            return $final_ID[4];
        } else {
            @preg_match('/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $IDD);
            return $IDD[5];
        }
    }

    public function notiMsg($id)
    {
        $data = DB::table('tbl_noti')->where(['user_id' => $id, 'noti_type' => 0])->orWhere(['user_id' => 0, 'noti_type' => 1])->select('title', 'msg', 'created_at')->latest()->limit(30)->get();
        return response()->json($data);
    }

    public function getGlobalMsg($id)
    {
        $data = DB::table('global_msg')->where(['user_id' => $id, 'status' => 0])->orWhere(['user_id' => 0])->inRandomOrder()->limit(1)->get();
        return response()->json($data);
    }

    public function readnoti()
    {
        if ($user = JWTAuth::User()) {
            DB::table('tbl_noti')->where(['user_id' => $user->cust_id])->update(['status' => 1]);
            return response()->json(['msg' => "Notificatin Mark as Read", 'balance' => 0, 'code' => 201]);
        }
    }

    public function submit_dailyoffer(Request $req)
    {
        if ($user = JWTAuth::User()) {

            $srv = DB::table('tbl_dailyoffer')->where('id', $req->id)->get();

            $limit = $this->getTaskLimit(1, 'task_daily_offer');
            $taskCount = $this->getTaskCount($user->cust_id, 'c_daily_offer');

            if ($taskCount > $limit) {
                return response()->json(['msg' => $this->getResponseMsg('today_no_task_left'), 'code' => 202]);
            }

            $cn = DB::table('data_dailyoffer')->where(['survey_id' => $req->id, 'user_id' => $user->cust_id])->count();

            if ($cn > 0) {
                return response()->json(['msg' => $this->getResponseMsg('offer_Already_Submited'), 'code' => 201]);
            }
            
            if($srv[0]->task_limit>0){
                if ($srv[0]->views >= $srv[0]->task_limit) {
                    return response()->json(['msg' => $this->getResponseMsg('Oops_you_are_late_offer_limit_has_been completed'), 'code' => 202]);
                }
            }

            $image = $req->newimage;
            $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(300, 500);
            $image_resize->save('images/dailyoffer/' . $fileNameToStore);

            DB::table('data_dailyoffer')->insert([
                'url' => $req->link,
                'survey_id' => $req->id,
                'taskStatus' => 0,
                'image' => $fileNameToStore,
                'user_id' => $user->cust_id,
                'name' => $user->name,
                'email' => $user->email,
            ]);

            $this->updateTaskCount($user->cust_id, 'c_daily_offer', $taskCount + 1);

            DB::table('tbl_dailyoffer')->where('id', $req->id)->update(['views' => ($srv[0]->views + 1)]);

            if ($srv[0]->task_limit > 0) {
                if (($srv[0]->views + 1) >= $srv[0]->task_limit) {
                    DB::table('tbl_dailyoffer')->where('id', $req->id)->update(['status' => 2]);
                }
            }

            return response()->json(['msg' => $this->getResponseMsg('Offer_Submit_Successfully_Bonus_will_be_receive_after_verification'), 'code' => 201]);
        }
    }
    public function supportTicket()
    {
        if ($user = JWTAuth::User()) {
            $data = DB::table('support_ticket')->where('user_id', $user->cust_id)->latest()->get();
            return response()->json($data);
        }
    }

    public function createSupportTicket(Request $req)
    {
        if ($user = JWTAuth::User()) {
            $cnt = DB::table('support_ticket')->where('user_id', $user->cust_id)->where('status', '<', 2)->count();

            $ins = DB::table('support_ticket')->insert([
                'user_id' => $user->cust_id,
                'ticketID' => mt_rand(123456, 999999),
                'email' => $req->email,
                'name' => $user->name,
                'subject' => $req->subject,
                'message' => $req->message,
                'status' => 0,
                'created_at' => Carbon::now(),
            ]);

            if ($ins) {
                return $this->respOk($this->getResponseMsg('Ticket_Created_Successfully'), 0);
            } else {
                return $this->respError("Something went wrong");
            }
        }
    }

    public function getReferralHistory()
    {
        if ($user = JWTAuth::User()) {
            $data = DB::table('customer')
                ->select('customer.name', 'customer.profile', 'customer.balance', 'customer.inserted_at', 'customer.cust_id', 'customer.refer', 'customer.level')
                ->where('from_refferal_id', $user->refferal_id)
                ->orderBy('cust_id', 'DESC')->limit(30)->get();
                
            $successRef = Users::where(['from_refferal_id' => $user->refferal_id, 'refer' => true])->count();
            $pendingRef = Users::where(['from_refferal_id' => $user->refferal_id, 'refer' => false])->count();

            return response(['data' => $data ,'successRef' => $successRef,
                'pendingRef' => $pendingRef]);
        }
    }

    public function deleteAccount($user)
    {
        if ($user = JWTAuth::User()) {
            $id = $user->cust_id;
            $email = $user->email;
            
            DB::table('delete_account')->insert(['email'=>$email]);
            
            DB::table('customer')->where('cust_id', $id)->delete();
            DB::table('transaction')->where('user_id', $id)->delete();
            DB::table('recharge_request')->where('user_id', $id)->delete();
            DB::table('data_dailyoffer')->where('user_id', $id)->delete();
            DB::table('monitor_report')->where('userid', $id)->delete();
            DB::table('task_count')->where('user_id', $id)->delete();
            DB::table('tbl_noti')->where('user_id', $id)->delete();
            DB::table('tbl_support')->where('user_id', $id)->delete();

            
            return $this->respOk($this->getResponseMsg('account_delete_success_message'), 0);
        } else {
            return $this->respError("Session Expired Login Again");
        }
    }
}
