<?php

namespace App\Http\Controllers;

use App\Models\Journal;
use App\Models\Issue;
use App\Models\Article;
use App\Models\Chapter;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Subject;
use App\Models\ContentAccess;
use App\Models\MarkList;
use App\Models\UserAccess\UserAccess;
use App\Models\Country;

use Illuminate\Http\Request;

use Auth;
use DB;

class SearchController extends BenthamController
{


     /*
     * Date: 15-12-2018
     * Author: Muhammad Arshad
     * Parameter: Request Parameters
     * Description: This function will search upon requesting keywords of user in amazon cloud search 
                    and return data in json format
     */
    public function amazon_search_get_webservicedata($request, $select_search_mode = 'basic_search')
    {
       // dd($request);
        $searchvalue = "";
        $genre = "";

        //$pagesize = $_REQUEST['search_results_number'];
        $pagesize = isset($request->pagesize) ? $request->pagesize : 10;
        $pageno   = isset($request->pageno) ? $request->pageno : 1;

        $fields    = urlencode($request->fields);
        $isjournal = isset($request->isjournal) ? $request->isjournal : 0;
        $isebook   = isset($request->isebook) ? $request->isebook : 0;
        $daterange = $request->daterange;
        $fromyear  = $request->fromyear ? $request->fromyear : 2000;
        $toyear    = $request->toyear ? $request->toyear: date("Y");

        $select_search_mode = $request->select_search_mode ? $request->select_search_mode : $select_search_mode;
        
        $subject = isset($request->subject) ? $request->subject : 0;
		
		if($fields == ""){
			$fields = 0;
		}

        if ($pageno == 1) {
            $start_from = $pageno-1;

        } else {

            $start_from = ($pageno - 1) * $pagesize;
        }
		if ($start_from < 0){
			$start_from = 0; //abs($start_from);
		}
			

        if ($subject != '0') {
            $subject_arr = '(%20or';
            for ($i = 0; $i < count($subject); $i++) {
                $subject_arr .= "%20subject:%27" . urlencode($subject[$i]) . "%27";
                //$subject="%27".implode("%20subject:%27", $subject)."%27";

            }
            $subject = $subject_arr . ')';
        } else {
            $subject = "";
        }
        
        if($request->journal && $request->method()=='POST'){
            if(is_array($request->journal)){
                $journal = isset($request->journal) ? $request->journal : 0;
            }else{
                $journal = isset($request->journal) ? explode(',',$request->journal) : 0;
            }
        }else{
            
            $journal = isset($request->journal) ? explode(',',$request->journal) : 0;
        }
        
        
        $journal_field = '';
        if ($journal != '0') {
            $journal_arr = '(%20or';
            
            for ($i = 0; $i < count($journal); $i++) {
                $journal_field .= urlencode($journal[$i]).',';
                $journal_arr .= "%20subtitle:%27" . urlencode($journal[$i]) . "%27";

            }            
            $journal_field = rtrim($journal_field,',');
            $journal = $journal_arr . ')';
        } else {
            $journal = "";
        }
        
        if($request->ebook && $request->method()=='POST'){
            if(is_array($request->ebook)){
                $ebook = isset($request->ebook) ? $request->ebook : 0;
            }else{
                 $ebook = isset($request->ebook) ? explode(',',$request->ebook) : 0;
            }
        }else{
            
            $ebook = isset($request->ebook) ? explode(',',$request->ebook) : 0;
        }       
        $ebook_field = '';
        if ($ebook != '0') {
            $ebook_arr = '(%20or';
            
            for ($i = 0; $i < count($ebook); $i++) {
                $ebook_field .= urlencode($ebook[$i]).',';
                $ebook_arr .= "%20journal_ebook_title:%27" . urlencode($ebook[$i]) . "%27";

            }
            $ebook_field = rtrim($ebook_field,',');
            $ebook = $ebook_arr . ')';
        } else {
            $ebook = "";
        }

        $priority = "'title^4','abstract^2','keyword^1','text^0.5'";
        $option   = "&q.options={fields:[" . urlencode($priority) . "]}";
        $paging   = "&size=" . $pagesize . "&start=" . $start_from;

        if ($request->daterange == 'all') {
            $fromyear = 2000;
            $toyear   = date("Y");

            $date = "(%20and%20volumeyear:[%27" . $fromyear . "%27,%27" . $toyear . "%27]";
        } else { 
            $date = "(%20and%20volumeyear:[%27" . $fromyear . "%27,%27" . $toyear . "%27]";
        }
        
            if ($request->searchvalue != "") {

                $searchvalue = htmlentities($request->searchvalue, ENT_QUOTES);
               // dd($str);die;
                $url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($searchvalue . " *"));
               //dd($url); die;
                if ($select_search_mode == 'ws') {
                    $value  = "%22" . urlencode(trim($searchvalue)) . "%22";
                    //$option = "&q.options={fields:[%27title%27,%27abstract%27]}";
                    //$paging = "&size=" . $pagesize . "&start=" . $pageno;
                    $return = "&return=title,subtitle,abstract,affiliation,first_page,last_page,author,volume_title,issue_title,volume_publication_date,id,nid,journal_ebook_title,genre,eissn,doi,issn,volumeyear,issue_publication_date";
                    //$fq="&fq=(and%20keyword:%27".urlencode($keyword)."%27)";
                    //$fq = "&fq=(%20or%20title:%27" . urlencode($request->keyword) . "%27(%20or%20abstract:%27" . urlencode($request->keyword) . "%27))";

                    //$url = "http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=" . $value . $option . $paging . $return;

                    if ($request->keyword != "") {
                        //$url = "http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=" . $value . $fq . $option . $paging . $return;

                    }
                     
                }
            if(!isset($request->btnjournalsearch)){
                $request->btnjournalsearch = 'basic_search';
            }
            if ($request->btnjournalsearch == 'basic_search') {
                    
                    $fq = "&fq=" . $date.')';
                    $url = $url . $fq. $option . $paging;
                    
                }
                else{

                    if ($request->btnjournalsearch != 'advance_search'){
                    $fq = "&fq=" . $date.')';
                        $url = $url . $fq. $option . $paging;                       
                    }
                }
            
            if ($request->btnjournalsearch == 'advance_search') {

                // if($subject!='')
                //{
                if ($isjournal == 1 && $isebook == 1 && $fields == '0') {
                    

                    $fq = "&fq=" . $date . $subject . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27" . "%20issn:%27" . urlencode($searchvalue) . "%27" . "%20text:%27" . urlencode($searchvalue) . "%27" . "%20isbn:%27" . urlencode($searchvalue) . "%27" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27" . "%20title:%27" . urlencode($searchvalue) . "%27))";

                    $url = $url . $fq . $option . $paging;
                    //echo $url;

                } else if ($isjournal == 1 && $isebook == 1 && $fields != '0') {
                    if ($fields == 'title') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;
                    }
                    if ($fields == 'authors') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20author:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;

                    }
                    if ($fields == 'affiliation') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;

                    }
                    if ($fields == 'issn') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20issn:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;
                    }
                    if ($fields == 'isbn') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20isbn:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;

                    }
                    if ($fields == 'text') {
                        $fq  = "&fq=" . $date . $subject . "(%20or%20text:%27" . urlencode($searchvalue) . "%27)" . ")";
                        $url = $url . $fq . $option . $paging;
                    }
                    if ($fields == 'titleabstractkeywords') {
                        $fq = "&fq=" . $date . $subject . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27)";

                        $url = $url . $fq . $option . $paging;
                    }

                }
                if ($isjournal == 1 && $isebook == 0) //all journal any specific ebook
                {
                    if ($fields == '0') // for all fields
                    {

                        $gener = "(%20and%20genre:%27article%27)";
                        if($ebook!='0' && $ebook != "") 
                        {
                         $gener = "(%20or%20genre:%27article%27%20genre:%27ebookvolume%27%20genre:%27chapter%27)";
                        }

                        $fq = "&fq=" . $date . $subject . $ebook . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27" . "%20issn:%27" . urlencode($searchvalue) . "%27" . "%20text:%27" . urlencode($searchvalue) . "%27" . "%20isbn:%27" . urlencode($searchvalue) . "%27" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27" . "%20title:%27" . urlencode($searchvalue) . "%27)".$gener.")";

                        $url = $url . $fq . $option . $paging;
                        //echo $url;
                    } else // for any specific field
                    {
                        if ($fields == 'title') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'authors') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20author:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'affiliation') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'issn') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20issn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'isbn') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20isbn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'text') {
                            $fq  = "&fq=" . $date . $subject . $ebook . "(%20or%20text:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'titleabstractkeywords') {
                            $fq = "&fq=" . $date . $subject . $ebook . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27)";

                            $url = $url . $fq . $option . $paging;
                        }

                    }

                } else if ($isebook == 1 && $isjournal == 0) {
                    //all ebook any specific journal

                    if ($fields == '0') // for all fields
                    {

                        $gener = "(%20or%20genre:%27ebookvolume%27%20genre:%27chapter%27)";
                        if($journal!='0' && $journal != "") 
                        {
                         $gener = "(%20or%20genre:%27article%27%20genre:%27ebookvolume%27%20genre:%27chapter%27)";
                        }

                        $fq = "&fq=" . $date . $subject . $journal . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27" . "%20issn:%27" . urlencode($searchvalue) . "%27" . "%20text:%27" . urlencode($searchvalue) . "%27" . "%20isbn:%27" . urlencode($searchvalue) . "%27" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27" . "%20title:%27" . urlencode($searchvalue) . "%27)".$gener.")";

                        $url = $url . $fq . $option . $paging;
                        

                    } 
                    else // for any specific field
                    {
                        if ($fields == 'title') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'authors') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20author:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'affiliation') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'issn') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20issn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'isbn') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20isbn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'text') {
                            $fq  = "&fq=" . $date . $subject . $journal . "(%20or%20text:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'titleabstractkeywords') {
                            $fq = "&fq=" . $date . $subject . $journal . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27)";

                            $url = $url . $fq . $option . $paging;
                        }

                    }

                } else if ($isjournal == 0 && $isebook == 0) //specific journal and specific ebook
                {

                    if ($fields == '0') // for all fields
                    {

                        $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27" . "%20issn:%27" . urlencode($searchvalue) . "%27" . "%20text:%27" . urlencode($searchvalue) . "%27" . "%20isbn:%27" . urlencode($searchvalue) . "%27" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27" . "%20title:%27" . urlencode($searchvalue) . "%27))";
                        $url = $url . $fq . $option . $paging;
                        //echo $url;
                        

                    } else // for any specific field
                    {
                        if ($fields == 'title') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'authors') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20author:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'affiliation') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20country:%27".urlencode($searchvalue)."%27"."%20affiliation:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'issn') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20issn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'isbn') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20isbn:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;

                        }
                        if ($fields == 'text') {
                            $fq  = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20text:%27" . urlencode($searchvalue) . "%27)" . ")";
                            $url = $url . $fq . $option . $paging;
                        }
                        if ($fields == 'titleabstractkeywords') {
                            $fq = "&fq=" . $date . $subject . $journal . $ebook . "(%20or%20title:%27" . urlencode($searchvalue) . "%27)" . "%20abstract:%27" . urlencode($searchvalue) . "%27" . "%20keyword:%27" . urlencode($searchvalue) . "%27)";

                            $url = $url . $fq . $option . $paging;
                        }
                    }
                }

                //} //end if subject

            }
        }
        
        $url = $url.'&facet.volumeyear={sort:%27bucket%27,size:25}';
        /* if(\Request::ip()=='103.236.135.34'){
           dd($url);
        }*/
        
        //dd($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // $output contains the output string
        $output = curl_exec($ch);
        // close curl resource to free up system resources
        curl_close($ch);
        $pagename="/search?xe=1";
        
        if($searchvalue!=""){
          $pagename .="&searchvalue=".urlencode(trim($searchvalue))."&btnjournalsearch=".$request->btnjournalsearch."&fields=".$fields."&isjournal=".$isjournal."&isebook=".$isebook."&journal=".$journal_field."&ebook=".$ebook_field."&fromyear=".$fromyear."&toyear=".$toyear;

        }

        return array($output, $pageno, $pagesize,$pagename);
    }

    /*
     * Date: 15-12-2018
     * Author: Muhammad Arshad
     * Parameter: Request Parameters
     * Description: This function will search upon requesting keywords of user in amazon cloud search 
                    and return data in json format
     *  This function use in front end only                     
    */

    public function getSearch(Request $request)
    {
        $results ='';
        $pageno =0;
        $pagesize ='';
        $pagename ='';
        $print ='';
        $size ='';
        $num_rows ='';
        $num_pages ='';
        $found =0;
        $results ='';
		$latest_issue = '';
        if ($request->searchvalue == "") {
            $request->searchvalue='science';
        }
       
        if(!empty($request->searchvalue)){
            list($results, $pageno, $pagesize,$pagename) = $this->amazon_search_get_webservicedata($request);
            if($results){   
                $print  = json_decode($results);
               //dd($print); 
                $size   = count($print->hits->hit);     
                $found  = $print->hits->found;       
                $num_rows =$found;  
                $num_pages = ceil($num_rows / $pagesize);  
                if (Auth::user())
                {    
                    if (Auth::user()->id > 0) {

                        $this->AddAccessSearches($request, Auth::user()->id);
                    }
                }
            }
        }
        
        $journal_title = DB::table('journal')->whereRaw('LOWER(title) = LOWER("'.$request->searchvalue.'")')->first();
		if($journal_title)
		{
			$latest_issue        = Issue::getcurrentissue($journal_title->journal_id);
		}

        $subject_list = Subject::Subjects();
        $journal_list = Journal::GetJournalList('',1000);
        $ebook_list = Ebook::GetEbooks('','','off');
        $searchvalue = $request->searchvalue;
        $btnjournalsearch = $request->btnjournalsearch;
        $post_vars = $_POST;
        return view('search',with(['searchvalue' => $searchvalue,
            'latest_issue' => $latest_issue,
            'subject_list' => $subject_list,
            'journal_list' => $journal_list,
            'journal_title' => $journal_title,
            'ebook_list' => $ebook_list,
            'found' => $found,
            'size' => $size,
            'print' => $print,
            'pagesize' => $pagesize,
            'pageno' => $pageno,
            'pagename' => $pagename,
            'num_rows' => $num_rows,
            'num_pages' => $num_pages,
            'post_vars' => $post_vars]));       

    } //   

    public function AddAccessSearches($request, $user_id)
    {
        $SecondsGap = 60;
        $timestamp  = time();
        
        $query = "select * from access_searches_report where (user_id = $user_id and search_term = '".$request->searchvalue."' ) and (unix_timestamp(CURRENT_TIMESTAMP())-timestamp) <= $SecondsGap order by timestamp desc ";
            $gap_res = DB::select($query);
            if ($gap_res) {
                $last_searches_session_userid = $request->session()->getId() . "-" . microtime(true);
                session(['last_searches_session_userid' => $last_searches_session_userid]);
                DB::select("update access_searches_report set timestamp=" . time() . ", session_id='" . session()->get('last_searches_session_userid') . "' where id='".$gap_res[0]->id."'");
        } else {

            if ($user_id != 0 && $request->searchvalue != "") {

                $this->setUserSearchesSession($request,$user_id);

                        $query = DB::select("Insert into access_searches_report (search_term, user_id,  timestamp, ip_address,session_id)
                            values ('".$request->searchvalue."',".$user_id.",".$timestamp.",".ip2long($request->ip()).",'".session()->get('last_searches_session_userid')."')");
            }
        }

    }

    public function GetSearchArticleAccess($article_id)
    {   
        $read_download_type="";
        $type = "";
        $view_type="";
        $art_type_array = array("Editorial", "Preface", "Acknowledgement","Biography","Corrigendum","Erratum","Obituary","Retraction Notice","Withdrawal Notice");
        $article                     = Article::GetArticleDetail($article_id);   

        if($article)
        {

            $is_epub                     = $article->is_epub;
            $article_id                  = $article->article_id;
            $article_nid                 = $article->article_nid;
            $issue_id                    = $article->issue_id;
            $volume_id                   = $article->volume_id;
            $volume_name                 = $article->volume;
            $journal_id                  = $article->journal_id;
            $DownloadAccess              = false;
            $rental                      = "";
            $bundle_content              = "";
            $content_download_type       = $read_download_type ? $read_download_type : "";
            $access_base_text            = "";
            $terms_popup                 = false;
            $checkIfMarked               = false;
            $restricted_user_access_key  = '';
            $restricted_user_access_type = '';
            $user_access_id              = 0;
            $view_option                 = 0;
            $view_abstract               = 1;
            $view_pdf                    = 0;
            $view_html                   = 0;
            //check article level content access
            $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $article_id, "a");

            if ($article_access[0]->total_count > 0) {
                $DownloadAccess = true;
                if ($article_access[0]->access_type == 1) {
                    $content_download_type = 'F';
                    if(!in_array($article->type_name,$art_type_array)){
                    //$access_base_text      = "promotion: free to download";
                    $access_base_text      = "";
                    }else{            
                        $access_base_text= 'free to download';
                    }                        
                    $terms_popup = true;
                } else {
                    $content_download_type = 'FO';
                    $access_base_text      = "open access plus";
                }
            }

            //check issue level content access
            if (!$DownloadAccess && ($is_epub == 0)) {
                $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i");
                if ($article_access[0]->total_count > 0) {
                    $DownloadAccess = true;
                    $free           = true;
                    if ($article_access[0]->access_type == 1) {
                        $content_download_type = 'F';
                        if(!in_array($article->type_name,$art_type_array)){
                        //$access_base_text      = "promotion: free to download";
                        $access_base_text      = "";
                        }else{            
                            $access_base_text= 'free to download';
                        }
                        $terms_popup = true;
                    } else {
                        $content_download_type = 'FO';
                        $access_base_text      = "open access plus";
                    }
                }
            }

            //check volume level content access
            if (!$DownloadAccess && ($is_epub == 0)) {
                $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $volume_id, "v");

                if ($article_access[0]->total_count > 0) {
                    $DownloadAccess = true;
                    $free           = true;
                    if ($article_access[0]->access_type == 1) {
                        $content_download_type = 'F';
                        if(!in_array($article->type_name,$art_type_array)){
                        //$access_base_text      = "promotion: free to download";
                        $access_base_text      = "";
                        }else{            
                            $access_base_text= 'free to download';
                        }
                        $terms_popup = true;
                    } else {
                        $content_download_type = 'FO';
                        $access_base_text      = "open access plus";
                    }

                }
            }

            //check if user has perpetual access (if artcile purchased by login user)
            if (($DownloadAccess == false) && session()->get('user_id')) {
                if (ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $article_id, 'article')[0]->total > 0) {
                    $DownloadAccess        = true;
                    $access_base_text      = "Subscribe";
                    $content_download_type = 'P';
                    $terms_popup           = true;
                }
            }

            if (!$DownloadAccess) {
                // Check User Access Volume Level
                $v_param['volume_id']  = $volume_id;
                $v_param['user_id']    = session()->get('user_id');
                $v_param['ip_address'] = \Request::ip();

                $ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param, array('volume' => true));
                if (!empty($ua_volume_lvl[0])) {

                    $parama['user_access_id']=$ua_volume_lvl[0]->user_access_id;
                    $user_access_info = UserAccess::GetUserAccess($parama);   
                    
                    $view_option                 = $user_access_info->view_option;
                    $DownloadAccess              = $ua_volume_lvl[0]->volume_id;
                    $user_access_id              = $ua_volume_lvl[0]->user_access_id;
                    $content_download_type       = $ua_volume_lvl[0]->content_download_type;
                    $access_base_text            = $ua_volume_lvl[0]->access_base_text;
                    $terms_popup                 = $ua_volume_lvl[0]->terms_popup;
                    $restricted_user_access_key  = $ua_volume_lvl[0]->restricted_user_access_key;
                    $restricted_user_access_type = $ua_volume_lvl[0]->restricted_user_access_type;
                    $type                        = $ua_volume_lvl[0]->type;
                }
            }

            if ($is_epub == 0) {
                if (!$DownloadAccess) {
                    // Check User Access Issue Level
                    $p_issue['issue_id']   = $issue_id;
                    $p_issue['user_id']    = session()->get('user_id');
                    $p_issue['ip_address'] = \Request::ip();

                    $ua_issue_lvl = UserAccess::GetAllContentUserAccess($p_issue, array('issue' => true));

                    if (!empty($ua_issue_lvl[0])) {

                        $parama['user_access_id']=$ua_issue_lvl[0]->user_access_id;
                        $user_access_info = UserAccess::GetUserAccess($parama);   

                        $view_option                 = $user_access_info->view_option;
                        $DownloadAccess              = $ua_issue_lvl[0]->issue_id;
                        $user_access_id              = $ua_issue_lvl[0]->user_access_id;
                        $content_download_type       = $ua_issue_lvl[0]->content_download_type;
                        $access_base_text            = $ua_issue_lvl[0]->access_base_text;
                        $terms_popup                 = $ua_issue_lvl[0]->terms_popup;
                        $restricted_user_access_key  = $ua_issue_lvl[0]->restricted_user_access_key;
                        $restricted_user_access_type = $ua_issue_lvl[0]->restricted_user_access_type;
                        $type                        = $ua_issue_lvl[0]->type;
                    }

                }

                if (!$DownloadAccess) {
                    // Check User Access Article Level
                    $p_article['article_id']     = $article_id;
                    $p_article['user_id']        = session()->get('user_id');
                    $p_article['ip_address']     = \Request::ip();
                    $p_article['disease_access'] = "article";

                    if (session()->get('disease_access')) {
                        $access = "disease";
                    } else {
                        $access = "article";
                    }

                    $ua_article_lvl = UserAccess::GetAllContentUserAccess($p_article, array($access => true));
                    if (!empty($ua_article_lvl[0])) {

                        $parama['user_access_id']=$ua_article_lvl[0]->user_access_id;
                        $user_access_info = UserAccess::GetUserAccess($parama);   

                        $view_option                 = $user_access_info->view_option;
                        $DownloadAccess              = $ua_article_lvl[0]->article_id;
                        $user_access_id              = $ua_article_lvl[0]->user_access_id;
                        $content_download_type       = $ua_article_lvl[0]->content_download_type;
                        $access_base_text            = $ua_article_lvl[0]->access_base_text;
                        $terms_popup                 = $ua_article_lvl[0]->terms_popup;
                        $restricted_user_access_key  = $ua_article_lvl[0]->restricted_user_access_key;
                        $restricted_user_access_type = $ua_article_lvl[0]->restricted_user_access_type;
                        $type                        = $ua_article_lvl[0]->type;
                    }
                }
            }

            if (session()->has('user_id')) {
                $checkIfMarked = MarkList::checkIfMarked(1, $article_nid, session()->get('user_id'));
                if (!empty($checkIfMarked)) {
                    $checkIfMarked = true;
                }
                $sparam['article_id'] = $article_id;
                $sparam['user_id']    = session()->get('user_id');

                //--------------User Bundle Access Check-----------------------
                $bundle_content = BundleOfferController::BundleOfferUserAccess(session()->get('user_id'));

                //--------------Article Rental Check-----------------------
                $rental = Article::CheckArticleRentalAccess($sparam);
                //dd($rental); // echo 1; return;
                if (count($rental) > 0) {
                    $rental                = $rental[0];
                    $content_download_type = 'RT';
                } else {
                    $rental = "";
                }
            }

            if (!empty($DownloadAccess) || $DownloadAccess==true)   
            {       
                if($view_type=="readpdf")
                {   
                    $user_access = UserAccess::where('user_access_id', $user_access_id)->first();
                    $articles   = Article::where('article_id', $article_id)->first();
                    $clientIP                   = ip2long($request->ip());
                    $user_id                    = isset($user_access->user_id) ? $user_access->user_id : session()->get('user_id');
                    $view_pdf = 1;
                    $view_abstract   = 0;
                    // Insert read pdf to download chapter table
                    if ($user_id) 
                    {
                        if (!empty($user_access)) 
                        {

                        $return = app('App\Http\Controllers\ArticleController')->CheckUserAccessOnArticle($request, $articles, $user_access, $restricted_user_access_key, $content_download_type, $clientIP, $user_id);
                        if ($return == false) 
                            {
                            return back();
                            }
                        }
                    }                           
                }
            }
                    $terms_popup = false;
                    return with(['view_option' => $view_option, 'rental' => $rental, 'bundle_content' => $bundle_content, 'DownloadAccess' => $DownloadAccess, 'content_download_type' => $content_download_type, 'access_base_text' => $access_base_text, 'terms_popup' => $terms_popup, 'restricted_user_access_key' => $restricted_user_access_key, 'restricted_user_access_type' => $restricted_user_access_type, 'checkIfMarked' => $checkIfMarked, 'article' => $article, 'user_access_id' => $user_access_id, 'type' => $type, 'view_abstract' => $view_abstract, 'view_pdf' => $view_pdf, 'view_html' => $view_html]);

        }
    }

    public function GetSearchChapterAccess($chapter_id)
    {   
        $read_download_type="";
        $type = "";
        $view_type="";
        
        $chapter_details = Chapter::where('chapter_id',$chapter_id)->first();

        if($chapter_details)
        {

            
            $chapter_id                  = $chapter_details->chapter_id;
            $chapter_nid                 = $chapter_details->nid;            
            $ebook_volume_id             = $chapter_details->ebook_volume_id;            
            $ebook_id                    = $chapter_details->ebook_id;
            $DownloadAccess              = false;
            $content_download_type       = $read_download_type ? $read_download_type : "";
            $access_base_text            = "";
            $terms_popup                 = true;
            $checkIfMarked               = false;
            $restricted_user_access_key  ='';
            $restricted_user_access_type ='';
            $CountMultipleVolumeExist    = 0;
            $bundle_content              = "";
            $user_access_id              = 0;
            $view_option                 = 0;
            $view_abstract               = 1;
            $param                       = array();
            $type                        ='';
            //check article level content access
            $chapter_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $chapter_id, "c");
        if ($chapter_access[0]->total_count > 0)
        {
            $DownloadAccess = true;
            if ($chapter_access[0]->access_type == 1) 
            {
                $content_download_type = 'F';   
            }
            else
            {
                $content_download_type = 'FO';
            }
            $terms_popup           = true;
        }

        //check ebook volume level content access
        if (!$DownloadAccess) {
            $ebook_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");
            
            if ($ebook_access[0]->total_count > 0) {
                $DownloadAccess        = true;
                $free                  = true;
                if ($chapter_access[0]->access_type == 1) 
                {
                    $content_download_type = 'F';   
                }
                else
                {
                    $content_download_type = 'FO';
                }
                $terms_popup           = true;
                
            }
        }

        //check if user has perpetual access (if artcile purchased by login user)
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $ebook_volume_id, 'volume')[0]->total > 0){                        
                $DownloadAccess        = true;
                $access_base_text      = "Subscribe";                        
                $content_download_type = 'P';
                $terms_popup           = true;
            }
        }

        //check if user has perpetual access (if artcile purchased by login user)
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $chapter_id, 'chapter')[0]->total > 0){                        
                $DownloadAccess        = true;
                $access_base_text      = "Subscribe";                        
                $content_download_type = 'P';
                $terms_popup           = true;
            }
        }
        
        if (!$DownloadAccess) 
        {
            // Check User Access Ebook Volume Level 
            $v_param['volume_id'] = $ebook_volume_id;
            $v_param['user_id'] = session()->get('user_id');
            $v_param['ip_address'] = \Request::ip();
            
            $ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param,array('ebook_volume'=>true));
            
            if (!empty($ua_volume_lvl[0])) 
            {
                $parama['user_access_id']=$ua_volume_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($parama);   
                
                $view_option                 = $user_access_info->view_option;
                $DownloadAccess              = $ua_volume_lvl[0]->volume_id;
                $user_access_id              = $ua_volume_lvl[0]->user_access_id;
                $content_download_type       = $ua_volume_lvl[0]->content_download_type;
                $access_base_text            = $ua_volume_lvl[0]->access_base_text;
                $terms_popup                 = $ua_volume_lvl[0]->terms_popup;
                $restricted_user_access_key  = $ua_volume_lvl[0]->restricted_user_access_key;
                $restricted_user_access_type = $ua_volume_lvl[0]->restricted_user_access_type;
                $type                        = $ua_volume_lvl[0]->type;
            }
        }
        
        if (!$DownloadAccess) 
        {
            // Check User Access Chapter Level 
            $p_article['chapter_id'] = $chapter_id;
            $p_article['user_id'] = session()->get('user_id');
            $p_article['ip_address'] = \Request::ip();
            $p_article['disease_access'] = "chapter";

            if(session()->get('disease_access'))
            {
                $access="disease";
            }
            else
            {
                $access="chapter";
            }

            $ua_chapter_lvl = UserAccess::GetAllContentUserAccess($p_article,array($access=>true));

            if (!empty($ua_chapter_lvl[0])) 
            {
                $param['user_access_id']=$ua_chapter_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($param);   
                
                $view_option                 = $user_access_info->view_option;
                $DownloadAccess              = $ua_chapter_lvl[0]->chapter_id;
                $user_access_id              = $ua_chapter_lvl[0]->user_access_id;
                $content_download_type       = $ua_chapter_lvl[0]->content_download_type;
                $access_base_text            = $ua_chapter_lvl[0]->access_base_text;
                $terms_popup                 = $ua_chapter_lvl[0]->terms_popup;
                $restricted_user_access_key  = $ua_chapter_lvl[0]->restricted_user_access_key;
                $restricted_user_access_type = $ua_chapter_lvl[0]->restricted_user_access_type;
                $type                        = $ua_chapter_lvl[0]->type;
            }
        }
        
        if (!empty($DownloadAccess)) 
        {
            $chapter_details->user_access_id = $user_access_id;
        }        
        
                

        /*-----------By Jalil Sahib Instruction------------
        Email Subject: Fwd: Changes Suggested on Eurekaselecet
        Dated: From Mohammad Azhar on 2022-02-08 18:01
        --------------------------------------------------*/
        $terms_popup = false;
                
        return with([
            'view_option' => $view_option,
            'chapter_details' => $chapter_details,                                                                        
            'DownloadAccess' => $DownloadAccess,
            'type' => $type,
            'content_download_type' => $content_download_type,            
            'access_base_text' => $access_base_text,
            'terms_popup' => $terms_popup,
            'restricted_user_access_key' => $restricted_user_access_key,
            'restricted_user_access_type' => $restricted_user_access_type,
            'user_access_id' => $user_access_id]);
        }
    }

    public function GetSearchEbookVolumeAccess($ebook_volume_id)
    {   
        $ebook_volume_details        = array();
        $ebk_vol_access              = null;
        $DownloadAccess              = false;
        $VolumeDownloadAccess        = false;
        $view_option                  = 0;        
        $access_base_text            = '';        
        $content_download_type       = "";
        $terms_popup                 = true;        
        $restricted_user_access_key  = '';
        $restricted_user_access_type = ''; 
        $user_access_id              = 0;       
       
        
        $ebook_volume_details = EbookVolume::GetEbookVolumeById(array('ebook_volume_id'=>$ebook_volume_id))[0];
        
        if($ebook_volume_details)
        {

            //if access given then $DownloadAccess will be true
            if(($DownloadAccess == false) && session()->get('user_id')){     
                if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $ebook_volume_id, 'volume')[0]->total > 0){                        
                    $DownloadAccess        = true;
                    $VolumeDownloadAccess  = true;
                    $access_base_text      = "Subscribe";                        
                    $content_download_type = 'P';
                    $terms_popup           = true;   
                    $ebk_vol_lvl_access    = true;
                }
            }

            // Check User Access Volume Level 
            if (!$DownloadAccess) 
            {
                $v_param['volume_id'] = $ebook_volume_id;
                $v_param['user_id'] = session()->get('user_id');
                $v_param['ip_address'] = \Request::ip();
                
                $ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param,array('ebook_volume'=>true));
                
                if (!empty($ua_volume_lvl[0])) 
                {
                    $DownloadAccess = $ua_volume_lvl[0]->volume_id;
                    $VolumeDownloadAccess = $ua_volume_lvl[0]->volume_id;
                    $content_download_type = $ua_volume_lvl[0]->content_download_type;
                    $restricted_user_access_key = $ua_volume_lvl[0]->restricted_user_access_key;
                    $user_access_id =$voparam['user_access_id'] = $user_access_id = $ua_volume_lvl[0]->user_access_id;
                    $vol_type = $ua_volume_lvl[0]->type;
                    $terms_popup = $ua_volume_lvl[0]->terms_popup;
                    $access_base_text = $ua_volume_lvl[0]->access_base_text;
                    $voinfo = UserAccess::GetUserAccessInfo($voparam);
                    $view_option = $voinfo->view_option;
                }
            }

            return with(['ebook_volume_details' => $ebook_volume_details,            
            'DownloadAccess' => $DownloadAccess,  
            'VolumeDownloadAccess' => $VolumeDownloadAccess,
            'view_option'    =>  $view_option,
            'content_download_type' => $content_download_type,
            'restricted_user_access_key' => $restricted_user_access_key,  
            'user_access_id' => $user_access_id,          
            'access_base_text' => $access_base_text,            
            'terms_popup' => $terms_popup,
            'restricted_user_access_type' => $restricted_user_access_type,
            ]);

        }
    }

	/*
		Author: Zubair Ashraf
		Date:  31 Aug,2023
		Description: 
	*/

	public function getJournalSearch(Request $request)
	{
		//dd($request);
		
		$results = '';
		$pageno = 0;
		$pagesize = '';
		$pagename = '';
		$print = '';
		$size = '';
		$num_rows = '';
		$num_pages = '';
		$found = 0;
		$APC_charges = "";
		$data_arr = array();
		$prep_dictionary = ["is","am","are","was","were","will","would","shall","should","can","colud","may","might","must","ought","i","we","me","he","she","they","there","their","us","myself","herself","themself","you","themseleve","it","then","a","of","from","form","the","with","also","his","him","her","on","taking","first","take","took","has","have","which","that","per","to","be","in","like","and","an","by","or","not","does","at","for","these","when","because","between","thus","many","years","as","ourself","ourselves","those","found"];
		$occurences = array();
		$journalSearch = "";
		$journal_list = array();
		$journal_average_decision_list = array();
		$journal_acceptance_rates_list = array();

		// Listing ten journals by default
		if ($request->searchvalue == "" && $request->abstract == "") {
			$journals = Journal::GetJournallistsofJournalFinder();

			foreach ($journals as $journal) {
				$current_journal = array();

				$current_journal['journal_id'] = $journal->journal_id;
				$current_journal['jms_code'] = $journal->jms_jcode;
				$current_journal['journal_title'] = $journal->title;
				$current_journal['issn'] = $journal->issn;
				$current_journal['ScopusCiteScore'] = $journal->ScopusCiteScore;
				$current_journal['journal_impact_factor'] = $journal->org_impact_factor;
				$current_journal['aims_and_scope'] = strip_tags(html_entity_decode($journal->aims_and_scope));
				$current_journal['image_file_name'] = $journal->image_file_name;
				$current_journal['image_file_name'] = $journal->image_file_name;
				$current_journal['journal_subject'] = $journal->journal_subject;

				$article_list = Article::GetLatestArticle($journal->journal_id);
				$publication_time = Journal::GetAveragePublicationTime($journal->subtitle);

				if (isset($publication_time->avg_time_till_acceptance_2023)) {
					$numberOfDays = $publication_time->avg_time_till_acceptance_2023;

					if ($numberOfDays > 0 && $numberOfDays <= 180) {
						$current_journal['publication_time'] = $numberOfDays . " days";
					} else {
						$current_journal['publication_time'] = "";
					}
				} else {
					$current_journal['publication_time'] = "";
				}

				$publication_fees = Journal::GetPublicationFeesbyJMSCode($journal->jms_jcode);

				if (isset($publication_fees->APC)) {
					$apc_charges = $publication_fees->APC;
					$current_journal['APC_charges'] = "$" . $apc_charges;
				} else {
					$current_journal['APC_charges'] = "";
				}

				for ($j = 0; $j < count($article_list); $j++) {
					$current_journal['article'][$j]['article_id'] = $article_list[$j]->article_id;
					$current_journal['article'][$j]['article_title'] = $article_list[$j]->title;
				}

				$journal_list[]  = $current_journal;
				
				$jms_code_list[] = $journal->jms_jcode;
			}
			
			$formatted_jms_codes = implode(', ', array_map(function ($item) {
				return "'$item'";
			}, $jms_code_list));
			$jms_code_list = trim($formatted_jms_codes, "'");

			if (!empty($jms_code_list)) {
				$journal_average_decision_list = Journal::GetJournalAverageFirstDecision($jms_code_list);
				$journal_acceptance_rates_list = Journal::GetJournalAcceptanceRate($jms_code_list);
			}
		}

		if ($request->searchOption == "") {
			$searchOption = 'keywords';
		} else {
			$searchOption = $request->searchOption;
		}

		if ($request->searchOption == "keywords") {
			$searchvalue = $journalSearch = trim($request->searchvalue);
			
			if (strpos($searchvalue, '"') !== false) {
				
				$request->merge(['searchvalue' => $searchvalue]);
				
			}else{
				$words = preg_split('/[\s,]+/', $searchvalue);

				$variations = array_map(function($word) {
					return $word . '*';
				}, $words);
				
				$variations_with_space = array_map(function($word) {
					return $word . ' *';
				}, $words);
				
				$pattern = implode('|', array_merge($variations, $variations_with_space));
				
				$request->merge(['searchvalue' => $pattern]);
			}
			//dd($request->searchvalue);
		}
		
		if ($request->searchOption == "abstract"){
			$abstractSearch = $journalSearch = htmlentities(trim($request->abstract), ENT_QUOTES);
			$abstractSearch = preg_replace('/\"/', '', $abstractSearch);
			$abstractSearch = preg_replace('/[^\p{L}\p{N}\s]/u', '', $abstractSearch);
			$abstractSearch = trim(preg_replace('/[0-9]+/', '', $abstractSearch));
			$abstractSearch = strtolower($abstractSearch);
			
			//convert string to array
			$abstractArray = explode(' ', $abstractSearch);
			$abstractArray = array_filter($abstractArray);
			
			// Filter out words with less than 5 alphabets
			$filteredWords = array_filter($abstractArray, function ($word) {
				return strlen($word) >= 5;
			});
			
			//remove dictionary words from array
			$filteredAbstractArray = array_diff($filteredWords, $prep_dictionary);
			
			//count how many times word appeared in array
			$abstractCounts = array_count_values($filteredAbstractArray);
			
			//remove words from array which count is less than 1
			$uniqueAbstract = [];
			foreach ($abstractCounts as $word => $count) {
				if ($count >= 2) {
					$uniqueAbstract[] = $word;
					$occurences[$word]= $count;
				}
			}
			
			//convert array into string
			$separatedAbstract = implode(' ', $uniqueAbstract);
			
			$words = preg_split('/[\s,]+/', $separatedAbstract);

			$variations = array_map(function($word) {
				return $word . '*';
			}, $words);
				
			$variations_with_space = array_map(function($word) {
				return $word . ' *';
			}, $words);
				
			$pattern = implode('|', array_merge($variations, $variations_with_space));
			//dd($pattern);

			$request->merge(['abstract' => $pattern]);
		}
		
		if (!empty($request->searchvalue) || !empty($request->abstract)) {
			
			list($results, $pageno, $pagesize, $pagename) = $this->amazon_search_get_journal_webservicedata($request, $journalSearch);
			
			if ($results) {
				$print  = json_decode($results);
				//dd($print); 
				$size   = count($print->hits->hit);
				$found  = $print->hits->found;
				$num_rows = $found;
				$num_pages = ceil($num_rows / $pagesize);
			}
		}

		if($found>0){
			for($i = 0; $i < $size; $i++){
				if (isset($print->hits->hit[$i]->fields->journal_title)) {

					$data_arr[$i]['journal_title'] = $print->hits->hit[$i]->fields->journal_title;
				}else{
					$data_arr[$i]['journal_title'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->issn)) {

					$data_arr[$i]['issn'] = $print->hits->hit[$i]->fields->issn;
				}else{
					$data_arr[$i]['issn'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->journal_cite_score)) {

					$data_arr[$i]['journal_cite_score'] = $print->hits->hit[$i]->fields->journal_cite_score;
				}else{
					$data_arr[$i]['journal_cite_score'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->journal_impact_factor)) {

					$data_arr[$i]['journal_impact_factor'] = $print->hits->hit[$i]->fields->journal_impact_factor;
				}else{
					$data_arr[$i]['journal_impact_factor'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->journal_subject)) {

					$data_arr[$i]['journal_subject'] = $print->hits->hit[$i]->fields->journal_subject;
				}else{
					$data_arr[$i]['journal_subject'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->aims_and_scope)) {

					$data_arr[$i]['aims_and_scope'] = strip_tags(html_entity_decode($print->hits->hit[$i]->fields->aims_and_scope));
				}else{
					$data_arr[$i]['aims_and_scope'] = "";
				}

				if (isset($print->hits->hit[$i]->fields->journal_code)) {

					$data_arr[$i]['journal_code'] = $print->hits->hit[$i]->fields->journal_code;
					$journal_code                 = $print->hits->hit[$i]->fields->journal_code;
				}else{
					$data_arr[$i]['journal_code'] = "";
				}

				$journal_info 		= Journal::GetJournalByCode($journal_code);
				
				$article_list 				= Article::GetLatestArticle($journal_info->journal_id);
				$publication_time 			= Journal::GetAveragePublicationTime($journal_code);
				
				if (isset($publication_time->avg_time_till_acceptance_2023)) {
					$numberOfDays = $publication_time->avg_time_till_acceptance_2023;

					if ($numberOfDays > 0 && $numberOfDays <= 180) {
						$data_arr[$i]['publication_time'] = $numberOfDays . " days";
					} else {
						$data_arr[$i]['publication_time'] = "";
					}
				} else {
					$data_arr[$i]['publication_time'] = "";
				}
				
				if(!empty($article_list)){
				for($j = 0; $j < count($article_list); $j++){
					$data_arr[$i]['article'][$j]['article_id'] = $article_list[$j]->article_id;
					$data_arr[$i]['article'][$j]['title'] = $article_list[$j]->title;
				}
				}else{
					$data_arr[$i]['article'] = "";
				}

				
				$data_arr[$i]['journal_id'] 	= $journal_info->journal_id;
				$data_arr[$i]['journal_status'] = $journal_info->journal_status;

				if (isset($journal_info->jms_jcode)){
					$data_arr[$i]['jms_jcode'] = $journal_info->jms_jcode;
					
					$publication_fees = Journal::GetPublicationFeesbyJMSCode($journal_info->jms_jcode);
					
					if (isset($publication_fees->APC)){
						$apc_charges = $publication_fees->APC;
						$data_arr[$i]['APC_charges'] = "$".$apc_charges;
					}else{
						$data_arr[$i]['APC_charges'] = "";
					}
				}else{
					$data_arr[$i]['jms_jcode'] = "";
				}
				
				if (isset($journal_info->image_file_name)){
					$data_arr[$i]['image_file_name'] = $journal_info->image_file_name;
				}else{
					$data_arr[$i]['image_file_name'] = "";
				}
				
				if (isset($print->hits->hit[$i]->fields->_score)) {
					$data_arr[$i]['score'] = $print->hits->hit[$i]->fields->_score;
				}else{
					$data_arr[$i]['score'] = "";
				}
				
				$jms_code_list[] = $journal_info->jms_jcode;
			}
			$formatted_jms_codes = implode(', ', array_map(function ($item) {
				return "'$item'";
			}, $jms_code_list));
			$jms_code_list = trim($formatted_jms_codes, "'");

			if (!empty($jms_code_list)) {
				$journal_average_decision_list = Journal::GetJournalAverageFirstDecision($jms_code_list);
				$journal_acceptance_rates_list = Journal::GetJournalAcceptanceRate($jms_code_list);
			}
		}
		
		$post_vars    = $_POST;
		

		if ($request->citescoreMinval == "" && $request->citescoreMaxVal == "" && $request->impactFactMinval == "" && $request->impactFactMaxVal == "") {

			return view('journal_search', with([
				'journalSearch' 					=> $journalSearch,
				'found' 							=> $found,
				'size' 								=> $size,
				'print' 							=> $print,
				'pagesize'							=> $pagesize,
				'pageno' 							=> $pageno,
				'pagename' 							=> $pagename,
				'num_rows' 							=> $num_rows,
				'num_pages' 						=> $num_pages,
				'post_vars' 						=> $post_vars,
				'data_arr' 							=> $data_arr,
				'searchOption' 						=> $searchOption,
				'occurences' 						=> $occurences,
				'journal_list' 						=> $journal_list,
				'journal_average_decision_list' 	=> $journal_average_decision_list,
				'journal_acceptance_rates_list' 	=> $journal_acceptance_rates_list
			]));
		} else {
			$data = '';
			foreach ($data_arr as $journal_details) {
				$data .= '<div class="card card-body shadow mb-3">';

				if ($journal_details['journal_status'] == 1) {

					$data .= '<div class="row justify-content-between align-items-center mb-3">
							<div class="col-md-6">
								<a href="https://www.eurekaselect.com/journal/' . $journal_details['journal_id'] . '" class="journalNameBtn" target="_blank">' . $journal_details['journal_title'] . '</a>
							</div>
							<div class="col-md-6 text-right">
                                <span style="background-color:orange;" class="float-left rounded p-1"><b>Search Score :' . $journal_details['score'] . '</b></span>';

					$data .= '<a href="https://bentham.manuscriptpoint.com/journals/' . $journal_details['jms_jcode'] . '?utm_source=eurekaselect&utm_medium=website&utm_campaign=journalfinder&utm_term=unpaid&utm_content=link" class="submit-paper-btn btn btn-sm btn-primary bg-siteblue" target="_blank">Submit paper <i class="fa-solid fa-chevron-right"></i></a>';

					$data .= '<a href="https://www.eurekaselect.com/journal/' . $journal_details['journal_id'] . '" class="submit-paper-btn btn btn-sm btn-primary bg-siteblue" target="_blank">Submit paper <i class="fa-solid fa-chevron-right"></i></a>';

					$data .= '</div></div>
									<p style="font-size: 20px; font-weight:500;" class="mb-2">ISSN: ' . $journal_details['issn'] . '</p>
								<div class="row">
									<div class="col-2">
										<img src="https://www.eurekaselect.com/images/bentham/' . $journal_details['image_file_name'] . '" alt="journal" class="img-fluid">
									</div>
									<div class="col-10">
										<div class="row mb-4">
											<div class="border-right-not-last col">
												<p class="mb-1 j-info-title">CiteScore</p>
												<h5 class="mb-0">' . $journal_details['journal_cite_score'] . '</h5>
											</div>
											<div class="border-right-not-last col">
												<p class="mb-1 j-info-title">Impact Factor</p>
												<h5 class="mb-0">' . $journal_details['journal_impact_factor'] . '</h5>
											</div>
											<div class="border-right-not-last col">
												<p class="mb-1 j-info-title">Acceptance rate</p>';
											if (!empty($journal_acceptance_rates_list)) {
												foreach ($journal_acceptance_rates_list as $journal_acceptance_rate) {
													if ($journal_details['jms_jcode'] == $journal_acceptance_rate->journal_code) {
														$data .= '<h5 class="mb-0">' . ceil($journal_acceptance_rate->acceptance_rate) . "%" . '</h5>';
													}
												}
											}
									$data .= '</div>
											<div class="border-right-not-last col">
												<p class="mb-1 j-info-title">Average time to 1st decision</p>';
												if (!empty($journal_average_decision_list)) {
													foreach ($journal_average_decision_list as $average_decision) {
														if ($journal_details['jms_jcode'] == $average_decision->journal_code) {
												$data .= '<h5 class="mb-0">' . ceil($average_decision->avg_time) . " days" . '</h5>';
											}
										}
									}
									$data .= '</div>
											<div class="border-right-not-last col">
												<p class="mb-1 j-info-title">Time to publication</p>
												<h5 class="mb-0">' . $journal_details['publication_time'] . '</h5>
											</div>
										</div>
										<div class="row d-block">';
					if (!empty($journal_details['APC_charges'])) {
						$data .= '<div class="col-12 mb-2">
												<h4 class="mb-0 border-bottom pb-2">Publishing options for this journal</h4>
											</div>
											<div class="col-12 col-md-6 mb-2 mb-md-0 float-left">
												<p class="mb-0 bg-primary text-white py-1 px-2 d-inline-block mb-2 font-14">Open Access</p>
													<h4>' . $journal_details['APC_charges'] . '</h4>
													<p class="text-small">Article Publishing Charge (APC), excluding taxes</p>
											</div>';
					}
					$data .= '<div class="accordion col-12 col-md-6 mb-2 mb-md-0 float-right pt-4" id="accordionExample">
												<div class="d-flex justify-content-end align-items-end h-100">
													<button class="btn btn-outline-dark btn-sm" type="button" data-toggle="collapse" data-target="#jfsjid' . $journal_details['journal_id'] . '" aria-expanded="true" aria-controls="jfsjid' . $journal_details['journal_id'] . '">
														More Details...
													</button>
												</div>
											</div>
										</div>
									</div>
									<div id="jfsjid' . $journal_details['journal_id'] . '" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
										<div class="card-body">
											<div class="row mb-3">
												<div class="col-2 fw-bold fs-18">Subject area</div>
												<div class="col-10">
													' . $journal_details['journal_subject'] . '
												</div>
											</div>
											<div class="row mb-3">
												<div class="col-2 fw-bold fs-18">
													Recent articles
												</div>
												<div class="col-10">
													<div class="row">';
					foreach ($journal_details['article'] as $article_lists) {
						$data .=	'<div class="col-12 col-md-4">
																<a href="https://www.eurekaselect.com/article/' . $article_lists['article_id'] . '" class="text-siteblue" target="_blank">' . $article_lists['title'] . '</a>
															</div>';
					}
					$data .= '</div>
												</div>
											</div>
											<div class="row mb-3">
												<div class="col-2 fw-bold fs-18">Journal scope</div>
												<div class="col-10">
													<p>' . $journal_details['aims_and_scope'] . '</p>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>';
				}
			}
			return $data;
		}
	}

	public function amazon_search_get_journal_webservicedata($request, $journalSearchvalue)
	{
		$journalSearch = "";
		$genre 		   = "";
		$minvalue 	   = "";
		$maxvalue 	   = "";

		$pagesize = isset($request->pagesize) ? $request->pagesize : 10;
		$pageno   = isset($request->pageno) ? $request->pageno : 1;

		if ($pageno == 1) {
			$start_from = $pageno - 1;
		} else {

			$start_from = ($pageno - 1) * $pagesize;
		}

		$fq 	  = "&fq=";
		$priority = "'keyword^1','journal_code^2'";
		$option   = "&q.options={fields:[" . urlencode($priority) . "]}";
		$sorting  = "&sort=_score+desc";
		$score	  = "&return=genre,journal_code,journal_title,journal_type,issn,eissn,doi,keyword,aims_and_scope,journal_indexed_in,journal_subject,_score,journal_cite_score,journal_impact_factor";
		$removeJournal = "(not%20issn:%272666-3384%27)(not%20issn:%272666-2140%27)(not%20issn:%272665-9808%27)(not%20issn:%272542-5919%27)(not%20issn:%272542-5846%27)(not%20issn:%272468-4244%27)(not%20issn:%272468-4228%27)(not%20issn:%272452-2732%27)(not%20issn:%272451-8271%27)(not%20issn:%272405-4658%27)(not%20issn:%272352-393X%27)(not%20issn:%272352-0949%27)(not%20issn:%272352-0922%27)(not%20issn:%272215-0811%27)(not%20issn:%272214-0832%27)(not%20issn:%272213-8099%27)(not%20issn:%272213-5294%27)(not%20issn:%272213-476X%27)(not%20issn:%272213-3852%27)(not%20issn:%272213-2759%27)(not%20issn:%272213-235X%27)(not%20issn:%272213-1116%27)(not%20issn:%272212-7984%27)(not%20issn:%272212-7178%27)(not%20issn:%272212-7119%27)(not%20issn:%272212-7070%27)(not%20issn:%272212-7038%27)(not%20issn:%272212-3962%27)(not%20issn:%272211-7407%27)(not%20issn:%272211-5552%27)(not%20issn:%272211-5528%27)(not%20issn:%272211-548X%27)(not%20issn:%272211-5420%27)(not%20issn:%272211-3347%27)(not%20issn:%272211-3320%27)(not%20issn:%272210-68711%27)(not%20issn:%272210-6863%27)(not%20issn:%272210-6847%27)(not%20issn:%272210-6839%27)(not%20issn:%272210-3090%27)(not%20issn:%272210-2965%27)(not%20issn:%271877-9441%27)(not%20issn:%271877-9123%27)(not%20issn:%271877-6116%27)(not%20issn:%271874-4761%27)(not%20issn:%271874-4737%27)(not%20issn:%271874-4648%27)(not%20issn:%271872-3128%27)(not%20issn:%271872-2156%27)(not%20issn:%271872-2148%27)(not%20issn:%271872-213X%27)(not%20issn:%271872-2113%27)(not%20issn:%271871-5281%27)(not%20issn:%271871-5222%27)(not%20issn:%271871-5214%27)(not%20issn:%271574-891X%27)(not%20issn:%271574-8901%27)(not%20issn:%271574-8898%27)(not%20issn:%271574-8847%27)(not%20issn:%271573-4005%27)(not%20issn:%271573-3955%27)(not%20issn:%271570-1603%27)(not%20issn:%271568-0169%27)(not%20issn:%271568-0150%27)(not%20issn:%271568-0142%27)(not%20issn:%271568-0134%27)(not%20issn:%271568-0126%27)(not%20issn:%271568-0118%27)(not%20issn:%271568-010X%27)(not%20issn:%271568-0088%27)(not%20issn:%271568-007X%27)(not%20issn:%271568-0061%27)(not%20issn:%271568-0053%27)(not%20issn:%271567-2700%27)(not%20issn:%271567-2697%27)(not%20issn:%271567-2034%27)";
		
		if ($request->searchOption == "keywords"){
			$journalSearch = $request->searchvalue;
		}
		if ($request->searchOption == "abstract"){
			$journalSearch = $request->abstract;
		}

		if ($journalSearch != "" && $request->citescoreMinval != "" && $request->citescoreMaxVal != "" && $request->impactFactMinval != "" && $request->impactFactMaxVal != "") {
			
			if($request->citescoreMinval == 0){
				$citescoreMinval = 1;
			}else{
				$citescoreMinval = $request->citescoreMinval;
			}
			
			if($request->citescoreMaxVal == 10){
				$citescoreMaxVal = 9;
			}else{
				$citescoreMaxVal = $request->citescoreMaxVal;
			}
			
			if($request->impactFactMinval == 0){
				$impactFactMinval = 1;
			}else{
				$impactFactMinval = $request->impactFactMinval;
			}
			
			if($request->impactFactMaxVal == 10){
				$impactFactMaxVal = 9;
			}else{
				$impactFactMaxVal = $request->impactFactMaxVal;
			}
			
			$url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($journalSearch));
			
			$gener = "(%20and%20genre:%27journal%27". $removeJournal ."(%20and%20journal_cite_score:[%27". urlencode($citescoreMinval) ."%27,%27". urlencode($citescoreMaxVal) ."%27])(%20and%20journal_impact_factor:[%27". urlencode($impactFactMinval) ."%27,%27". urlencode($impactFactMaxVal) ."%27]))";
			
			$url = $url . $fq . $gener . $option . $sorting . $score;

			//return $url;
		}
		
		elseif ($journalSearch != "" && $request->citescoreMinval != "" && $request->citescoreMaxVal != "") {
			
			if($request->citescoreMinval == 0){
				$citescoreMinval = 1;
			}else{
				$citescoreMinval = $request->citescoreMinval;
			}
			
			if($request->citescoreMaxVal == 10){
				$citescoreMaxVal = 9;
			}else{
				$citescoreMaxVal = $request->citescoreMaxVal;
			}
			
			
			$url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($journalSearch));
			
			$gener = "(%20and%20genre:%27journal%27". $removeJournal ."(%20and%20journal_cite_score:[%27". urlencode($citescoreMinval) ."%27,%27". urlencode($citescoreMaxVal) ."%27]))";
			
			$url = $url . $fq . $gener . $option . $sorting . $score;	
			//return $url;
		}
		
		elseif ($journalSearch != "" && $request->impactFactMinval != "" && $request->impactFactMaxVal != "") {
			
			$impactFactMinval = $request->impactFactMinval;
			
			if($request->impactFactMaxVal == 10){
				$impactFactMaxVal = 9;
			}else{
				$impactFactMaxVal = $request->impactFactMaxVal;
			}
			
			$url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($journalSearch));
			
			$gener = "(%20and%20genre:%27journal%27". $removeJournal ."(%20and%20journal_impact_factor:[%27". urlencode($impactFactMinval) ."%27,%27". urlencode($impactFactMaxVal) ."%27]))";
			
			$url = $url . $fq . $gener . $option . $sorting . $score;	
			//return $url;
		}
		
		else {
			
			$paging   = "&size=" . $pagesize . "&start=" . $start_from;
			
			$gener = "(%20and%20genre:%27journal%27". $removeJournal .")";
				
			$url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($journalSearch));
			
			$url = $url . $fq . $gener . $option . $paging . $sorting . $score;
			//dd($url);
		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		//return the transfer as a string
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// $output contains the output string
		$output = curl_exec($ch);
		// close curl resource to free up system resources
		curl_close($ch);
		$pagename = "/journalfinder?xe=1";

		if ($request->searchOption == "keywords"){
			$pagename .= "&searchOption=" . urlencode(trim($request->searchOption)) . "&searchvalue=" . urlencode($journalSearchvalue);
		}elseif($request->searchOption == "abstract") {
			$pagename .= "&searchOption=" . urlencode(trim($request->searchOption)) . "&abstract=" . urlencode($journalSearchvalue);
		}

		return array($output, $pageno, $pagesize, $pagename);
	}

	/*
		Author: Zubair Ashraf
		Date:  01 Feb,2024
		Description: 
	*/

	public function getReviewerSearch(Request $request, $parameter = "")
	{
		if ($parameter !== 'afc43a1-dd72a4515') {
			return redirect('/');
		}

		$results 			 = '';
		$print 				 = '';
		$size 	 			 = '';
		$found 				 = 0;
		$reviewerSearchValue = '';
		$reviewerSearch 	 = '';
		$data_arr 			 = array();
		$prep_dictionary = ["is", "am", "are", "was", "were", "will", "would", "shall", "should", "can", "colud", "may", "might", "must", "ought", "i", "we", "me", "he", "she", "they", "there", "their", "us", "myself", "herself", "themself", "you", "themseleve", "it", "then", "a", "of", "from", "form", "the", "with", "also", "his", "him", "her", "on", "taking", "first", "take", "took", "has", "have", "which", "that", "per", "to", "be", "in", "like", "and", "an", "by", "or", "not", "does", "at", "for", "these", "when", "because", "between", "thus", "many", "years", "as", "ourself", "ourselves", "those", "found"];

		$country_list = DB::table('country')->where('iso','!=','')->get();

		$param['country_name'] 	= $request->country_name;
		$param['reviewer_data'] = $request->reviewer_data;
		$param['h_index']		= $request->h_index;
		$reviewer_id_list 		= [];

		if ($request->exportButton == "exportButton") {
			$reviewer_id_list = $request->export_reviewer_list;
			$reviewer_id_array = explode(',', $reviewer_id_list);
			$data_arr = Journal::GetAmazonReviewerData($reviewer_id_array);
			// dd($data_arr);
			$this->export_amazon_search_reviewer($data_arr);
		}

		if ($request->searchOption == "") {
			$searchOption = 'keywords';
		} else {
			$searchOption = $request->searchOption;
		}
		// dd($request);
		if ($request->searchOption == "keywords") {
			$searchvalue = $reviewerSearch = trim($request->keywords);
			// dd($reviewerSearch);

			if (strpos($searchvalue, '"') !== false) {

				$reviewerSearchValue =  $searchvalue;
			} elseif(strpos($searchvalue, '|') !== false){
				$words = preg_split('/[\s|]+/', $searchvalue);

				$variations = array_map(function ($word) {
					return $word . '*';
				}, $words);

				$variations_with_space = array_map(function ($word) {
					return $word . ' *';
				}, $words);

				$pattern = implode('|', array_merge($variations, $variations_with_space));

				$reviewerSearchValue =  $pattern;

			}else {
				$words = preg_split('/[\s,]+/', $searchvalue);

				$variations = array_map(function ($word) {
					return $word . '*';
				}, $words);

				$variations_with_space = array_map(function ($word) {
					return $word . ' *';
				}, $words);

				$pattern = implode('', array_merge($variations, $variations_with_space));
				// dd($pattern);

				$reviewerSearchValue =  $pattern;
			}
		} elseif ($request->searchOption == "abstract") {
			$abstractSearch = $reviewerSearch = htmlentities(trim($request->abstract), ENT_QUOTES);
			$abstractSearch = preg_replace('/\"/', '', $abstractSearch);
			$abstractSearch = preg_replace('/[^\p{L}\p{N}\s]/u', '', $abstractSearch);
			$abstractSearch = trim(preg_replace('/[0-9]+/', '', $abstractSearch));
			$abstractSearch = strtolower($abstractSearch);

			//convert string to array
			$abstractArray = explode(' ', $abstractSearch);
			$abstractArray = array_filter($abstractArray);

			// Filter out words with less than 5 alphabets
			$filteredWords = array_filter($abstractArray, function ($word) {
				return strlen($word) >= 5;
			});

			//remove dictionary words from array
			$filteredAbstractArray = array_diff($filteredWords, $prep_dictionary);

			//count how many times word appeared in array
			$abstractCounts = array_count_values($filteredAbstractArray);

			//remove words from array which count is less than 1
			$uniqueAbstract = [];
			foreach ($abstractCounts as $word => $count) {
				if ($count >= 2) {
					$uniqueAbstract[] = $word;
					$occurences[$word] = $count;
				}
			}

			//convert array into string
			$separatedAbstract = implode(' ', $uniqueAbstract);

			$words = preg_split('/[\s,]+/', $separatedAbstract);

			$variations = array_map(function ($word) {
				return $word . '*';
			}, $words);

			$variations_with_space = array_map(function ($word) {
				return $word . ' *';
			}, $words);

			$pattern = implode('|', array_merge($variations, $variations_with_space));
			//dd($pattern);

			$reviewerSearchValue =  $pattern;
		}

		if (!empty($request->keywords) || !empty($request->abstract)) {

			list($results) = $this->amazon_search_get_reviewer_webservicedata($reviewerSearchValue);

			if ($results) {
				$print  = json_decode($results);
				$size   = count($print->hits->hit);
				$found  = $print->hits->found;

				if ($found > 0) {

					// Get Reviewer ID's from search data using for loop
					for ($i = 0; $i < $size; $i++) {
						if (isset($print->hits->hit[$i]->id)) {
							$reviewer_id_list[] = str_replace('r', '', $print->hits->hit[$i]->id);
						}
					}

					$param['page_size']	= 20;
					// Search this reviewer ID's in tbl_amazon_reviewer_data or applying filter
					$data_arr = Journal::GetAmazonReviewerData($reviewer_id_list, $param);
				}
			}
		}

		if ($request->reviewer_export == 'reviewer_export') {
			$this->export_amazon_search_reviewer($data_arr);
		} else {
			return view('reviewer_search', with([
				'reviewerSearch' 	=> $reviewerSearch,
				'searchOption' 		=> $searchOption,
				'data_arr' 			=> $data_arr,
				'country_list' 		=> $country_list,
				'param' 			=> $param,
			]));
		}
	}

	public function amazon_search_get_reviewer_webservicedata($reviewerSearchValue)
	{
		$fq 	  = "&fq=";
		$priority = "'reviewer_keywords^3','field_of_expertise^3'";
		$option   = "&q.options={fields:[" . urlencode($priority) . "]}";
		$sorting  = "&sort=_score+desc";
		$fields	  = "&return=id";
		$paging   = "&size=" . 10000;


		$gener = "(%20and%20genre:%27reviewer%27)";

		$url = 'http://search-eurekaselect-search-4rhehd3t2qbs27zi5yp56dv3oy.eu-west-1.cloudsearch.amazonaws.com/2013-01-01/search?q=' . urlencode(trim($reviewerSearchValue));

		$url = $url . $fq . $gener . $option . $paging . $sorting . $fields;
		// dd($url);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		//return the transfer as a string
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// $output contains the output string
		$output = curl_exec($ch);
		// close curl resource to free up system resources
		curl_close($ch);

		return array($output);
	}

	function export_amazon_search_reviewer($data_arr)
	{
		// dd($data_arr);
		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename=reviewer.csv");

		$r = 'Name, Email, Country, City, Institution,	H-Index, Field of expertise, Keywords, Orcid, Scopus ID, Journal, Manuscript Reviewed';
		$r .= "\n";

		foreach ($data_arr as $vals) {

			$name = '"' . $vals->first_name . ' ' . $vals->last_name . '"';
			$name = str_replace(',', '', $name);
			$r .= $name . ',';

			$r .= $vals->email . ',';

			$reviewer_country = '"' . $vals->country . '"';
			$r .= $reviewer_country . ',';

			$r .= $vals->city . ',';

			$institution = str_replace(',', '', $vals->institution);
			$institution = '"' . $institution . '"';
			$r .= $institution . ',';

			$r .= $vals->h_index . ',';

			$field_of_expertise = str_replace(',', '', $vals->field_of_expertise);
			$field_of_expertise = '"' . $field_of_expertise . '"';
			$r .= $field_of_expertise . ',';

			$keywords = str_replace(',', '', $vals->keywords);
			$reviewer_keywords = '"' . $keywords . '"';
			$r .= $reviewer_keywords . ',';

			$r .= $vals->orcid . ',';
			$r .= $vals->scopus_id . ',';

			$reviewer_journal = '"' . $vals->reviewer_journal . '"';
			$r .= $reviewer_journal . ',';

			if (empty($vals->total_reviewed)) {
				$r .= 0 . ',';
			} else {
				$r .= $vals->total_reviewed . ',';
			}
			$r .= "\n";
		}
		echo $r;
		die;
	}
} //class