<?php

namespace App\Helpers;

use Auth;
use App\User;
use App\Helpers\CommonHelper;
use Illuminate\Support\Facades\DB;
use Config;
use Mail;
use App\Models\LogsAPIs;
use App\Models\LogsSAML;
use App\Models\UserToken;
use App\Models\UserLibrary;
use App\Models\NotificationUsers;
use App\Models\NotificationLogs;
use App\Models\SiteConfiguration;
use App\Models\AccessToken;
use Corcel\Model\Post as WordpressPost;
use Hash;
use Illuminate\Support\Facades\Storage;

class CommonHelper
{

  static function starsRatings($star)
  {
            if ($star <= config('constants.STAR_1') && $star > config('constants.STAR_0')) 
            {
                $rate1 =  '<i class="fa fa-star"></i>';
            }
             elseif ($star <= config('constants.STAR_1_5') && $star > config('constants.STAR_1')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star-half"></i>';
            }
             elseif ($star <= config('constants.STAR_2') && $star > config('constants.STAR_1_5')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i>';
            }
             elseif ($star <= config('constants.STAR_2_5') && $star > config('constants.STAR_2')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half"></i>';
            }
             elseif ($star <= config('constants.STAR_3') && $star > config('constants.STAR_2_5')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i>';
            }
                elseif ($star <= config('constants.STAR_3_5') && $star > config('constants.STAR_3')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half"></i>';
            }
                 elseif ($star <= config('constants.STAR_4') && $star > config('constants.STAR_3_5')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i>';
            }
                 elseif ($star <= config('constants.STAR_4_5') && $star > config('constants.STAR_4')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half"></i>';
            }
                  elseif ($star <= config('constants.STAR_5') && $star > config('constants.STAR_4_5')) 
            {
                $rate1 =  '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i>';
            }
            else
            {
                $rate1 = "";
            }
            return $rate1;
  }

  static function array_to_csv_download($array,$file_name) 
    {
    
        if (count($array) == 0) 
          {
            return null;
        }
        
          $filename = "$file_name-" . date("Y-m-d-H:i:s") . ".csv";
          // disable caching
          $now = gmdate("D, d M Y H:i:s");
          header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
          header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
          header("Last-Modified: {$now} GMT");
       
          // force download  
          header("Content-Type: application/force-download");
          header("Content-Type: application/octet-stream");
          header("Content-Type: application/download");
       
          // disposition / encoding on response body
          header("Content-Disposition: attachment;filename={$filename}");
          header("Content-Transfer-Encoding: binary");
       
          $df = fopen("php://output", 'w');
          fputcsv($df, array_keys(reset($array)));
          foreach ($array as $row) {
              fputcsv($df, $row);
        }
        fclose($df);
        die();    
    }
    
  static function _processDataTableRequest($_params=array())
  {
    $draw         = @$_params['draw'];
    $columns      = @$_params['columns'];
    $offset       = @$_params['start'];
    $recordsPerPage   = @$_params['length'];
    $searchKeyword    = @$_params['search']['value'];
    $sortOrderIndex   = @$_params['order'][0]['column'];
    $sortOrderDirection = @$_params['order'][0]['dir'];    
    $sortColumn     = @$columns[$sortOrderIndex]['name'];

    $returnArray = array();
    
    if(!$draw)
    {
      $draw = 0;
    }
    
    if(!$offset)
    {
      $offset = 0;
    }
    
    if(!$recordsPerPage)
    {
      $recordsPerPage = config('constants.BACKEND_LISTING_RECORDS_PER_PAGE');
    }

    $returnArray['offset']        = $offset;
    $returnArray['records_per_page']  = $recordsPerPage;
    $returnArray['search_keyword']    = $searchKeyword;
    $returnArray['sort_column']     = $sortColumn;
    $returnArray['sort_direction']    = $sortOrderDirection;    
    $returnArray['draw']        = $draw;
    
    return $returnArray;
  }
  
