<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\_Home;
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 App\Models\AppOffer;
use App\Models\Recharge;
use App\Models\Video;
use App\Models\Web;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;


class Home extends Controller
{
    public function index()
    {

        if(DB::table('ad_count')->where(['date'=>date('Y-m-d')])->count()==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,
            ]);
        }

        $user=  Users::count();   
        $ban=  Users::where('status',1)->count();   
        $today=  Users::whereDate('inserted_at',date('Y-m-d'))->count();   
        $appopen=  Users::whereDate('updated_at',date('Y-m-d'))->count();   
        $offerEarning= DB::select("SELECT SUM(earning) as income FROM offerwall_earing");
        $redeem=  DB::table('redeem')->count();   
        $trans=  DB::table('transaction')->count();   
        $video=  Video::where('status',0)->count();   
        $weblink=  Web::where('status',0)->count();   
        $pending=DB::table('recharge_request')->where('status','Pending')->count();
        $complete=DB::table('recharge_request')->where('status','Success')->count();
        $web=DB::table('offerwall')->where('type','web')->count();
        $doffer=DB::table('tbl_dailyoffer')->count();
        $game=DB::table('games')->count();
        $adCount=DB::table('ad_count')->where('date',date('Y-m-d'))->first();
        $month=Users::whereMonth('inserted_at', date('m'))
        ->whereYear('inserted_at', date('Y'))
        ->count();
        
        $allusercount = Users::select('cust_id','inserted_at')
            ->get()
            ->groupBy(function ($datess) {
                if(Carbon::parse($datess->inserted_at)->format('Y')==Carbon::now()->year){
                                return Carbon::parse($datess->inserted_at)->format('m');
                }
            });

            $usermcountss = [];
            $userArrss = [];
        
            foreach ($allusercount as $key => $value) {
                $usermcountss[(int)$key] = count($value);
            }
        
            $monthss = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        
            for ($i = 1; $i <= 12; $i++) {
                if (!empty($usermcountss[$i])) {
                    $userArrss[$i]['count'] = $usermcountss[$i];
                } else {
                    $userArrss[$i]['count'] = 0;
                }
                $userArrss[$i]['month'] = $monthss[$i - 1];
            }       
        
        $arr = '';
        $countryIso = DB::table('user_statistics')->get(['country_iso']);
        if(isset(request()->filter)){
            if(request()->filter=='month'){
                foreach ($countryIso as $item) {
                    $arr .= strtolower($item->country_iso) . ':' . DB::table('user_statistics')->where('country_iso',$item->country_iso)->whereMonth('created_at', date('m'))->count() . ',';
                }
            }else if(request()->filter=='3month'){
                foreach ($countryIso as $item) {
                    $arr .= strtolower($item->country_iso) . ':' . DB::table('user_statistics')->where('country_iso',$item->country_iso)->whereMonth('created_at', date('m'))->count() . ',';
                 }
            }else if(request()->filter=='year'){
                foreach ($countryIso as $item) {
                    $arr .= strtolower($item->country_iso) . ':' . DB::table('user_statistics')->where('country_iso',$item->country_iso)->whereYear('created_at', date('Y'))->count() . ',';
                }
            }else if(request()->filter=='day'){
                foreach ($countryIso as $item) {
                    $arr .= strtolower($item->country_iso) . ':' . DB::table('user_statistics')->where('country_iso',$item->country_iso)->whereDate('created_at', date('Y-m-d'))->count() . ',';
                }
            }
        }else{
             foreach ($countryIso as $item) {
                    $arr .= strtolower($item->country_iso) . ':' . DB::table('user_statistics')->where('country_iso',$item->country_iso)->whereDate('created_at', date('Y-m-d'))->count() . ',';
                }
        }
        
        $arr= rtrim($arr, ',');
        
        $totalAd=$adCount->admob_inter+$adCount->admob_reward+$adCount->applovin_inter+$adCount->applovin_reward+$adCount->fb_inter+$adCount->fb_reward+$adCount->unity_inter+$adCount->unity_reward+$adCount->wortise_inter+$adCount->wortise_reward+$adCount->irons_inter+$adCount->irons_reward+$adCount->startio;
        
           return view('dashboards.default',
                ['user'=>$user,
                'offerEarning'=>$offerEarning,
                'redeem'=>$redeem,
                'video'=>$video,
                'weblink'=>$weblink,
                'pending'=>$pending,
                'trans'=>$trans,
                'complete'=>$complete,
                'web'=>$web,
                'doffer'=>$doffer,
                'game'=>$game,
                'appopen'=>$appopen,
                'today'=>$today,
                'ban'=>$ban,
                'month'=>$month,
                'userstatics'=>$arr,
                'alluser'=>$userArrss,
                'adCount'=>$adCount,
                'totalAd'=>$totalAd
                ]);
    }
    
    public function indexAppHome(){
        if(isset(request()->type) && request()->type>0){
              $data = DB::table('home')->
                join('home_category','home_category.id','=','home.cat')
                ->where('cat',request()->type)
                ->select('home.*','home_category.title_en as cattitle')
                ->orderBy('roworder','ASC')->paginate();
        }else{
            $data = DB::table('home')->
            join('home_category','home_category.id','=','home.cat')
            ->select('home.*','home_category.title_en as cattitle')
            ->orderBy('roworder','ASC')->paginate();
        }       
        $cat=DB::table('home_category')->where('editable','0')->orderBy('row_order','ASC')->get();
        return view('home/hometask',['data'=>$data,'cat'=>$cat]);
    }
    
    public function indexCatHome(){
       $data=DB::table('home_category')->orderBy('row_order','ASC')->paginate(15);
       return view('home/category',['data'=>$data]);    
    }
    
    public function AddCatHome(){
      return view('home/add-category');    
    }
    
    public function AddHome(){
       $cat=DB::table('home_category')->where(['editable'=>0])->orderBy('row_order','ASC')->get(); 
      $btn=DB::table('btn_action')->where('cat','btn')->orderBy('row_order','ASC')->get();
      return view('home/add-top',['cat'=>$cat,'btn'=>$btn]);    
    }
    
    function getCatByLang($lang){
        return DB::table('home_category')->where(['lang'=>$lang,'editable'=>0])->orderBy('row_order','ASC')->get();
    }
    
    public function EditHome(_Home $id){
        $cat=DB::table('home_category')->where(['editable'=>0])->orderBy('row_order','ASC')->get(); 
        $btn=DB::table('btn_action')->where('cat','btn')->orderBy('row_order','ASC')->get();
        return view('home/edit-top',['data'=>$id,'cat'=>$cat,'btn'=>$btn]);
    }
    
    public function EditCatHome($id){
        return view('home/edit-category',['data'=>DB::table('home_category')->where('id',$id)->get()]);
    }
    
    public function DeleteCatHome($id){
        
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }

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

        DB::table('home')->where('id',$id)->delete();
        return 1;
    }
    
    public function StoreHome(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=='category'){
            $res=DB::table('home_category')->insert([
                'title_en'=>$req->title_en,
                'title_ar'=>$req->title_ar,
                'title_in'=>$req->title_in,
                'title_fr'=>$req->title_fr,
                'title_de'=>$req->title_de,
                'title_es'=>$req->title_es,
                'title_vi'=>$req->title_vi,
                'title_it'=>$req->title_it,
                'title_bn'=>$req->title_bn,
                'cat_theme'=>$req->cat_theme,
                'view_mode'=>$req->view_mode,
                'row_order'=>$req->row_order
                ]);
                
                
                
                
             if($res){
                return redirect('/app-setting/homepage/category')->with('success', 'Category Added Successfully');
            }else{
                 return redirect('/app-setting/homepage/category')->with('error', 'Something went wrong');
            }
        }
        
        if($req->icon){
          $filename=  Fun::StoreImage("image",null,null,$req,"icon",false);
          if($filename==null){
             return redirect('/app-setting/homepage/create')->with('error', 'Technical Error in Image Upload');
          }
        }
        
        
        $home=new _Home;
        $home->title_en=$req->title_en;
        $home->title_ar=$req->title_ar;
        $home->title_in=$req->title_in;
        $home->title_fr=$req->title_fr;
        $home->title_de=$req->title_de;
        $home->title_es=$req->title_es;
        $home->title_vi=$req->title_vi;
        $home->title_it=$req->title_it;
        $home->title_bn=$req->title_bn;
        $home->subtitle_en=(isset($req->subtitle_en)) ? $req->subtitle_en : null;
        $home->subtitle_ar=(isset($req->subtitle_ar)) ? $req->subtitle_ar : null;
        $home->subtitle_in=(isset($req->subtitle_in)) ? $req->subtitle_in : null;
        $home->subtitle_fr=(isset($req->subtitle_fr)) ? $req->subtitle_fr : null;
        $home->subtitle_de=(isset($req->subtitle_de)) ? $req->subtitle_de : null;
        $home->subtitle_es=(isset($req->subtitle_es)) ? $req->subtitle_es : null;
        $home->subtitle_vi=(isset($req->subtitle_vi)) ? $req->subtitle_vi : null;
        $home->subtitle_it=(isset($req->subtitle_it)) ? $req->subtitle_it : null;
        $home->subtitle_bn=(isset($req->subtitle_bn)) ? $req->subtitle_bn : null;
        $home->icon=$filename;
        $home->btn_name_en=(isset($req->btn_name_en)) ? $req->btn_name_en : null;
        $home->btn_name_ar=(isset($req->btn_name_ar)) ? $req->btn_name_ar : null;
        $home->btn_name_in=(isset($req->btn_name_in)) ? $req->btn_name_in : null;
        $home->btn_name_fr=(isset($req->btn_name_fr)) ? $req->btn_name_fr : null;
        $home->btn_name_de=(isset($req->btn_name_de)) ? $req->btn_name_de : null;
        $home->btn_name_es=(isset($req->btn_name_es)) ? $req->btn_name_es : null;
        $home->btn_name_vi=(isset($req->btn_name_vi)) ? $req->btn_name_vi : null;
        $home->btn_name_it=(isset($req->btn_name_it)) ? $req->btn_name_it : null;
        $home->btn_name_bn=(isset($req->btn_name_bn)) ? $req->btn_name_bn : null;
        $home->btn_action=$req->btn_action;
        $home->url=(isset($req->url)) ? $req->url : null;
        $home->btn_theme=$req->btn_theme;
        $home->cat=$req->cat;
        
        if($req->btn_theme==0){
            $btnbackground=$req->background_color0;
             $home->btn_background=$btnbackground;
            if($btnbackground==5){
              $home->background_color=$req->background_color_code;
            }
        }
        else if($req->btn_theme==1){
       
           $home->background_color=$req->background_color2;
           if($req->background_color2==11){
              $home->background_color=$req->background_color_code2;
           }
           
        }
        else if($req->btn_theme==2){
            $btnbackground=$req->background_color2;
            $home->btn_background=$btnbackground;
            $home->btn_color=$req->btnbackground_color2;
            if($btnbackground==11){
              $home->background_color=$req->background_color_code2;
            }
        }
        else if($req->btn_theme==5){
            $home->background_color=$req->background_color5;
        }
        else if($req->btn_theme==6){
            $home->background_color=$req->background_color5;
        }
        else if($req->btn_theme==7  || $req->btn_theme==8){
            $btnbackground=$req->background_color2;
            $home->btn_background=$btnbackground;
            if($btnbackground==11){
              $home->background_color=$req->background_color7;
              $home->btn_color=$req->btnbackground_color7;
            }
        }
      
        $home->roworder=$req->roworder;
        $home->type=$req->type;
        $res=$home->save();
        
        if($res){
             return redirect('/app-setting/homepage')->with('success', 'Button Added Successfully');
            
        }else{
             return redirect('/app-setting/homepage/create')->with('error', 'Something went wrong');
        }
        
    }
    
    public function UpdateHome(Request $req){
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>env('PERMISSION_ERROR')]);
        }

       
        if($req->type=='category'){
            $res=DB::table('home_category')->where('id',$req->id)->update([
                'title_en'=>$req->title_en,
                'title_ar'=>$req->title_ar,
                'title_in'=>$req->title_in,
                'title_fr'=>$req->title_fr,
                'title_de'=>$req->title_de,
                'title_es'=>$req->title_es,
                'title_vi'=>$req->title_vi,
                'title_it'=>$req->title_it,
                'title_bn'=>$req->title_bn,
                'cat_theme'=>$req->cat_theme,
                'view_mode'=>$req->view_mode,
                'row_order'=>$req->row_order
                ]);
               _Home::where('cat',$req->id)->update(['btn_theme'=>$req->cat_theme]); 
             if($res){
                return redirect('/app-setting/homepage/category')->with('success', 'Category Update Successfully');
            }else{
                 return redirect('/app-setting/homepage/category')->with('error', 'Something went wrong');
            }
        }
        
        if($req->icon){
          $filename=  Fun::StoreImage("image",null,null,$req,"icon",true);
          if($filename==null){
             return redirect('/app-setting/homepage/create')->with('error', 'Technical Error in Image Upload');
          }
        }else{
           $filename=$req->oldicon; 
        }
        
        $btnTheme=DB::table('home_category')->where('id',$req->cat)->first();
        
        $home=_Home::find($req->id);
        $home->title_en=$req->title_en;
        $home->title_ar=$req->title_ar;
        $home->title_in=$req->title_in;
        $home->title_fr=$req->title_fr;
        $home->title_de=$req->title_de;
        $home->title_es=$req->title_es;
        $home->title_vi=$req->title_vi;
        $home->title_it=$req->title_it;
        $home->title_bn=$req->title_bn;
        $home->subtitle_en=(isset($req->subtitle_en)) ? $req->subtitle_en : null;
        $home->subtitle_ar=(isset($req->subtitle_ar)) ? $req->subtitle_ar : null;
        $home->subtitle_in=(isset($req->subtitle_in)) ? $req->subtitle_in : null;
        $home->subtitle_fr=(isset($req->subtitle_fr)) ? $req->subtitle_fr : null;
        $home->subtitle_de=(isset($req->subtitle_de)) ? $req->subtitle_de : null;
        $home->subtitle_es=(isset($req->subtitle_es)) ? $req->subtitle_es : null;
        $home->subtitle_vi=(isset($req->subtitle_vi)) ? $req->subtitle_vi : null;
        $home->subtitle_it=(isset($req->subtitle_it)) ? $req->subtitle_it : null;
        $home->subtitle_bn=(isset($req->subtitle_bn)) ? $req->subtitle_bn : null;
        $home->icon=$filename;
        $home->btn_name_en=(isset($req->btn_name_en)) ? $req->btn_name_en : null;
        $home->btn_name_ar=(isset($req->btn_name_ar)) ? $req->btn_name_ar : null;
        $home->btn_name_in=(isset($req->btn_name_in)) ? $req->btn_name_in : null;
        $home->btn_name_fr=(isset($req->btn_name_fr)) ? $req->btn_name_fr : null;
        $home->btn_name_de=(isset($req->btn_name_de)) ? $req->btn_name_de : null;
        $home->btn_name_es=(isset($req->btn_name_es)) ? $req->btn_name_es : null;
        $home->btn_name_vi=(isset($req->btn_name_vi)) ? $req->btn_name_vi : null;
        $home->btn_name_it=(isset($req->btn_name_it)) ? $req->btn_name_it : null;
        $home->btn_name_bn=(isset($req->btn_name_bn)) ? $req->btn_name_bn : null;
        $home->btn_action=$req->btn_action;
        $home->url=(isset($req->url)) ? $req->url : null;
        $home->btn_theme=$btnTheme->cat_theme;
        $home->cat=$req->cat;
        
        if($btnTheme->cat_theme==0){
            $btnbackground=$req->background_color0;
            $home->btn_background=$btnbackground;
            if($btnbackground==5){
              $home->background_color=$req->background_color_code;
            }
        }
        else if($btnTheme->cat_theme==1){
           $home->background_color=$req->background_color2;
           $home->btn_background=$req->background_color2;
           if($req->background_color2==11){
              $home->background_color=$req->background_color_code2;
           }
        }
        else if($btnTheme->cat_theme==2){
            $btnbackground=$req->background_color2;
            $home->btn_background=$btnbackground;
            $home->btn_color=$req->btnbackground_color2;
            if($btnbackground==11){
              $home->background_color=$req->background_color_code2;
            }
        }
        else if($btnTheme->cat_theme==5){
            $home->background_color=$req->background_color5;
        }
        else if($btnTheme->cat_theme==6){
            $home->background_color=$req->background_color5;
        }
        else if($btnTheme->cat_theme==7  || $btnTheme->cat_theme==8){
            $btnbackground=$req->background_color2;
            $home->btn_background=$btnbackground;
            if($btnbackground==11){
              $home->background_color=$req->background_color7;
              $home->btn_color=$req->btnbackground_color7;
            }
        }
      
        $home->roworder=$req->roworder;
        $home->type=$req->type;
        $res=$home->save();
        
        if($res){
             return redirect('/app-setting/homepage')->with('success', 'Button Update Successfully');
            
        }else{
             return redirect('/app-setting/homepage/create')->with('error', 'Something went wrong');
        }
        
    }
    
    public function CatHomeAction(Request $req){
        if(auth()->user()->role_edit=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }

        if ($req->status == "enable") {
            $update = DB::table('home_category')->whereIn('id', explode(",", $req->id))->update(['status' => 0]);
            if ($update) {
                return 1;
            } else {
                return "not updated";
            }
        } else if ($req->status == "disable") {
            $update = DB::table('home_category')->whereIn('id', explode(",", $req->id))->update(['status' => 2]);
            if ($update) {
                return 1;
            } else {
                return "not updated";
            }
        }  
    }
    
    public function HomeAction(Request $req)
    {   
        if(auth()->user()->role_edit=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }


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