<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use DateTimeZone;
use Image;
use Storage;
use App\Models\Setting;
use App\Models\Token;
use DateTime;
use Auth;
use DB;
use App\Models\FamilyMember;
use App\Models\Package;
use App\Models\Profiles;
use App\Models\Parameter;
use App\Models\CartMember;
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    public function base64uploadFileImage(Request $request, $uploadFolderName, $inputFileName){
       // dd($request);
        $img = $request->get($inputFileName);
        // dd($img);
        $img = str_replace('data:image/png;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $fname= uniqid() . '.png';
        $file = Storage_path("app/public/".$uploadFolderName).'/' .$fname;
        $success = file_put_contents($file, $data);        
        return $fname;
    }
    protected function removeImage($image_path)
    {
        $image_path = Storage_path().'/app/public/'.$image_path;
        if(file_exists($image_path)){
            unlink($image_path);
        }        
    }

    public function gettotalcartmember(){
        $totalcartmember = count(DB::table('cart_member')
                 ->select('cart_member.family_member_id')
                 ->join('family_member', 'family_member.id', '=', 'cart_member.family_member_id')    
                 ->where("cart_member.user_id",Auth::id())             
                 ->groupBy('cart_member.family_member_id') 
                 ->get());
        return $totalcartmember;
    }

    public function getcartcontent(){
        $data=DB::table('cart_member')
                 ->select('cart_member.family_member_id')
                 ->join('family_member', 'family_member.id', '=', 'cart_member.family_member_id')    
                 ->where("cart_member.user_id",Auth::id())             
                 ->groupBy('cart_member.family_member_id') 
                 ->get();
               $ls1 = array();
              if(count($data)>0){
                   
                    foreach($data as $g){
                        $arr = array();
                        $getfamilyinfo = FamilyMember::find($g->family_member_id);
                        $arr['member_id'] = $g->family_member_id;
                        $arr['member_name'] = $getfamilyinfo->name;
                        $arr['relation'] = $getfamilyinfo->relation;
                        $arr['gender'] = $getfamilyinfo->gender;
                        $arr['age'] = $getfamilyinfo->age;
                        $getcartinfo = CartMember::where("user_id",Auth::id())->where("family_member_id",$g->family_member_id)->get();
                        foreach($getcartinfo as $g){
                            $b = array();
                            if($g->type==1){
                                $item_data = Package::find($g->type_id);
                            }else if($g->type==2){
                                $item_data = Parameter::find($g->type_id);
                            }else{
                                $item_data = Profiles::find($g->type_id);
                                if($item_data){
                                    $item_data->name = $item_data->profile_name;
                                }
                            }
                            $b['test_name'] = isset($item_data->name)?$item_data->name:'';
                            $b['mrp'] = isset($item_data->mrp)?$item_data->mrp:'';
                            $b['price']= isset($item_data->price)?$item_data->price:'';
                            $b['parameter']=$g->parameter;
                            $b['type']=$g->type;
                            $b['id']=$g->id;
                            $b['type_id']=$g->type_id;
                            $arr['testdata'][]=$b;
                        }
                        $ls1[] = $arr;
                    }
                }
                return $ls1;
    }

    public function getcartsubtotal(){
              $data=CartMember::where("user_id",Auth::id())->get();
              $total = 0;
              if(count($data)>0){
                        foreach($data as $g){
                            $b = array();
                            if($g->type==1){
                                $item_data = Package::find($g->type_id);
                            }else if($g->type==2){
                                $item_data = Parameter::find($g->type_id);
                            }else{
                                $item_data = Profiles::find($g->type_id);
                                if($item_data){
                                    $item_data->name = $item_data->profile_name;
                                }
                            }
                            
                            $price= isset($item_data->price)?$item_data->price:'';
                            $total = $total+$price;                            
                        }
                }
                return $total;
    }

    public function fileuploadFileImage(Request $request, $uploadFolderName, $inputFileName){
        $image     = $request->file($inputFileName);
        $fileName  = time().rand() . '.' . $image->getClientOriginalExtension();
       
        $img = Image::make($image->getRealPath());
        $img->resize(120, 120, function ($constraint) {
                $constraint->aspectRatio();                 
        });
        $img->stream(); 
        Storage::disk('local')->put('/public/'.$uploadFolderName.'/'.$fileName, $img, 'public');
        return $fileName;
    }

    public function send_notification_order_android($key,$user_id,$msg,$order_id){
          $getuser=Token::where("type","1")->where("user_id",$user_id)->get();
            if(count($getuser)!=0){               
                $reg_id = array();
                foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
                }
                $regIdChunk=array_chunk($reg_id,1000);
                foreach ($regIdChunk as $k) {
                       $registrationIds =  $k;    
                        $message = array(
                            "type"=>'order',
                            "click_action"=>"FLUTTER_NOTIFICATION_CLICK", "order_id"=> $order_id
                          );
                        $message1 = array(
                            'body' => $msg,
                            'title' =>  __('admin.Notification')
                        );
                       $fields = array(
                          'registration_ids'  => $registrationIds,
                          'data'              => $message,
                          'notification'=>$message1
                       );

                       $url = 'https://fcm.googleapis.com/fcm/send';
                       $headers = array(
                         'Authorization: key='.$key,// . $api_key,
                         'Content-Type: application/json'
                       );
                      $json =  json_encode($fields);   
                      $ch = curl_init();
                      curl_setopt($ch, CURLOPT_URL, $url);
                      curl_setopt($ch, CURLOPT_POST, true);
                      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                      curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                      $result = curl_exec($ch);   
                      if ($result === FALSE){
                         die('Curl failed: ' . curl_error($ch));
                      }     
                     curl_close($ch);
                     $response[]=json_decode($result,true);
               }
              $succ=0;
               if($response){
                 foreach ($response as $k) {
                    if(isset($k['success'])){
                      $succ=$succ+$k['success'];
                    }
                    
                 }
              }
             if($succ>0)
              {
                   return 1;
              }
               {
                  return 0;
               }
        }
        return 0;
   }
   public function send_notification_order_IOS($key,$user_id,$msg,$order_id){
      $getuser=Token::where("type","2")->where("user_id",$user_id)->get();
         if(count($getuser)!=0){               
               $reg_id = array();
               foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
               }
                 $regIdChunk=array_chunk($reg_id,1000);
               foreach ($regIdChunk as $k) {
                       $registrationIds =  $k;    
                       $message = array(
                            "type"=>'order',
                            "click_action"=>"FLUTTER_NOTIFICATION_CLICK", "order_id"=> $order_id
                          );
                       $message1 = array(
                            'body' => $msg,
                            'title' =>  __('admin.Notification')
                        );
                       $fields = array(
                          'registration_ids'  => $registrationIds,
                          'data'              => $message,
                          'notification'=>$message1
                       );
                       $url = 'https://fcm.googleapis.com/fcm/send';
                       $headers = array(
                         'Authorization: key='.$key,// . $api_key,
                         'Content-Type: application/json'
                       );
                      $json =  json_encode($fields);   
                      $ch = curl_init();
                      curl_setopt($ch, CURLOPT_URL, $url);
                      curl_setopt($ch, CURLOPT_POST, true);
                      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                      curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                      $result = curl_exec($ch);   
                      if ($result === FALSE){
                         die('Curl failed: ' . curl_error($ch));
                      }     
                     curl_close($ch);
                     $response[]=json_decode($result,true);
               }
              $succ=0;
              if($response){
                 foreach ($response as $k) {
                   if(isset($k['success'])){
                      $succ=$succ+$k['success'];
                    }
                 }
              }
              
             if($succ>0)
              {
                   return 1;
              }
            else
               {
                  return 0;
               }
        }
        return 0;
   }

    public function getsitedate(){
            $setting=Setting::find(1);
            $date_zone=array();
            $timezone=$this->generate_timezone_list();
                foreach($timezone as $key=>$value){
                      if($setting->default_timezone==$key){
                              $date_zone=$value;
                      }
                }
            date_default_timezone_set($date_zone);   
            return date('d-m-Y h:i:s');                    
     }

      public function getsitedateonly(){
            $setting=Setting::find(1);
            $date_zone=array();
            $timezone=$this->generate_timezone_list();
                foreach($timezone as $key=>$value){
                      if($setting->default_timezone==$key){
                              $date_zone=$value;
                      }
                }
            date_default_timezone_set($date_zone);   
            return date('Y-m-d');                    
     }

      static public function generate_timezone_list(){
          static $regions = array(
                     DateTimeZone::AFRICA,
                     DateTimeZone::AMERICA,
                     DateTimeZone::ANTARCTICA,
                     DateTimeZone::ASIA,
                     DateTimeZone::ATLANTIC,
                     DateTimeZone::AUSTRALIA,
                     DateTimeZone::EUROPE,
                     DateTimeZone::INDIAN,
                     DateTimeZone::PACIFIC,
                 );
                  $timezones = array();
                  foreach($regions as $region) {
                            $timezones = array_merge($timezones, DateTimeZone::listIdentifiers($region));
                  }

                  $timezone_offsets = array();
                  foreach($timezones as $timezone) {
                       $tz = new DateTimeZone($timezone);
                       $timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
                  }
                 asort($timezone_offsets);
                 $timezone_list = array();
    
                 foreach($timezone_offsets as $timezone=>$offset){
                          $offset_prefix = $offset < 0 ? '-' : '+';
                          $offset_formatted = gmdate('H:i', abs($offset));
                          $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
                          $timezone_list[] = "$timezone";
                 }

                 return $timezone_list;
                ob_end_flush();
       }

       public function gettimezonename($timezone_id){
              $getall=$this->generate_timezone_list();
              foreach ($getall as $k=>$val) {
                 if($k==$timezone_id){
                     return $val;
                 }
              }
       }
}