  static function getGUID()
  {
    if (function_exists('com_create_guid'))
    {
      return str_replace(array('{', '}'), array('',''), com_create_guid());
    }
    else 
    {
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12)
            .chr(125);// "}"
      return str_replace(array('{', '}'), array('',''), $uuid);
            // return $uuid;
    }
  }

  static function _formatDateofBirth($date){ //used while saving into db
    if(@$date){
      $date = date("Y-m-d", strtotime($date));
      return $date;
    }else{
      return false;
    }
  }

  static function _formatDate($date){ //used while saving into db
    if(@$date){
      $date = date("Y-m-d", strtotime(str_replace("-","/",@$date)));
      return $date;
    }else{
      return '';
    }
  }
  static function _showDate($date){
    if(!empty($date) && ($date != '0000-00-00') && ($date != '0000-00-00 00:00:00')){
      $date = date("d-M-Y", strtotime(str_replace("-", "/", $date)));
      return $date;
    }else{
      return '';
    }
  }
  static function _showTime($time){
      if(!empty($time)  && ($time != '00:00:00')){
          $time = date("h:i A", strtotime(str_replace("-", "/", $time)));
          return $time;
      }else{
          return "00:00:00";
      }
  }
  static function getUserByToken($token)
  {
    $user = \App\User::where('token', $token)->where('is_deleted', 0)->first();

    if(!empty($user))
    {
      return $user;
    }
    else
    {
      return false;
    }
  }

  static function checkAuth($user_id, $token)
  {
    $current_user = @CommonHelper::getUserByToken($token);
    if($current_user == false && $user_id != @$current_user->id)
    {
        $data["header"]["error"] = "1";
        $data['message']         = 'Invalid user or token mismatch';
    }
    elseif(@$current_user->is_terminated == 1){
        $data["header"]["error"] = "1";
        $data['message']         = 'Session terminated';
    }else
    {
        $data["header"]["error"] = "0";
        $data['current_user'] = $current_user;
    }
    return $data;
  }

  static function getPaginationDetails($params=array())
  {
    $recordsPerPage = Config::get('api.recordsPerPage');
    $offset = 0;
    $current_page = 1;
    $next_page = 2;

    $input = $params['input'];
    $total_records = $params['total_records'];

    if(isset($input['page']))
    {
        $page = $input['page'];

        if(is_numeric($page))
        {
            if($page > 1)
            {
                $current_page = (int) $page;

                $next_page = (int) ($current_page + 1);

                $offset = (($page-1) * $recordsPerPage);
            }
        }
    }

    $total_pages = ceil($total_records / $recordsPerPage);

    if($total_pages <= 0)
    {
        $total_pages = 1;
    }

    if(($total_pages <= 1) || ($next_page > $total_pages) || (($current_page) >= $total_pages))
    {
        $next_page = 0;
    }

    return array(
                  'offset'            => $offset,
                  'records_per_page'  => $recordsPerPage,
                  'total_records'     => $total_records, 
                  'total_pages'       => $total_pages, 
                  'current_page'      => $current_page, 
                  'next_page'         => $next_page
              );

  }

  static function getInputParam($input=array(), $field_key='')
  {
    $field_value = '';

    if(isset($input[$field_key]))
    {
      $_field_value = $input[$field_key];

      if($_field_value)
      {
        $field_value = $_field_value;
      }
    }

    return $field_value;
  }

  static function sendEmail($params=array())
  {
    $templateName = $params['template_name'];
    $templateData = $params['template_data']; //array of data!
    $sendToEmail  = $params['send_to'];
    $subject      = $params['subject'];

    Mail::send( 'emails.'.$templateName, $templateData, function ($m) use ($sendToEmail, $subject) { $m->to($sendToEmail)->subject($subject); } );
  }
  static function generateToken()
  {
    return md5(uniqid(rand(), true));
  }

  static function generateOTPToken()
  {
    // return md5(uniqid(rand(), true));
    // return rand(11111, 99999);
    return "click123";
  }

  static function checkAuthentication($email, $token)
  {
    $check_user = @UserToken::where('email', $email)->where('token', $token)->count();
    if($check_user > 0)
    {
      return true;
    }
    return false;
  }

  static function getApiExpiryTimeStamp()
  {
        $t = strtotime('+5 minutes', time());

        return $t;
  }

  static function response($data, $api_log_id = false, $api_start_time = false)
  {
      //-log-save-start
      if($api_log_id)
      {
          $start_time     = $api_start_time;
          $end_time       = microtime(true);
          
          $logData = array();
          
          $logData['response']        = json_encode($data); 
          $logData['response_time']   = date('Y-m-d H:i:s');
          $logData['total_seconds']   = $end_time-$start_time; //in seconds

          LogsAPIs::updateOrCreate(['id' => $api_log_id], $logData);
      }
      //log-save-end

      return response($data);
  }

  static function bm_estimated_reading_time($post_content='', $type='display') 
  {
        if($post_content)
        {
            $words = str_word_count( html_entity_decode(strip_tags( $post_content ) ) );
            $minutes = floor( $words / 120 );
            $seconds = floor( $words % 120 / ( 120 / 60 ) );

            if ( 1 <= $minutes ) 
            {
                if($type == 'calculate')
                {
                    $estimated_time = ($minutes * 60) + $seconds;
                }
                else
                {
                    $estimated_time = $minutes . ' min' . ' ' . $seconds . ' sec';
                }
                
            }
            else
            {
                if($type == 'calculate')
                {
                    $estimated_time = (int) $seconds;
                }
                else
                {
                   $estimated_time = $seconds . ' sec';
                }
                
            }

            return $estimated_time;
        }

        if($type == 'calculate')
        {
            return 0;
        }

        return '';
    }

    static function getShortDescriptionForArticle($_content='')
    {
        $short_description = '';
        if($_content)
        {
            $_content = str_replace('“', '"', $_content);
            $_content = str_replace('‘', '', $_content);
            $_content = str_replace('’', '', $_content);

            $plain_content = (strip_tags($_content));

            if($plain_content)
            {
                $plain_content = str_replace(array("\r", "\n", '&nbsp;'), '', $plain_content); //remove some characters from html!

                if($plain_content)
                {
                    //$plain_content = trim($plain_content);

                    $short_description = substr($plain_content, 0, 150)."...";

                    $short_description = html_entity_decode($short_description);
                }
            }
        }

        return $short_description;
    }

    static function _getImage($obj, $thumb = false)
    {
      $img = config('constants.DEFAULT_LARGE_IMAGE');
      if($thumb == true)
      {
        $img = config('constants.DEFAULT_THUMB_IMAGE');
      }
      if(@WordpressPost::find($obj)->url)
      {
        $img = WordpressPost::find($obj)->url;
      }

      return $img;
    }

    static function _getPostData($request, $articleData, $postType, $isFull=false)
    {
        $_userId = 0;
        $hasInReadingList = 0;
        $user_read_seconds = 0;

        // $request = $current_request;
        $input = $request->input();

        if(isset($input['user_id']))
        {
            if($input['user_id'])
            {
                $_userId = $input['user_id'];
            }
        }

        $userLibraryModel = new UserLibrary();
        if($_userId)
        {

            $count = $userLibraryModel->checkArticleHasInLibrary($_userId, $articleData['ID']);

            if($count > 0)
            {
                $hasInReadingList = 1;
            }

            $record = $userLibraryModel->getReadingSecondsForArticle($_userId, $articleData['ID']);
            
            if($record)
            {
                if($record->read_seconds)
                {
                    $user_read_seconds = $record->read_seconds;
                }
            }
        }

        


        if($postType == 'law_update_articles')
        {
            $articleWriters     = $articleData->acf->lawUpdateArticleWriters;
            $articlePractices   = $articleData->acf->lawUpdateArticlePractices;
            $articleSectors     = $articleData->acf->lawUpdateArticleSectors;
            $articleNotWriters  = $articleData->acf->lawUpdateArticleNoWriters;

            $articleMonth  = $articleData->acf->lawUpdateArticleMonth;

            $articleMonthText = $articleMonth->post_title;

            $txtPractices = array();
            $txtSectors = array();
            $txtWriters = array();

            //article practice!
            $arrArticlePractices = array();

            if($articlePractices)
            {
                foreach($articlePractices as $articlePracticeKey => $articlePracticeValue)
                {
                    $_lawUpdateArticlePractice = $articlePracticeValue['lawUpdateArticlePractice'];
                    if($_lawUpdateArticlePractice)
                    {
                      $arrArticlePractices[] = array( 
                                                  'id'   => $_lawUpdateArticlePractice->ID, 
                                                  'name' => $_lawUpdateArticlePractice->post_title 
                                              );

                      $txtPractices[] = strtoupper($_lawUpdateArticlePractice->post_title);
                    }
                }
            }

            

            //article sectors!
            $arrArticleSectors = array();

            if($articleSectors)
            {
                foreach($articleSectors as $articleSectorKey => $articleSectorValue)
                {
                    $_lawUpdateArticleSector = $articleSectorValue['lawUpdateArticleSector'];
                    if($_lawUpdateArticleSector)
                    {
                      $arrArticleSectors[] = array( 
                                                    'id' => $_lawUpdateArticleSector->ID, 
                                                  'name' => $_lawUpdateArticleSector->post_title 
                                              );
                      $txtSectors[] = $_lawUpdateArticleSector->post_title;
                    }

                }
            }


            //article writers!
            $arrArticleUsers = array();

            if($articleSectors)
            {
              if($articleWriters)
              {
                foreach($articleWriters as $articleWriterKey => $articleWriterValue)
                {
                    $_lawUpdateArticleWriter = $articleWriterValue['lawUpdateArticleWriter'];
                    if($_lawUpdateArticleWriter)
                    {
                      $arrArticleUsers[] = array( 
                                                    'id' => $_lawUpdateArticleWriter->ID, 
                                                  'name' => $_lawUpdateArticleWriter->post_title 
                                              );
                      $txtWriters[] = $_lawUpdateArticleWriter->post_title;
                    }

                }
              }
            }

            //article writers!
            $arrArticleNotWriters = array();

            if($articleNotWriters)
            {
                foreach($articleNotWriters as $articleNotWriterKey => $articleNotWriterValue)
                {
                    $_lawUpdateAuthorName = $articleNotWriterValue['lawUpdateAuthorName'];
                    $_lawUpdateAuthorEmail = $articleNotWriterValue['lawUpdateAuthorEmail'];
                    $_lawUpdateAuthorLocation = $articleNotWriterValue['lawUpdateAuthorLocation'];

                    $arrArticleNotWriters[] = array( 
                                                
                                                'name' => $_lawUpdateAuthorName,
                                                'email' => $_lawUpdateAuthorEmail,
                                                'location' => $_lawUpdateAuthorLocation,
                                            );

                    $txtWriters[] = $_lawUpdateAuthorName;
                }
            }

            $article = [];
            $article['type'] = $postType;
            $article['id'] = $articleData['ID'];
            $article['title'] = $articleData['post_title'];
            $article['image'] = CommonHelper::_getImage($articleData->mobileAppLarge);
            $article['thumb_image'] = CommonHelper::_getImage($articleData->mobileAppThumb, true);
            $article['category'] = $articleMonthText;
            $article['practices'] = implode(' / ', $txtPractices);
            $article['sectors'] = implode(' / ', $txtSectors);
            $article['writers'] = implode(' / ', $txtWriters);
            $article['post_date'] = date('Y-m-d H:i:s', strtotime($articleData['post_date']));
            $article['pdf_link'] = env('WP_SITE_URL').'pdflawupdate/?pageID='.$articleData['ID'];

            $_content = $articleData->meta->content;

            $article['read_time_display'] = CommonHelper::bm_estimated_reading_time($_content);
            $article['read_time_seconds'] = CommonHelper::bm_estimated_reading_time($_content, 'calculate');

            if($isFull)
            {
                $article['content'] = html_entity_decode($_content);
            }

            $article['short_description'] = CommonHelper::getShortDescriptionForArticle($_content);
            $article['in_reading_list'] = $hasInReadingList;
            $article['user_read_seconds'] = $user_read_seconds;
            $article['article_web_link'] = env('WP_SITE_URL').'law-update-articles/'.$articleData->slug;

            $article['in_continue_reading_list'] = $userLibraryModel->logicCheckArticleHasInContinueReadingList($_userId, $articleData['ID'], $article['read_time_seconds']);

            //$article['category_id'] = $articleData->meta->lawUpdateArticleMonth;
            //$article['content'] = $articleData->meta->content;
            /*$article['category'] = $articleMonthText;
            $article['practices'] = $arrArticlePractices;
            $article['sectors'] = $arrArticleSectors;
            $article['writers'] = $arrArticleUsers;
            $article['not_writers'] = $arrArticleNotWriters;
            */

            return $article;
        }
        else if($postType == 'blogposts')
        {
            $articleWriters     = $articleData->acf->blogWriters;

            $txtPractices = array();
            $txtSectors = array();
            $txtWriters = array();

            //article writers!
            $arrArticleUsers = array();

            foreach($articleWriters as $articleWriterKey => $articleWriterValue)
            {
                $_lawUpdateArticleWriter = $articleWriterValue['blogWriter'];

                $arrArticleUsers[] = array( 
                                              'id' => $_lawUpdateArticleWriter->ID, 
                                              'name' => $_lawUpdateArticleWriter->post_title 
                                        );

                $txtWriters[] = $_lawUpdateArticleWriter->post_title;
            }

            $article = [];
            $article['type'] = $postType;
            $article['id'] = $articleData['ID'];
            $article['title'] = $articleData['post_title'];
            // $article['image'] = @WordpressPost::find($articleData->mobileAppLarge)->url;
            $article['image'] = CommonHelper::_getImage($articleData->mobileAppLarge);
            $article['thumb_image'] = CommonHelper::_getImage($articleData->mobileAppThumb, true);
            $article['writers'] = implode(' / ', $txtWriters);
            $article['post_date'] = date('Y-m-d H:i:s', strtotime($articleData['post_date']));

            $_content = $articleData->meta->content;

            $article['read_time_display'] = CommonHelper::bm_estimated_reading_time($_content);
            $article['read_time_seconds'] = CommonHelper::bm_estimated_reading_time($_content, 'calculate');



            if($isFull)
            {
                $article['content'] = $_content;
            }

            $article['short_description'] = CommonHelper::getShortDescriptionForArticle($_content);
            $article['in_reading_list'] = $hasInReadingList;
            $article['user_read_seconds'] = $user_read_seconds;
            $article['article_web_link'] = env('WP_SITE_URL').'insights/blog/'.$articleData->slug;

            $article['in_continue_reading_list'] = $userLibraryModel->logicCheckArticleHasInContinueReadingList($_userId, $articleData['ID'], $article['read_time_seconds']);

            return $article;
        }
        else if($postType == 'publication')
        {
            $articleImage     = $articleData->acf->publicationImage;

            if($articleImage)
            {
                $articleImage = $articleImage->url;
            }

            $publicationTitle     = $articleData->acf->publicationTitle;
            $publicationURL     = $articleData->acf->publicationURL;

            $publicationPDFUrl     = $articleData->acf->publicationPDFUrl;

            if($publicationPDFUrl)
            {
                $publicationPDFUrl = $publicationPDFUrl->url;
            }

            $article = [];
            $article['type'] = $postType;
            $article['id'] = $articleData['ID'];
            $article['title'] = $articleData['post_title'];
            $article['image'] = $articleImage;
            $article['pdf_url'] = $publicationPDFUrl;
            $article['web_url'] = $publicationURL;
            $article['post_date'] = date('Y-m-d H:i:s', strtotime($articleData['post_date']));
            $article['content'] = '';
            $article['short_description'] = '';
            $article['in_reading_list'] = $hasInReadingList;
            $article['user_read_seconds'] = $user_read_seconds;
            $article['article_web_link'] = '';
            $article['read_time_display'] = '';
            $article['read_time_seconds'] = 0;

            $article['in_continue_reading_list'] = $userLibraryModel->logicCheckArticleHasInContinueReadingList($_userId, $articleData['ID'], $article['read_time_seconds']);


            return $article;

        }
        else if($postType == 'news-room')
        {
            $article = [];
            $article['type'] = $postType;
            $article['id'] = $articleData['ID'];
            $article['title'] = $articleData['post_title'];
            // $article['image'] = @WordpressPost::find($articleData->mobileAppLarge)->url;
            $article['image'] = CommonHelper::_getImage($articleData->mobileAppLarge);
            $article['thumb_image'] = CommonHelper::_getImage($articleData->mobileAppThumb, true);
            $article['post_date'] = date('Y-m-d H:i:s', strtotime($articleData['post_date']));

            $_content = $articleData->meta->content;

            $article['read_time_display'] = CommonHelper::bm_estimated_reading_time($_content);
            $article['read_time_seconds'] = CommonHelper::bm_estimated_reading_time($_content, 'calculate');

            if($isFull)
            {
                $article['content'] = $_content;
            }

            $article['short_description'] = CommonHelper::getShortDescriptionForArticle($_content);
            $article['in_reading_list'] = $hasInReadingList;
            $article['user_read_seconds'] = $user_read_seconds;
            $article['article_web_link'] = env('WP_SITE_URL').'news/'.$articleData->slug;

            $article['in_continue_reading_list'] = $userLibraryModel->logicCheckArticleHasInContinueReadingList($_userId, $articleData['ID'], $article['read_time_seconds']);

            return $article;

        }
        else if($postType == 'video-gallery')
        {
            $articleImage     = $articleData->acf->videoImage;

            if($articleImage)
            {
                $articleImage = $articleImage->url;
            }

            $videoID     = $articleData->acf->videoID;
            $videoDate     = $articleData->acf->videoDate;
            $videoContentField     = $articleData->acf->videoContentField;

            $article = [];
            $article['type'] = $postType;
            $article['id'] = $articleData['ID'];
            $article['title'] = $articleData['post_title'];
            $article['image'] = $articleImage;
            $article['youtube_video_id'] = $videoID;
            $article['video_date'] = date('Y-m-d H:i:s', strtotime($videoDate));
            $article['post_date'] = date('Y-m-d H:i:s', strtotime($articleData['post_date']));

            if($isFull)
            {
                $article['content'] = $videoContentField;
            }

            $_content = $videoContentField;

            $article['read_time_display'] = CommonHelper::bm_estimated_reading_time($_content);
            $article['read_time_seconds'] = CommonHelper::bm_estimated_reading_time($_content, 'calculate');

            $article['short_description'] = CommonHelper::getShortDescriptionForArticle($_content);
            $article['in_reading_list'] = $hasInReadingList;
            $article['user_read_seconds'] = $user_read_seconds;
            $article['article_web_link'] = env('WP_SITE_URL').'insights/video-gallery/'.$articleData->slug;

            $article['in_continue_reading_list'] = $userLibraryModel->logicCheckArticleHasInContinueReadingList($_userId, $articleData['ID'], $article['read_time_seconds']);


            return $article;
        }
        else if($postType == 'lawyer')
        {
            $callFrom = '';

            if(isset($articleData['call_from']))
            {
                $callFrom = $articleData['call_from'];
            }

            if($callFrom == 'dropdown')
            {
                $article = [];
                $article['id'] = $articleData['ID'];
                $article['title'] = $articleData['post_title'];
            }
            else
            {
                $content     = $articleData->acf->biography;
                
                $education = $articleData->acf->LawyerAppEducations;
                $profile_image = @WordpressPost::find($articleData->profile_image)->url;

                $educationArr = array();
                if($education)
                {
                  foreach($education as $edu)
                  {
                    $educationArr[] = $edu['LawyerAppEducation'];
                  }
                }

                $language = $articleData->acf->LawyerAppLangugaes;

                $languageArr = array();
                if($language)
                {
                  foreach($language as $lang)
                  {
                    $languageArr[] = $lang['LawyerAppLangugae'];
                  }
                }

                $languagestring = implode(',', $languageArr);

                $practices = $articleData->acf->practices;

                $practicesArr1 = array();
                if($practices)
                {
                  foreach($practices as $lang)
                  {
                    $practicesArr1[] = $lang['practice']['post_title'];
                  }
                }
                $practicesString = implode(',', $practicesArr1);

                $lawyerLocations = $articleData->acf->lawyerLocations;

                $arrLawyerLocationNames = array();

                if($lawyerLocations)
                {
                    foreach($lawyerLocations as $_ll_key => $_ll_value)
                    {
                        $officeLocationTitle = $_ll_value['lawyerLocation']['post_title'];

                        $officeLocationCountry = '';

                        if(isset($_ll_value['lawyerLocation']->acf))
                        {
                            if(isset($_ll_value['lawyerLocation']->acf->cityCountryLocation))
                            {
                                $officeLocationCountry = $_ll_value['lawyerLocation']->acf->cityCountryLocation['post_title'];
                            }
                        }

                        $officeLocationCountry = $_ll_value['lawyerLocation']->acf->cityCountryLocation['post_title'];

                        if($officeLocationCountry)
                        {
                            $officeLocationTitle = $officeLocationTitle . ', ' . $officeLocationCountry;
                        }

                        $arrLawyerLocationNames[] = $officeLocationTitle;
                    }
                }

                $lawyerLocationNames = '';
                if(is_array($arrLawyerLocationNames) && count($arrLawyerLocationNames) > 0)
                {
                    $lawyerLocationNames = implode(' / ', $arrLawyerLocationNames);
                }

                //practice!
                $practices_array = array();
                $practices = $articleData->acf->practices;
                foreach($practices as $index => $practice)
                {
                    $practices_array[] = $practice['practice']['post_title'];
                }

                $txt_practices = '';
                if(is_array($practices_array) && count($practices_array) > 0)
                {
                    $txt_practices = implode(' / ', $practices_array);
                }

                //sectors!
                $sectors_array = array();
                $lawyerSectors = $articleData->acf->lawyerSectors;
                foreach($lawyerSectors as $index => $lawyerSector)
                {
                    $sectors_array[] = $lawyerSector['lawyerSector']['post_title'];
                }

                $txt_sectors = '';
                if(is_array($sectors_array) && count($sectors_array) > 0)
                {
                    $txt_sectors = implode(' / ', $sectors_array);
                }
                
                $article = [];
                $article['type'] = $postType;
                $article['id'] = $articleData['ID'];
                $article['title'] = $articleData['post_title'];
                // $article['image'] = CommonHelper::_getImage($articleData->mobileAppLarge);
                $article['image'] = $profile_image;
                // $article['thumb_image'] = CommonHelper::_getImage($articleData->mobileAppThumb, true);
                $article['designation'] = $articleData->meta->designation;
                $article['phone'] = $articleData->meta->contact_no;
                $article['email'] = $articleData->meta->email;
                $article['office'] = $lawyerLocationNames;
                $article['practices'] = $txt_practices;
                $article['sectors'] = $txt_sectors;
                
                if($isFull)
                {
                    $article['biography'] = $content;
                    $article['education'] = $educationArr;
                    // $article['education'][] = 'LL.M., Harvard School of Law'; //TODO: make it dynamic!
                    // $article['education'][] = 'LL.B., Al Ain Law School'; //TODO: make it dynamic!

                    // $article['practices_full'] = 'Arbitration, Litigation, Family Business & Private Wealth'; //TODO: make it dynamic!
                    $article['practices_full'] = $practicesString; //TODO: make it dynamic!

                    // $article['languages'] = 'Arabic, English'; //TODO: make it dynamic!
                    $article['languages'] = $languagestring; //TODO: make it dynamic!

                    $article['has_related_articles'] = false;
                }

            }

            return $article;
        }
        else if($postType == 'connect')
        {
            $article = [];
            $article['type'] = 'connect';
            $article['id'] = $articleData['id'];
            $article['title'] = $articleData['display_name'];
            $article['image'] = @WordpressPost::find($articleData->mobileAppLarge)->url;
            $article['designation'] = $articleData['title'];
            $article['phone'] = $articleData['mobile_number'];
            $article['email'] = $articleData['email'];
            $article['department'] = $articleData['department'];
            $article['office_address'] = $articleData['office_address'];

            return $article;
        }
        else if($postType == 'event')
        {
            $eventCallFrom = '';

            if(isset($articleData['call_from']))
            {
                $eventCallFrom = $articleData['call_from'];
            }

            $startDate  = $articleData['start_date'];
            $endDate    = $articleData['end_date'];

            $eventDate = '';
            if($startDate)
            {
                $eventDate = date('d', strtotime($startDate));
            }

            $eventMonth = '';
            if($startDate)
            {
                $eventMonth = date('M', strtotime($startDate));

                if($eventMonth)
                {
                    $eventMonth = strtoupper($eventMonth);
                }
            }

            unset($articleData['start_date']);
            unset($articleData['end_date']);

            $article = [];

            $article['id'] = $articleData['id'];
            $article['name'] = $articleData['name'];
            $article['display_date'] = $eventDate;
            $article['display_month'] = $eventMonth;
            $article['text_date'] = date('d F Y', strtotime($startDate)) . ' - ' . date('d F Y', strtotime($endDate));
            $article['text_time'] = date('h:i A', strtotime($startDate)) . ' - ' . date('h:i A', strtotime($endDate));
            $article['text_location'] = $articleData['location']; //-->'Jeddah, Riyadh & Al Khobar'; //TODO: make it dynamic!

            // str_replace(PHP_EOL, ' ', $articleData['location']);

            if($eventCallFrom == 'view_upcoming_event')
            {
                $article['type'] = 'upcoming'; //TODO: make it dynamic!
                $article['text_type'] = 'Upcoming Event'; //TODO: make it dynamic!
                $article['text_start'] = 'Start in 3 days'; //TODO: make it dynamic!
            }
            else if($eventCallFrom == 'view_pending_event')
            {
                $article['type'] = 'pending'; //TODO: make it dynamic!
                $article['text_type'] = 'Pending RSVP'; //TODO: make it dynamic!
                $article['text_start'] = ''; //TODO: make it dynamic!
            }
            else //if($eventCallFrom == 'view_all_event')
            {
                if(($articleData['id'] % 2) == 0) //TODO: make it dynamic!
                {
                    $article['type'] = 'upcoming'; //TODO: make it dynamic!
                    $article['text_type'] = 'Upcoming Event'; //TODO: make it dynamic!
                    $article['text_start'] = 'Start in 3 days'; //TODO: make it dynamic!
                } 
                else
                {
                    $article['type'] = 'pending'; //TODO: make it dynamic!
                    $article['text_type'] = 'Pending RSVP'; //TODO: make it dynamic!
                    $article['text_start'] = ''; //TODO: make it dynamic!
                }
            }

            if($isFull)
            {
                $article['text_location'] = $articleData['location'];

                // $article['image']   = @WordpressPost::find($articleData->mobileAppLarge)->url;
                $article['image']   = CommonHelper::_getImage($articleData->mobileAppLarge);

                $article['thumb_image']   = CommonHelper::_getImage($articleData->mobileAppThumb, true);
                
                $article['content'] = $articleData['description'];
                
                $article['topics'] = array();

                if($articleData['topic1'])
                {
                    $article['topics'][] = array(
                                                'text' => $articleData['topic1'],
                                                'color' => '#DFA872',
                                            );
                }

                if($articleData['topic2'])
                {
                    $article['topics'][] = array(
                                                'text' => $articleData['topic2'],
                                                'color' => '#FE8668',
                                            );
                }

                if($articleData['topic3'])
                {
                    $article['topics'][] = array(
                                                'text' => $articleData['topic3'],
                                                'color' => '#DFA872',
                                            );
                }
                
                $article['agenda'] = $articleData['agenda'];

                //speaker_details
                $speakerDetails = $articleData['speaker_details'];

                $arrSpeakers =  array();

                foreach($speakerDetails as $speakerInfo)
                {
                    $arrSpeakers[] = array(
                                                'name'  => $speakerInfo->name,
                                                'title' => $speakerInfo->title,
                                                'email' => $speakerInfo->email,
                                        );

                }

                $article['speaker_details'] = $arrSpeakers;

                /*
                //location_details
                $arrLocations =  array();
                $arrAgenda = array();

                if($articleData['id'] == 1)
                {
                    $arrLocations[]  = array(
                                                'name' => 'Jeddah',
                                                'date' => 'Date: Mon, 3 July 2019',
                                                'time' => 'Time: 07:00 - 09:15',
                                                'location' => 'Location: Elaf Galleria Hotel'

                                            );

                     $arrLocations[]  = array(
                                                'name' => 'Riyadh',
                                                'date' => 'Date: Mon, 5 July 2019',
                                                'time' => 'Time: 08:00 - 10:15',
                                                'location' => 'Location: Rosh Rayhaan by Rotana'

                                            );

                     $arrLocations[]  = array(
                                                'name' => 'Al Khobar',
                                                'date' => 'Date: Mon, 7 July 2019',
                                                'time' => 'Time: 09:00 - 11:15',
                                                'location' => 'Location: Mövenpick'

                                            );

                     //agenda_details!
                     $arrAgenda['heading'] = 'The Agenda for each of the Saudi Arabia Tax events will be as follows:';
                     
                     $arrAgenda['timings'][] = array('time' => '09:00 – 09:30', 'label' =>'Registration and Breakfast');
                     $arrAgenda['timings'][] = array('time' => '09:30 – 11:30', 'label' =>'Main Presentation');
                     $arrAgenda['timings'][] = array('time' => '11:30 – 12:00', 'label' =>'Q&A');
                     $arrAgenda['timings'][] = array('time' => '12:00 – 12:15', 'label' =>'Networking');

                }

                //$article['location_details'] = $arrLocations;
                //$article['agenda_details'] = $arrAgenda;
                */

                $article['text_header_time'] = '10:00 AM'; //TODO: make it dynamic!
                $article['text_header_location'] = 'Saudi Arabia'; //TODO: make it dynamic!
                $article['text_invitee_location'] = 'You have accepted "Jeddah" Location for this event!'; //TODO: make it dynamic!

                $article['text_enquiry'] = 'For any further enquiries, please email events@tamimi.com.';
                $article['label_topic'] = 'Our seminar will cover the following topics:';
                $article['label_speaker'] = 'Agenda and Speakers';
                $article['label_agenda'] = 'The Agenda for '. $articleData['name'] .' will be as follows:';

            }

            return $article;

        }

    }

    static function __getLawyerImage($value)
    {
        // $data = WordpressPost::find($id);
        // return $data['guid'];
        $image = $value->acf->profile_image;
        return $image->url;
    }

    static function contructLog($request) 
    {
        $return = array();

        $return['api_start_time'] = microtime(true);

        $headers = getallheaders();
        
        $user_id = 0;
        $token = '';
        if(isset($headers['Userid']))
        {
            $user_id = $headers['Userid'];
        }  
        if(isset($headers['accesstoken']))
        {
            $token = $headers['accesstoken'];
        }       
        
        $_post = $request->input(); //-->@$_REQUEST; //-->@$_POST;
        if(isset($_post['user_id']) )
        {
          if(!empty($_post['user_id']))
          {
            $user_id = $_post['user_id'];
          }
        }
        $_post_params = json_encode($_post);
        
        if(!$_post_params)
        {
            $_post_params = $_post;
        }
        if(empty($user_id))
        {
          // $data["error"]    = '1';
          // $data["message"]  = "User id not provided.";

          // return ($data); 
        }

        $_accessToken = AccessToken::where('user_id', $user_id)->where('token', $token)->count();

        if($_accessToken == 0)
        {
          // $data["error"]    = '1';
          // $data["message"]  = "Invalid token.";
          // return ($data); 
        }
        $ipAddress = $request->ip();
        
        $logData['user_id']         = $user_id; 
        $logData['service']         = $request->route()->getActionMethod();
        $logData['header_params']   = json_encode($headers);
        $logData['post_params']     = $_post_params; //-->json_encode($_POST);
        $logData['response']        = NULL;
        $logData['request_time']    = date('Y-m-d H:i:s');
        $logData['response_time']   = NULL;
        $logData['ip_address']      = $ipAddress;

        $logDataInfo = LogsAPIs::updateOrCreate(['id' => 0], $logData);

        if($logDataInfo)
        {
           $return['api_log_id'] = $logDataInfo->id;
        }

        $return['user_id'] = $user_id;
        
        return $return;
    }

    static function signupEmployee($email, $info=array())
    {
        $first_name = @$info['first_name'];
        $last_name  = @$info['last_name'];

        $user = User::where('email' , $email)->first();

        $defaultPassword = config('constants.SAML_SIGNUP_DEFAULT_PASSWORD');

        if($user) //user already found with this email!
        {
            if(!$user->hasRole(config('api.roles.employee')))
            {
                $user->assignRole(config('api.roles.employee'));
            }
        }
        else
        {
            $user = User::create([

              'first_name'  => $first_name,
              'last_name'   => $last_name,
              'email'       => $email,
              'password'    => Hash::make($defaultPassword),
          ]);

          if($user)
          {
            $userId = $user->id;

            if($userId)
            {
              $user->assignRole(config('api.roles.employee'));
            }
          }
        }
    }
    static function checkSamlAccount($email, $saml_id)
    {
      if($email)
      {
        if($saml_id)
        {
          $logSaml = LogsSAML::where('response_email', $email)->where('saml_id', $saml_id)->count();
          if($logSaml > 0)
          {
            return true;
          }
        }
      }
      return false;
    }
    static function matterAmountFormatWithCurrency($currency, $amount)
    {
        return $currency . ' ' . @number_format($amount, 2);
    }

    static function _getMenus()
    {
        $menuItems = array();

        $menuItems['home']              = ['title' => 'Home', 'has_access' => true, 'orderPriorityIndex' => 0];
        $menuItems['matters']           = ['title' => 'My Matters', 'has_access' => true, 'orderPriorityIndex' => 1];
        $menuItems['insights']          = ['title' => 'Insights', 'has_access' => true, 'orderPriorityIndex' => 2];
        $menuItems['library']           = ['title' => 'My Library', 'has_access' => true, 'orderPriorityIndex' => 3];
        $menuItems['calender']          = ['title' => 'My Calender', 'has_access' => true, 'orderPriorityIndex' => 4];
        $menuItems['contact_us']        = ['title' => 'Contact Us', 'has_access' => true, 'orderPriorityIndex' => 5];
        $menuItems['about_us']          = ['title' => 'About Us', 'has_access' => true, 'orderPriorityIndex' => 6];
        $menuItems['lawyers']           = ['title' => 'Find a Lawyer', 'has_access' => true, 'orderPriorityIndex' => 7];
        // $menuItems['client_services']   = ['title' => 'Client Services', 'has_access' => true, 'orderPriorityIndex' => 8];
        $menuItems['careers']           = ['title' => 'Careers', 'has_access' => true, 'orderPriorityIndex' => 9];
        $menuItems['feedback']          = ['title' => 'Feedback', 'has_access' => true, 'orderPriorityIndex' => 10];


        $dashboardItems = array();
        
        $dashboardItems['insights']          = ['title' => 'Insights', 'has_access' => true, 'color' => '4D4D85'];
        $dashboardItems['ask_essam']         = ['title' => 'Ask Essam', 'has_access' => true, 'color' => '117B92'];
        $dashboardItems['lawyers']           = ['title' => 'Find a Lawyer', 'has_access' => true, 'color' => 'A1B2C2'];
        $dashboardItems['library']           = ['title' => 'My Library', 'has_access' => true, 'color' => '794274'];
        $dashboardItems['calender']          = ['title' => 'My Calender', 'has_access' => true, 'color' => '84838D'];
        $dashboardItems['matters']           = ['title' => 'My Matters', 'has_access' => true, 'color' => '3A3B76'];
        $dashboardItems['events']            = ['title' => 'Events', 'has_access' => true, 'color' => '1131141'];
        $dashboardItems['connect']           = ['title' => 'Connect', 'has_access' => true, 'color' => '148190'];
        $dashboardItems['elearning']         = ['title' => 'E-Learning', 'has_access' => true, 'color' => '188127'];

        return array('menu' => $menuItems, 'dashboard' => $dashboardItems);

    }

    static function getLoginMenus($user)
    {
      $_menu = CommonHelper::_getMenus();
      
      $menuItems = $_menu['menu'];
      $dashboardItems = $_menu['dashboard'];

      $myDashboardItems = array();
      $myMenuItems = array();
      $myMenuItems = $menuItems;
      if($user->hasRole(config('api.roles.client')))
      {
          $myDashboardItems['matters'] = $dashboardItems['matters'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          //menu items!
          //-->$myMenuItems['matters']['has_access']     = false; //show all menu for client!
      }
      else if($user->hasRole(config('api.roles.subscribed')))
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else if($user->hasRole(config('api.roles.employee')))
      {
         $myDashboardItems['insights'] = $dashboardItems['insights'];
         $myDashboardItems['events'] = $dashboardItems['events'];
         $myDashboardItems['connect'] = $dashboardItems['connect'];
         $myDashboardItems['library'] = $dashboardItems['library']; 
         //menu items!
         $myMenuItems['matters']['has_access']     = false;
         unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else //guest-user
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          $myDashboardItems['library'] = $dashboardItems['library'];
          //dashboard items!
          $myDashboardItems['library']['has_access'] = false;
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          $myMenuItems['library']['has_access']     = false;
          $myMenuItems['calender']['has_access']    = false;
          // unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }

      return array('menu' => $myMenuItems, 'dashboard' => $myDashboardItems);
    }

    static function getLoginEmployeesMenus($user)
    {
      $_menu = CommonHelper::_getMenus();
      
      $menuItems = $_menu['menu'];
      $dashboardItems = $_menu['dashboard'];

      $myDashboardItems = array();
      $myMenuItems = array();
      $myMenuItems = $menuItems;
      if($user->hasRole(config('api.roles.client')))
      {
          $myDashboardItems['matters'] = $dashboardItems['matters'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['matters']['orderPriorityIndex']     = 0;
          $myDashboardItems['ask_essam']['orderPriorityIndex']   = 1;
          $myDashboardItems['calender']['orderPriorityIndex']    = 2;
          $myDashboardItems['insights']['orderPriorityIndex']    = 3;
          //menu items!
          //-->$myMenuItems['matters']['has_access']     = false; //show all menu for client!
      }
      else if($user->hasRole(config('api.roles.subscribed')))
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          $myDashboardItems['insights']['orderPriorityIndex']     = 0;
          $myDashboardItems['ask_essam']['orderPriorityIndex']    = 1;
          $myDashboardItems['calender']['orderPriorityIndex']     = 2;
          $myDashboardItems['lawyers']['orderPriorityIndex']      = 3;
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else if($user->hasRole(config('api.roles.employee')))
      {
         $myDashboardItems['insights'] = $dashboardItems['insights'];
         $myDashboardItems['events'] = $dashboardItems['events'];
         $myDashboardItems['connect'] = $dashboardItems['connect'];
         $myDashboardItems['library'] = $dashboardItems['library']; 
         $myDashboardItems['insights']['orderPriorityIndex']      = 0;
         $myDashboardItems['events']['orderPriorityIndex']        = 1;
         $myDashboardItems['connect']['orderPriorityIndex']       = 2;
         $myDashboardItems['library']['orderPriorityIndex']       = 3;
         //menu items!
         $myMenuItems['matters']['has_access']     = false;
         unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else //guest-user
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          $myDashboardItems['library'] = $dashboardItems['library'];
          $myDashboardItems['insights']['orderPriorityIndex']      = 0;
          $myDashboardItems['ask_essam']['orderPriorityIndex']     = 1;
          $myDashboardItems['lawyers']['orderPriorityIndex']       = 2;
          $myDashboardItems['library']['orderPriorityIndex']       = 3;
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          $myMenuItems['library']['has_access']     = false;
          $myMenuItems['calender']['has_access']    = false;
          unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }

      return array('menu' => $myMenuItems, 'dashboard' => $myDashboardItems);

    }

    static function getSignupMenus($user)
    {
      $_menu = CommonHelper::_getMenus();
      
      $menuItems = $_menu['menu'];
      $dashboardItems = $_menu['dashboard'];

      $myDashboardItems = array();
      $myMenuItems = array();
      $myMenuItems = $menuItems;
      if($user->hasRole(config('api.roles.client')))
      {
          $myDashboardItems['matters'] = $dashboardItems['matters'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          //menu items!
          //-->$myMenuItems['matters']['has_access']     = false; //show all menu for client!
      }
      else if($user->hasRole(config('api.roles.subscribed')))
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['calender'] = $dashboardItems['calender'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else if($user->hasRole(config('api.roles.employee')))
      {
         $myDashboardItems['insights'] = $dashboardItems['insights'];
         $myDashboardItems['events'] = $dashboardItems['events'];
         $myDashboardItems['connect'] = $dashboardItems['connect'];
         $myDashboardItems['library'] = $dashboardItems['library']; 
         //menu items!
         $myMenuItems['matters']['has_access']     = false;
         unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      else //guest-user
      {
          $myDashboardItems['insights'] = $dashboardItems['insights'];
          $myDashboardItems['ask_essam'] = $dashboardItems['ask_essam'];
          $myDashboardItems['lawyers'] = $dashboardItems['lawyers'];
          $myDashboardItems['library'] = $dashboardItems['library'];
          //menu items!
          $myMenuItems['matters']['has_access']     = false;
          $myMenuItems['library']['has_access']     = false;
          $myMenuItems['calender']['has_access']    = false;
          unset($myMenuItems['matters']); //remove menu items which we dont have access to!
      }
      return array('menu' => $myMenuItems, 'dashboard' => $myDashboardItems);

    }

    static function DBEncrypt($string)
    {
        $ecryptedData = self::encrypt_decrypt('encrypt', $string);

        return $ecryptedData;
    }

    static function DBDecrypt($string)
    {
      if($string == '')
      {
        return '';
      }

      $decryptedData = self::encrypt_decrypt('decrypt', $string);

      return $decryptedData;

    }

    static function encrypt_decrypt($action, $string) 
    {
        $output = false;
        $encrypt_method = "AES-256-CBC";
        
        $secret_key = env('ENCRYPTION_KEY');
        $secret_iv  = env('ENCRYPTION_IV');
        
        // hash
        $key = hash('sha256', $secret_key);
        
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);

        if ( $action == 'encrypt' ) {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if( $action == 'decrypt' ) {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }

        return $output;
    }

    static function addNotification($data)
    {
      foreach ($data as $input) {
        # code...
        $notification = new NotificationUsers;
        $notification->user_id = @$input['user_id'];
        $notification->email = @$input['email'];
        $notification->type = @$input['type'];
        $notification->heading = @$input['heading'];
        $notification->text = @$input['text'];
        $notification->value = @$input['value'];
        $notification->event_id = @$input['event_id'];
        $notification->event_type = @$input['event_type'];
        $notification->date_time = time();
        $notification->call_from = @$input['call_from'];
        $notification->save();

        if($input['device_id'] == '')
        {
          CommonHelper::NotificationLog( $input['type']. ' device_id - Error', '0', $input['email']. ' device id or type not found.' );
        }
        else
        {
          $notify_data = array(
            'device_id' => $input['device_id'],
            'heading' => $input['heading'],
            'text' => $input['text'],
            'email' => $input['email'],
            'type' => $input['type'],
          );


          self::pushNotification($notify_data);
        }
      }

    }

    static function pushNotification($_data){
      
      $headers = array
      (
       'Authorization: key=' . env('FCM_SERVER_KEY'),
       'Content-Type: application/json'
      );

      $_registration_ids = array();
      $_registration_ids[] = $_data['device_id'];

      $_notification = array();
      $_notification['title'] = $_data['heading'];
      $_notification['body'] = $_data['text'];
      $_notification['sound'] = 'default';

      $_main_data = array();
      $_main_data['registration_ids'] = $_registration_ids;
      $_main_data['mutable_content'] = true;
      $_main_data['notification'] = $_notification;

      $ch = curl_init();
      curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
      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_encode($_main_data) );
      $result = curl_exec($ch );
      curl_close( $ch );

      if(!empty($result))
      {
        $r = json_decode($result);
        if($r->success == 0)
        {
          CommonHelper::NotificationLog( $_data['type'].' Push notification - Error', '0', $_data['email']. ' error: '.json_encode($r) );
        }
        if($r->success == 1)
        {
          CommonHelper::NotificationLog( $_data['type'].' Push notification - Success', '1', $_data['email']. ' sent:'.json_encode($r)  );
        }

      }
       
      return true;
    }


    static function NotificationLog($type, $success, $message)
    {
      $notification_user = new NotificationLogs;
      $notification_user->type = $type;
      $notification_user->success = $success;
      $notification_user->message = $message;
      $notification_user->save();
    }

    static function getConfigValue($key)
    {
      $site_config = @SiteConfiguration::where('meta_key', $key)->first();
      if(!empty($site_config))
      {
        return @$site_config->meta_value;
      }
      return '';
    }

}