<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Author;
use App\Models\BookAccess;
use App\Models\Chapter;
use App\Models\ContentAccess;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Indexing;
use App\Models\Issue;
use App\Models\Journal;
use App\Models\Keywords;
use App\Models\Volume;
use App\Models\Subject;
use App\Models\JMSContent;
use Auth;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class WebServicesController extends BenthamController
{
    /*
     * Date: 15-11-2018
     * Author: Muhammad Arshad
     * Parameter: None
     * Description:  this function will return the journal List in json format
     */

    public function services_journals(Request $request)
    {

        if (isset($request->pagesize)) {
            $pagesize = $request->pagesize;
        } else {
            $pagesize = 10;
        }
        //return response()->json(array('journal_list' => $request->searchText), 200);

        $journal_list = Journal::where('journal_status', '=', 1);

        if (isset($request->searchText)) {
            $journal_list = $journal_list->where('title', 'like', '%' . $request->searchText . '%');
        }

        $journal_list = $journal_list->select('journal_id', 'nid as journal_nid', 'image_file_name', 'title as journal_title', 'issn', 'eissn')->orderBy('journal_title')->paginate($pagesize);

        if ($request->format == 'xml') {
            foreach ($journal_list as $key => $val) {
                $val->journal_title   = "<![CDATA[ " . $val->journal_title . " ]]>";
                $val->image_file_name = 'https://' . $_SERVER['HTTP_HOST'] . '/images/bentham/' . $val->image_file_name;
            }

            $xml = json2xml(json_encode($journal_list));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');
            //return Response::make(json2xml(json_encode($journal_list)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json(array('journal_list' => $journal_list), 200);
        }

    }

    /*
     * Date: 15-11-2018
     * Author: Muhammad Arshad
     * Parameter: None
     * Description:  this function will return the ebook List in json format
     */

    public function services_ebooks(Request $request)
    {

        if (isset($request->pagesize)) {
            $pagesize = $request->pagesize;
        } else {
            $pagesize = 10;
        }

        $ebook_list = EbookVolume::GetAllEbookVolumeList($pagesize);

        $cnt = 0;
        foreach ($ebook_list as $volume) {

            $ebooks['data'][$cnt]['ebook_id']        = $volume->ebook_id;
            $ebooks['data'][$cnt]['ebook_nid']       = $volume->vnid;
            $ebooks['data'][$cnt]['volume_id']       = $volume->ebook_volume_id;
            $ebooks['data'][$cnt]['volume']          = $volume->volume_name;
            $ebooks['data'][$cnt]['image_file_name'] = 'https://' . $_SERVER['HTTP_HOST'] . '/images/bentham/' . $volume->ebk_image_file_name;
            $ebooks['data'][$cnt]['ebook_title']     = $volume->title;
            $ebooks['data'][$cnt]['isbn']            = $volume->isbn;
            $ebooks['data'][$cnt]['eisbn']           = $volume->eisbn;
            $ebooks['data'][$cnt]['doi']             = $volume->doi;
            $ebooks['data'][$cnt]['price']           = $volume->ebook_price;
            $ebooks['data'][$cnt]['print_price']     = $volume->ebook_price_pod;
            $ebooks['data'][$cnt]['print_pod_price'] = $volume->ebook_price_podandpdf;

            $volume_authors = Author::GetAuthorsByContentId($volume->ebook_volume_id, 'ebook_volume_id');

            if ($volume_authors) {
                $AuthorNames = '';
                foreach ($volume_authors as $author) {
                    if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                }

                $AuthorNames = rtrim($AuthorNames, ', ');

                $pos = strrpos($AuthorNames, ",");
                if ($pos) {
                    $str         = substr($AuthorNames, 0, $pos);
                    $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                    $AuthorNames = $str . " and " . $str2;
                }

                $ebooks['data'][$cnt]['author'] = $AuthorNames;
            } else {
                $ebooks['data'][$cnt]['author'] = "";
            }
            $cnt++;
        }

        $ebooks['current_page']   = $ebook_list->toArray()['current_page'];
        $ebooks['first_page_url'] = $ebook_list->toArray()['first_page_url'];
        $ebooks['from']           = $ebook_list->toArray()['from'];
        $ebooks['last_page']      = $ebook_list->toArray()['last_page'];
        $ebooks['last_page_url']  = $ebook_list->toArray()['last_page_url'];
        $ebooks['next_page_url']  = $ebook_list->toArray()['next_page_url'];
        $ebooks['path']           = $ebook_list->toArray()['path'];
        $ebooks['per_page']       = $ebook_list->toArray()['per_page'];
        $ebooks['prev_page_url']  = $ebook_list->toArray()['prev_page_url'];
        $ebooks['to']             = $ebook_list->toArray()['to'];
        $ebooks['total']          = $ebook_list->toArray()['total'];

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($ebooks));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');
            //return Response::make(json2xml(json_encode($ebooks)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json(array('ebooks' => $ebooks), 200);
        }

    }

    /*
     * Date: 15-11-2018
     * Author: Muhammad Arshad
     * Parameter: None
     * Description:  this function will return the ebook List in json format
     */

    public function services_volumes(Request $request)
    {

        if (isset($request->pagesize)) {
            $pagesize = $request->pagesize;
        } else {
            $pagesize = 10;
        }

        //$volume          = Volume::where('volume_id', $request->volume_id)->first();
        $journal_id      = $request->journal_id;
        $journal_details = Journal::where('journal_id', $journal_id)->first();

        //Free or Open access volume level
        $param['journal_id']  = $journal_id;
        $param['access_type'] = 1; //free volume list
        $FreeVolumeList       = ContentAccess::GetContentAccessVolumeList($param);
        if ($FreeVolumeList) {
            foreach ($FreeVolumeList as $fvl) {
                $fvl_array[] = $fvl->content_type_id;
            }
            $FreeVolumeList = $fvl_array;
        }

        $param['access_type'] = 2; //openaccess volume list
        $OpenAccessVolumeList = ContentAccess::GetContentAccessVolumeList($param);
        if ($OpenAccessVolumeList) {
            foreach ($OpenAccessVolumeList as $ovl) {
                $ovl_array[] = $ovl->content_type_id;
            }
            $OpenAccessVolumeList = $ovl_array;
        }
        //Free or Open access issue level
        $param['access_type'] = 1; //free issue list
        $FreeIssueList        = ContentAccess::GetContentAccessIssueList($param);
        if ($FreeIssueList) {
            foreach ($FreeIssueList as $fil) {
                $fil_array[] = $fil->content_type_id;
            }
            $FreeIssueList = $fil_array;
        }
        $param['access_type'] = 2; //openaccess volume list
        $OpenAccesIssueList   = ContentAccess::GetContentAccessIssueList($param);
        if ($OpenAccesIssueList) {
            foreach ($OpenAccesIssueList as $oil) {
                $oil_array[] = $oil->content_type_id;
            }
            $OpenAccesIssueList = $oil_array;
        }

        $IsuesUnderVolArrray = Issue::GetAllIssueByJournalID($journal_id);
        $IssueCount          = count($IsuesUnderVolArrray);
        $articleSection      = Article::getArticleSectionBySequenceOrder();

        $image_file_name = $journal_details->image_file_name;
        if ($image_file_name == "") {
            $image_file_name = 'no_image.jpg';
        }
        $json_output['journal_details'] = array(
            'journal_id'       => $journal_details->journal_id,
            'journal_title'    => $journal_details->title,
            'journal_subtitle' => $journal_details->subtitle,
            'issn'             => $journal_details->issn,
            'eissn'            => $journal_details->eissn,
            'price'            => $journal_details->price,
            'image_file_name'  => $image_file_name,
        );
        $epubArticlesCount = 0;
        $epub_articles = array();
        foreach ($articleSection as $section) {
            $epubArticles = Article::GetTrackList($journal_id, $section->art_sec_id, 0);

            $epubArticlesCount = count($epubArticles) + $epubArticlesCount;

            if ($epubArticlesCount > 0) {

                foreach ($epubArticles as $index => $row) {
                    $epub_articles[] = array(
                        'epub_article_nid'   => $row->nid,
                        'pubmed_id'          => $row->pmid,
                        'epub_article_title' => '<![CDATA[' . $this->RemoveIllegalCharacters($row->title) . ']]>',
                    );
                }

            }
        }
        $json_output['total_epub_articles'] = $epubArticlesCount;
        $json_output['epub_articles']       = $epub_articles;

        if ($IssueCount > 0) {
            $json_output['issue_count'] = $IssueCount;
            $volume                     = '';
            $Volume_Open_Free           = 0;
            $Issue_Open_Free            = 0;
            $vcnt                       = 0;
            $icnt                       = 0;
            $flag                       = 0;
            foreach ($IsuesUnderVolArrray as $row) {
                $Volume_Open_Free = 0;
                $Issue_Open_Free  = 0;

                if ($volume != $row->volume_name) {

                    if ($vcnt == 0 && $flag == 0) {} else {
                        $vcnt++;
                    }
                    $flag = 1;

                    $json_output['volumes'][$vcnt]['volume'] = array('volno' => $row->volume_name,
                        'vol_year'                                               => $row->year,
                    );

                    $icnt = 0;
                    //$json_output['volumes']['volume'][$vcnt]['issues'] = array();

                    $Volume_Open_Free = 0;
                    if ($FreeVolumeList) {

                        if (in_array($row->volume_id, $FreeVolumeList)) {
                            $Volume_Open_Free = 1;
                        }
                    }
                    if (!empty($OpenAccessVolumeList) && ($Volume_Open_Free == 0)) {
                        if (in_array($row->volume_id, $OpenAccessVolumeList)) {
                            $Volume_Open_Free = 2;
                        }
                    }

                    //$xml_output .= "<volume>".$row['volume'];

                    if ($Volume_Open_Free == 1) {
                        $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['volume_content_access'] = 'free';
                    } else if ($Volume_Open_Free == 2) {
                        $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['volume_content_access'] = 'open access';
                    }
                }

                if (($FreeIssueList) && ($Volume_Open_Free == 0)) {
                    if (in_array($row->issue_id, $FreeIssueList)) {
                        $Issue_Open_Free = 1;
                    }
                }
                if (($OpenAccesIssueList) && ($Volume_Open_Free == 0) && ($Issue_Open_Free == 0)) {
                    if (in_array($row->issue_id, $OpenAccesIssueList)) {
                        $Issue_Open_Free = 2;
                    }
                }

                // listing all issues under thier volumes
                $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue'] = array(
                    'issue_no'    => $row->issue_title,
                    'issue_id'    => $row->issue_id,
                    'issue_nid'   => $row->nid,
                    'issue_month' => $row->month,

                );

                if ($row->issue_type == 1) {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_thematic'] = array(
                        'is_thematic'    => 'Yes',
                        'about_thematic' => $this->RemoveIllegalCharacters($row->about_issue),
                        'title_thematic' => $row->issue_title,
                    );

                } else {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_thematic']['is_thematic'] = 'No';

                }

                if ($row->issue_type == 2) {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_inprocess']['is_inprocess'] = 'Yes';
                } else {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_inprocess']['is_inprocess'] = 'No';
                }

                if ($Issue_Open_Free == 1) {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_content_access'] = 'free';
                } else if ($Issue_Open_Free == 2) {
                    $json_output['volumes'][$vcnt]['volume']['issues'][$icnt]['issue']['issue_content_access'] = 'open access';
                }
                $volume = $row->volume_name;

                $icnt++;

            }

        }

        if ($request->format == 'xml') {
            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');
            //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json($json_output, 200);
        }

    }

    /*
     * Date: 03-12-2018
     * Author: Muhammad Arshad
     * Parameter: None
     * Description:  this function will return the ebook chapter detail
     */
    public function services_chapter(Request $request)
    {

        $volume_obj = EbookVolume::where('ebook_volume_id', $request->volume_id)->first();
        if (!empty($volume_obj)) {
            $obj = Ebook::where('ebook_id', $volume_obj->ebook_id)->first();

            if ($request->cid == "") {
                $cid = "0";
            }

            $volume_id     = $volume_obj->ebook_volume_id;
			$volume_nid     = $volume_obj->nid;
            $ebook_id      = $volume_obj->ebook_id;
            $chapter_price = $volume_obj->chapter_price;

            $ChaptersUnderVolArrray = Chapter::getAllChaptersUnderVolumes($volume_id, $request->cid);

            $totalChapters = count($ChaptersUnderVolArrray);

            $volume              = '';
            $volumeLabel         = '';
            $index               = 0;
            $Chapter_Open_Free   = 0;
            $Volume_Open_Free    = 0;
            $eBookDownloadAccess = false;
            $Access              = "NO";

            $volume_authors = Author::GetAuthorsByContentId($volume_id, 'ebook_volume_id');
            if ($volume_authors) {
                $AuthorNames = '';
                foreach ($volume_authors as $author) {
                    if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                }

                $AuthorNames = rtrim($AuthorNames, ', ');

                $pos = strrpos($AuthorNames, ",");
                if ($pos) {
                    $str         = substr($AuthorNames, 0, $pos);
                    $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                    $AuthorNames = $str . " and " . $str2;
                }
                $AuthorNames = rtrim($AuthorNames, ',');

                $ebooks['ebook']['author'] = $AuthorNames;
            } else {

            }

            if ($volume_obj->image_file_name != "") {

                $ImageFileName = $volume_obj->image_file_name;

            } else {

                $ImageFileName = 'no_image.thumbnail.jpg';

            }

            $json_output['ebook']['ebook_id']        = $ebook_id;
            $json_output['ebook']['volume_id']       = $volume_id;
			$json_output['ebook']['volume_nid']      = $volume_nid;
            $json_output['ebook']['volume_no']       = $volume_obj->volume_name;
            $json_output['ebook']['image_file_name'] = "<![CDATA[" . $ImageFileName . "]]>";

            $title                                   = str_replace("–", "-", $obj->ebook_title);
            $title                                   = str_replace('“', '"', $title);
            $title                                   = str_replace('”', '"', $title);
            $json_output['ebook']['ebook_title']     = '<![CDATA[ ' . $this->RemoveIllegalCharacters($obj->title) . ' ]]>';
            $json_output['ebook']['isbn']            = $volume_obj->isbn;
            $json_output['ebook']['eisbn']           = $volume_obj->eisbn;
            $json_output['ebook']['doi']             = $volume_obj->doi;
            $json_output['ebook']['price']           = $volume_obj->ebook_price;
            $json_output['ebook']['print_price']     = $volume_obj->ebook_price_podandpdf;
            $json_output['ebook']['print_pod_price'] = $volume_obj->ebook_price_pod;
            $json_output['ebook']['author']          = "<![CDATA[" . $this->RemoveIllegalCharacters($AuthorNames) . "]]>";

            //checking if volume is Open Access
            $Volume_Open_Free = ContentAccess::CheckOpenFreeAcccessWithType('ebook_access', $volume_id, 'v');

            if ($Volume_Open_Free[0]->total_count != '0') {
                $eBookDownloadAccess = true;
                $Access              = "FREE";
            }
            $json_output['ebook']['ebook_sample_file'] = $volume_obj->ebook_sample;
            $json_output['ebook']['ebook_epub_file']   = $volume_obj->ebook_epub;
            $json_output['ebook']['ebook_prc_file']    = $volume_obj->ebook_prc;
            $json_output['ebook']['ebook_access']      = $Access;

            //Free or Open access chapter level
            $param['ebook_volume_id'] = $volume_id;
            $param['access_type']     = 1;
            $FreeChapterList          = BookAccess::GetContentAccessChapterList($param);
            $param['access_type']     = 2;
            $OpenAccesChapterList     = BookAccess::GetContentAccessChapterList($param);
            $cnt                      = 0;
			
            foreach ($ChaptersUnderVolArrray as $row) {

                $subscribed = false;

                $Chapter_Open_Free    = 0;
                $chapter_level_access = false;

                if ($Volume_Open_Free[0]->total_count == 0) {
                    $Access = "NO";
                }

                if (($FreeChapterList) && ($Volume_Open_Free[0]->total_count == 0)) {

                    foreach($FreeChapterList as $ff){
						if ($row->chapter_id== $ff->chapter_id ) {
							$Access = "FREE";
						}
					}

                }

                if (($OpenAccesChapterList) && ($Volume_Open_Free[0]->total_count == 0) && ($Chapter_Open_Free == 0)) {
					
					foreach($OpenAccesChapterList as $oa){
						if ($row->chapter_id== $oa->chapter_id ) {
							$Access = "FREE";
						}
					}
                    

                }

                if ($subscribed == true) {
                    $Access = "subscribed";
                }

                //echo $volumeLabel;
                $json_output['chapter'][$cnt]['chapter_id']  = $row->chapter_id;
                $json_output['chapter'][$cnt]['chapter_nid'] = $row->nid;
                $json_output['chapter'][$cnt]['title']       = $row->title;
                if ($row->first_page == $row->last_page) {
                    $_pageno = $row->first_page;
                } else {
                    $_pageno = $row->first_page . '-' . $row->last_page . ' (' . $row->page_count . ')';
                }

                $json_output['chapter'][$cnt]['pageno']    = $_pageno;
                $json_output['chapter'][$cnt]['abstracts'] = "<![CDATA[" . $this->RemoveIllegalCharacters($row->abstract) . "]]>";
                $json_output['chapter'][$cnt]['doi']       = $row->doi;
                $json_output['chapter'][$cnt]['link']      = url('/') . "/node/" . $row->nid;

                $chapter_authors = Author::GetAuthorsByContentId($row->chapter_id, 'chapter_id');
                $cAuthorNames    = '';
                $cAuthorAff      = '';
				if($chapter_authors){
					foreach ($chapter_authors as $cauthor) {
						if ($cauthor->is_principle == 1) {

							$cAuthorNames .= $cauthor->authors . '*' . ',  ';

						} else {

							$cAuthorNames .= $cauthor->authors . ',  ';

						}

						$cAuthorAff .= $cauthor->affiliation . ',  ';

					}
				}
				$cAuthorNames = rtrim($cAuthorNames,', ');
                $cAuthorAff = rtrim($cAuthorAff,', ');
				
                $json_output['chapter'][$cnt]['author']            = $cAuthorNames;
                $json_output['chapter'][$cnt]['affiliation']       = $cAuthorAff;
                $json_output['chapter'][$cnt]['access']            = $Access;
                $json_output['chapter'][$cnt]['chapter_price']     = $chapter_price;
                $json_output['chapter'][$cnt]['chapter_supp_file'] = $row->supplementary_filename;
                $json_output['chapter'][$cnt]['chapter_epub_file'] = $row->epub_filename;
                $json_output['chapter'][$cnt]['chapter_prc_file']  = $row->prc_filename;

                $cnt++;
            } //foreach

            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');
                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'Record Not Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }
    /*
     * Date: 26-12-2018
     * Author: Muhammad Arshad
     * Parameter: Pagesize (optional)
     * Description:  This web service will show All free ebooks.
     */
    public function services_free_ebooks(Request $request)
    {

        $pagesize = $request->pagesize ? $request->pagesize : 10;

        $free_ebooks = EbookVolume::GetFreeEbook($pagesize);

        $cnt = 0;

        foreach ($free_ebooks as $row) {

            if ($row->image_file_name != "") {
                $ImageFileName = $row->image_file_name;
            } else {
                $ImageFileName = 'no_image.thumbnail.jpg';
            }

            $title                                   = str_replace("–", "-", $row->ebook_title);
            $title                                   = str_replace('“', '"', $title);
            $title                                   = str_replace('”', '"', $title);
            $ebooks['data'][$cnt]['ebook_title']     = $title;
            $ebooks['data'][$cnt]['volume_no']       = $row->volume;
            $ebooks['data'][$cnt]['image_file_name'] = $ImageFileName;
            $ebooks['data'][$cnt]['isbn']            = $row->isbn;
            $ebooks['data'][$cnt]['eisbn']           = $row->eisbn;
            $ebooks['data'][$cnt]['author']          = $row->eisbn;

            $volume_authors = Author::GetAuthorsByContentId($row->ebook_volume_id, 'ebook_volume_id');

            if ($volume_authors) {
                $AuthorNames = '';
                foreach ($volume_authors as $author) {
                    if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                }

                $AuthorNames = rtrim($AuthorNames, ', ');

                $pos = strrpos($AuthorNames, ",");
                if ($pos) {
                    $str         = substr($AuthorNames, 0, $pos);
                    $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                    $AuthorNames = $str . " and " . $str2;
                }

                $ebooks['data'][$cnt]['author'] = '<![CDATA[' . $this->RemoveIllegalCharacters($AuthorNames) . ']]>';
            } else {
                $ebooks['data'][$cnt]['author'] = '<![CDATA[]]>';
            }

            $cnt++;

        } //foreach

        $ebooks['current_page']   = $free_ebooks->toArray()['current_page'];
        $ebooks['first_page_url'] = $free_ebooks->toArray()['first_page_url'];
        $ebooks['from']           = $free_ebooks->toArray()['from'];
        $ebooks['last_page']      = $free_ebooks->toArray()['last_page'];
        $ebooks['last_page_url']  = $free_ebooks->toArray()['last_page_url'];
        $ebooks['next_page_url']  = $free_ebooks->toArray()['next_page_url'];
        $ebooks['path']           = $free_ebooks->toArray()['path'];
        $ebooks['per_page']       = $free_ebooks->toArray()['per_page'];
        $ebooks['prev_page_url']  = $free_ebooks->toArray()['prev_page_url'];
        $ebooks['to']             = $free_ebooks->toArray()['to'];
        $ebooks['total']          = $free_ebooks->toArray()['total'];

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($ebooks));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');

            //return Response::make(json2xml(json_encode($ebooks)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json(array('ebooks' => $ebooks), 200);
        }

    }

    public function services_free_chapters(Request $request)
    {

        $type        = $request->type ? $request->type : 1;
        $pagesize    = $request->pagesize ? $request->pagesize : 10;
        $ebook_eisbn = $request->ebook_eisbn ? $request->ebook_eisbn : 0;
        if ($type == "" or $type == "0" or $type > 2) {
            $type = "1";
        }

        $free_chapters = Chapter::GetFreeEbookChapters($type, $ebook_eisbn, $pagesize);

        if (!empty($free_chapters->all())) {

            $flag = "";
            $cnt  = 0;
            foreach ($free_chapters as $row) {
                if ($row->image_file_name != "") {

                    $ImageFileName = $row->image_file_name;

                } else {

                    $ImageFileName = 'no_image.thumbnail.jpg';

                }

                if ($flag != $row->eisbn) {

                    $json_output['ebook']['volume_no']       = $row->volume;
                    $json_output['ebook']['image_file_name'] = $ImageFileName;

                    $title = str_replace("–", "-", $row->ebook_title);
                    $title = str_replace('“', '"', $title);
                    $title = str_replace('”', '"', $title);

                    $json_output['ebook']['ebook_title'] = $title;
                    $json_output['ebook']['isbn']        = $row->isbn;
                    $json_output['ebook']['eisbn']       = $row->eisbn;
                    $json_output['ebook']['ebook_doi']   = $row->ebook_doi;

                    $volume_authors = Author::GetAuthorsByContentId($row->ebook_volume_id, 'ebook_volume_id');

                    if ($volume_authors) {
                        $AuthorNames = '';
                        foreach ($volume_authors as $author) {
                            if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                        }

                        $AuthorNames = rtrim($AuthorNames, ', ');

                        $pos = strrpos($AuthorNames, ",");
                        if ($pos) {
                            $str         = substr($AuthorNames, 0, $pos);
                            $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                            $AuthorNames = $str . " and " . $str2;
                        }

                        $ebooks['ebook'][$cnt]['author'] = $AuthorNames;
                    } else {
                        $ebooks['ebook'][$cnt]['author'] = "";
                    }

                    $ebooks['ebook'][$cnt]['access_on'] = $row->access_on;
                }

                if ($type == "1") {

                    $title = str_replace("–", "-", $row->ebook_title);
                    $title = str_replace('“', '"', $title);
                    $title = str_replace('”', '"', $title);

                    $json_output['ebook']['chapter'][$cnt]['chapter_title'] = $row->title;
                    $json_output['ebook']['chapter'][$cnt]['pageno']        = $row->first_page . '-' . $row->last_page . ' (' . $row->page_count . ')';
                    $abstract                                               = $this->RemoveIllegalCharacters($row->abstract);
                    $json_output['ebook']['chapter'][$cnt]['abstracts']     = $abstract;
                    $json_output['ebook']['chapter'][$cnt]['chapter_doi']   = $row->chapter_doi;
                    $chapter_authors                                        = Author::GetAuthorsByContentId($row->chapter_id, 'chapter_id');
                    $cAuthorNames                                           = '';
                    $cAuthorAff                                             = '';

                    if (!empty($chapter_authors)) {
                        foreach ($chapter_authors as $cauthor) {
                            if ($cauthor->is_principle == 1) {

                                $cAuthorNames = $cauthor->authors . '*' . ',  ';

                            } else {

                                $cAuthorNames = $cauthor->authors . ',  ';

                            }

                            $cAuthorAff = $cauthor->affiliation;

                        }

                        $json_output['ebook']['chapter'][$cnt]['author'] = $cAuthorNames;

                    } else {
                        $json_output['ebook']['chapter'][$cnt]['author'] = '';
                    }

                    $json_output['ebook']['chapter'][$cnt]['link'] = '/chapter/' . $row->chapter_id;

                } //type

                $flag = $row->eisbn;
                $cnt++;
            } //foreach

            
            if ($request->format == 'xml') {
                
                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');
                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
            } elseif ($request->format == 'json') {
                return response()->json($json_output, 200);
            }

        } else {
            $json_output['error'] = 'Record Not Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }

    /*
     * Date: 03-12-2018
     * Author: Muhammad Arshad
     * Parameter: issue id/ nid
     * Description:  this function will return the ebook chapter detail
     */

    public function services_issues(Request $request)
    {

        $issue_id = $request->issue_id;
		

        $journal_details = Issue::GetIssue(array('issue_id' => $issue_id));
		

        if (!empty($journal_details) && !empty($journal_details->all())) {

            $journal_details = $journal_details[0];
			
			
			if($journal_details->subtitle == "CIS" || $journal_details->subtitle == "CCS" || $journal_details->subtitle == "CSS" || $journal_details->subtitle == "CMC" || $journal_details->subtitle == "CPD" || $journal_details->subtitle == "CAR" || $journal_details->subtitle == "CMM" || $journal_details->subtitle == "ACAMC")
			{
				
				
				$image_file_name = $journal_details->image_file_name;
				if ($image_file_name == "") {
					$image_file_name = 'no_image.jpg';
				}

				$journal_id = $journal_details->journal_id;
				$volume_id  = $journal_details->volume_id;
				$issue_id   = $journal_details->issue_id;

				$json_output['journal_details']['journal_id']       = $journal_details->journal_id;
				$json_output['journal_details']['journal_title']    = '<![CDATA[ ' . $journal_details->journal_title . ' ]]>';
				$json_output['journal_details']['journal_subtitle'] = $journal_details->subtitle;
				$json_output['journal_details']['issn']             = $journal_details->issn;
				$json_output['journal_details']['eissn']            = $journal_details->eissn;
				$json_output['journal_details']['price']            = $journal_details->price;
				$json_output['journal_details']['volume']           = $journal_details->volume_name;
				$json_output['journal_details']['issue_title']      = $journal_details->issue_title;
				$json_output['journal_details']['image_file_name']  = $image_file_name;

				$json_output['issue_url'] = 'https://www.eurekaselect.com/issue/' . $issue_id;
				
				$free_open_access = 0;

				//Check free or open access on volume
				$access_value = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $volume_id, "v");
				if ($access_value) {
					$free_open_access = $access_value;
				}
				
				//Check free or open access on issue
				if ($free_open_access == 0) {
					$access_value = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i");
					if ($access_value) {
						$free_open_access = $access_value;
					}
				}
				
				//echo $free_open_access;die;
				$freeArticleList;
				$OpenAccessArticleList;
				if ($free_open_access == 0) {
					$freeArticleList       = ContentAccess::GetFreeOpenAccessArticleList($journal_id, 1);
					$OpenAccessArticleList = ContentAccess::GetFreeOpenAccessArticleList($journal_id, 2);

				}
				//echo $issue_id;
				$articlesArray = Article::getAllArticlesByIssueID($issue_id);
				//rint_r($articlesArray);die;
				$cnt          = 0;
				$data_article = '';
				foreach ($articlesArray as $row) {
					$subscribed = false;

					$json_output['article'][$cnt]['translation']['english'] = 'en';
					$json_output['article'][$cnt]['article_id']             = $row->article_id;
					$json_output['article'][$cnt]['article_nid']            = $row->nid;
					$json_output['article'][$cnt]['pubmed_id']              = $row->pmid;
					$article_title                                          = html_entity_decode($row->title, ENT_QUOTES, 'UTF-8'); //iconv("UTF-8", "UTF-8//IGNORE", $row->title);
					$json_output['article'][$cnt]['article_title']          = '<![CDATA[ ' . $this->RemoveIllegalCharacters($article_title) . ' ]]>';
					$abstract                                               = html_entity_decode($this->RemoveIllegalCharacters($row->abstract), ENT_QUOTES, 'UTF-8'); //iconv("UTF-8", "UTF-8//IGNORE", $this->RemoveIllegalCharacters($row->abstract));
					$json_output['article'][$cnt]['abstract']               = '<![CDATA[ ' . $this->ConvertToEntityNumber($abstract) . ' ]]>';

					//if no issue and volume level access
					if (($free_open_access == 0) && ($freeArticleList)) {
						if (in_array($row->article_id, $freeArticleList)) {
							$json_output['article'][$cnt]['article_access'] = 'free';
						}
					}
					if (($free_open_access == 0) && ($OpenAccessArticleList)) {
						if (in_array($row->article_id, $OpenAccessArticleList)) {
							$json_output['article'][$cnt]['article_access'] = 'open access';
						}
					}
					if ($free_open_access == 1) {
						$json_output['article'][$cnt]['article_access'] = 'free';
					} else if ($free_open_access == 2) {
						$json_output['article'][$cnt]['article_access'] = 'open access';
					}

					if ($subscribed == true) {
						$json_output['article'][$cnt]['article_access'] = 'subscribed';
					}
					$openaccessarticle = ContentAccess::GetFreeOpenAccessArticlesbyarticleID($row->article_id);
					if ($openaccessarticle) {
						$data_article = (array) $openaccessarticle[0];
					}

					$issue = ContentAccess::GetFreeOpenAccessIssuesbyID($issue_id);
					if ($issue) {
						$data = (array) $issue[0];
						if ($data) {
							$json_output['article'][$cnt]['content_access_start_date'] = $data['from_date'];
							$json_output['article'][$cnt]['content_access_end_date']   = $data['to_date'];
							$json_output['article'][$cnt]['is_perpetual']              = $data['perpetual'];

						}
					}
					if ($data_article) {
						$json_output['article'][$cnt]['content_access_start_date'] = $data_article['from_date'];
						$json_output['article'][$cnt]['content_access_end_date']   = $data_article['to_date'];
						$json_output['article'][$cnt]['is_perpetual']              = $data_article['perpetual'];

					}

					$graphical_abstract         = "";
					$is_epub                    = $row->is_epub;
					$article_graphical_abstract = $row->graph_abs_lg_filename;

					if ($article_graphical_abstract != "") {

						$url = "https://www.eurekaselect.com";

						if ($is_epub == "0") {

							$graphical_abstract = $url . "/images/graphical-abstract/" . strtolower($journal_details->subtitle) . "/" . $journal_details->volume_name . "/" . $journal_details->issue_title . "/" . $article_graphical_abstract;

						} else {

							switch ($is_epub) {

								case "1":
									$folder = "EPUB";
									break;
								case "2":
									$folder = "QUICKTRACK";
									break;
								case "3":
									$folder = "EXPRESSTRACK";
									break;
							}

							$graphical_abstract = $url . "/images/graphical-abstract/" . strtolower($journal_details->subtitle) . "/" . $journal_details->volume . "/" . $folder . "/" . $journal_details->graphical_abstract;

						}
					}

					//$pub_date = $row['year']."-".$row['month']."-"."1";
					$pub_date = $row->month . "," . $row->year;

					$json_output['article'][$cnt]['first_page']   = $row->first_page;
					$json_output['article'][$cnt]['last_page']    = $row->last_page;
					$json_output['article'][$cnt]['page_count']   = $row->page_count;
					$json_output['article'][$cnt]['article_doi']  = $row->doi;
					$json_output['article'][$cnt]['article_type'] = $row->article_type_name;

					$json_output['article'][$cnt]['graphical_abstract'] = $graphical_abstract;
					$json_output['article'][$cnt]['publish_date']       = $pub_date;
					$json_output['article'][$cnt]['elocator']       = $row->elocator;

					$volume_authors = Author::getAuthorDataById($row->article_id, 'article_id');
					if ($volume_authors) {
						$AuthorNames = '';
						foreach ($volume_authors as $author) {
							if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
						}

						$AuthorNames = rtrim($AuthorNames, ', ');

						$pos = strrpos($AuthorNames, ",");
						if ($pos) {
							$str         = substr($AuthorNames, 0, $pos);
							$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
							$AuthorNames = $str . " and " . $str2;
						}

						$json_output['article'][$cnt]['aff'] = '<![CDATA[ ' . $this->RemoveIllegalCharacters($AuthorNames) . ' ]]>';
					} else {

					}
					$cnt++;
				}

				if ($request->format == 'xml') {

					$xml = json2xml(json_encode($json_output));
					$xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
					$xml = str_replace(']]&gt;',']]>',$xml);
					return Response::make($xml, '200')->header('Content-Type', 'text/xml');

					//return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

				} else {

					return response()->json($json_output, 200);
				}

			}

        } else {
			

            $json_output['error'] = 'No record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }

    /*
     * Date: 03-12-2018
     * Author: Muhammad Arshad
     * Parameter:journal nid
     * Description:  Getting all Free Issue of specific Journal
     */

    public function services_free_issues(Request $request)
    {

        $journal_details = Journal::where('nid', $request->journal_nid)->first();

        $image_file_name = $journal_details->image_file_name;
        if ($image_file_name == "") {
            $image_file_name = 'no_image.jpg';
        }

        $journal_id                     = $journal_details->journal_id;
        $json_output['journal_details'] = array(
            'journal_id'       => $journal_details->journal_id,
            'journal_title'    => $journal_details->title,
            'journal_subtitle' => $journal_details->subtitle,
            'issn'             => $journal_details->issn,
            'eissn'            => $journal_details->eissn,
            'price'            => $journal_details->price,
            'image_file_name'  => $image_file_name,
        );

        //Free or Open access volume level. 1 for Free and 2 for Open Access and 0 for both (free and open access)
        $FreeIssueList = ContentAccess::GetFreeOpenAccessIssues($journal_id, 0);

        $cnt = 0;
        foreach ($FreeIssueList as $data) {

            $json_output['free_issues']['issue'][$cnt]['volume_node']               = $data->volume_node;
            $json_output['free_issues']['issue'][$cnt]['volume']                    = $data->volume;
            $json_output['free_issues']['issue'][$cnt]['issue_node']                = $data->issue_node;
            $json_output['free_issues']['issue'][$cnt]['issue']                     = $data->issue;
            $json_output['free_issues']['issue'][$cnt]['month']                     = $data->month;
            $json_output['free_issues']['issue'][$cnt]['year']                      = $data->year;
            $json_output['free_issues']['issue'][$cnt]['access_type']               = $data->access_type;
            $json_output['free_issues']['issue'][$cnt]['content_access_start_date'] = $data->from_date;
            $json_output['free_issues']['issue'][$cnt]['content_access_end_date']   = $data->to_date;

            $cnt++;
        }

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');
           // return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json($json_output, 200);
        }

    }

    /*
     * Date: 19-12-2018
     * Author: Muhammad Arshad
     * Parameter: journal node id = nid
     * Description:  this function will return the open access article of specific journal
     */

    public function services_open_access_articles(Request $request)
    {
        $journal_details = Journal::where('nid', $request->nid)->first();

         if($journal_details){
            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }
        }

        $journal_id = $journal_details->journal_id;

        $journal_details_arr['journal_details'] = array(
            'journal_id'       => $journal_details->journal_id,
            'journal_title'    => '<![CDATA[ ' . $journal_details->title . ' ]]>',
            'journal_subtitle' => $journal_details->subtitle,
            'issn'             => $journal_details->issn,
            'eissn'            => $journal_details->eissn,
            'price'            => $journal_details->price,
            'image_file_name'  => $image_file_name,
        );

        $json_output[] = $journal_details_arr;

        //Free or Open access articles level
        $Open_Access_Article_List = ContentAccess::GetFreeOpenAccessArticles($journal_id, 2);

        $cnt = 1;
        foreach ($Open_Access_Article_List as $row) {

            $json_output_article['article']['volume']                    = $row->volume;
            $json_output_article['article']['issue']                     = $row->issue;
            $json_output_article['article']['month']                     = $row->month;
            $json_output_article['article']['year']                      = $row->year;
            $json_output_article['article']['article_nid']               = $row->nid;
			$json_output_article['article']['article_id']               = $row->article_id;
            $json_output_article['article']['pubmed_id']                 = $row->pmid;
            $json_output_article['article']['article_doi']               = $row->doi;
            $json_output_article['article']['article_title']             = '<![CDATA[ ' . $this->RemoveIllegalCharacters($row->title) . ' ]]>';
            $json_output_article['article']['abstract']                  = '<![CDATA[ ' . $this->RemoveIllegalCharacters($row->abstract) . ' ]]>';
            $json_output_article['article']['first_page']                = $row->first_page;
            $json_output_article['article']['last_page']                 = $row->last_page;
            $json_output_article['article']['page_count']                = $row->page_count;
            $json_output_article['article']['content_access_start_date'] = $row->from_date;
            $json_output_article['article']['content_access_end_date']   = $row->to_date;
			$json_output_article['article']['article_type'] 			 = $row->article_type_name;

            $volume_authors = Author::GetAuthorsByContentId($row->article_id, 'article_id');

            if ($volume_authors) {
                $AuthorNames = '';
                foreach ($volume_authors as $author) {
                    if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                }

                $AuthorNames = rtrim($AuthorNames, ', ');

                $pos = strrpos($AuthorNames, ",");

                if ($pos) {
                    $str         = substr($AuthorNames, 0, $pos);
                    $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                    $AuthorNames = $str . " and " . $str2;
                }

                $json_output_article['article']['author'] = '<![CDATA[ ' . $this->RemoveIllegalCharacters($AuthorNames) . ' ]]>';

            } else {

            }

            $json_output_article['article']['url'] = "https://www.eurekaselect.com/article/" . $row->article_id;
            $json_output[]                         = $json_output_article;
            $cnt++;

        }

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');

            //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json($json_output, 200);
        }

    }

    /*
     * Date: 21-12-2018
     * Author: Muhammad Arshad
     * Parameter: journal node id = nid
     * Description:  this function will return the most cited article of specific journal
     */
    public function services_mostcited_articles(Request $request)
    {

        $journal_details = Journal::where('nid', $request->nid)->first();

        $image_file_name = $journal_details->image_file_name;
        if ($image_file_name == "") {
            $image_file_name = 'no_image.jpg';
        }

        $journal_id = $journal_details->journal_id;

        $json_output['journal_details'] = array(
            'journal_id'       => $journal_details->journal_id,
            'journal_title'    => $journal_details->title,
            'journal_subtitle' => $journal_details->subtitle,
            'issn'             => $journal_details->issn,
            'eissn'            => $journal_details->eissn,
            'price'            => $journal_details->price,
            'image_file_name'  => $image_file_name,
        );

        $result = Journal::GetMostCitedArticles($journal_id);
        $cnt    = 0;
        foreach ($result as $row) {
            $json_output['article'][$cnt]['volume']        = $row->volume_name;
            $json_output['article'][$cnt]['issue']         = $row->issue;
            $json_output['article'][$cnt]['month']         = $row->month;
            $json_output['article'][$cnt]['year']          = $row->year;
            $json_output['article'][$cnt]['article_nid']   = $row->nid;
            $json_output['article'][$cnt]['article_id']   = $row->article_id;
            $json_output['article'][$cnt]['pubmed_id']     = $row->pmid;
            $json_output['article'][$cnt]['article_doi']   = $row->doi;
            $json_output['article'][$cnt]['article_title'] = $row->title;
            $json_output['article'][$cnt]['abstract']      = $this->RemoveIllegalCharacters($row->abstract);
            $json_output['article'][$cnt]['first_page']    = $row->first_page;
            $json_output['article'][$cnt]['last_page']     = $row->last_page;
            $json_output['article'][$cnt]['page_count']    = $row->page_count;
			$json_output['article'][$cnt]['article_type']  = $row->article_type_name;

            $article_authors = Author::GetAuthorsByContentId($row->article_id, 'article_id');
            if ($article_authors) {
                $AuthorNames = '';
                foreach ($article_authors as $author) {
                    if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                }

                $AuthorNames = rtrim($AuthorNames, ', ');

                $pos = strrpos($AuthorNames, ",");
                if ($pos) {
                    $str         = substr($AuthorNames, 0, $pos);
                    $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                    $AuthorNames = $str . " and " . $str2;
                }

                $json_output['article'][$cnt]['author'] = $this->RemoveIllegalCharacters($AuthorNames);
            } else {

            }
            $json_output['article'][$cnt]['url'] = "https://www.eurekaselect.com/article/" . $row->article_id;

            $cnt++;
        }

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');

            //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        } else {

            return response()->json($json_output, 200);
        }

    }

    /*
     * Date: 21-12-2018
     * Author: Muhammad Arshad
     * Parameter:
    param1 = journal_id
    param2 = track id (1=epub track, 2 = quick track , 3 express track
     * Description:  Getting all epub track / express track / fast track of specific journal
     */

    public function services_track_articles(Request $request)
    {

        $section_id = $request->section_id;
        $uid        = "";
        $user       = Auth::user();
        if ($user) {
            $uid = $user->id;
        }

        if ($section_id == "0") {
            die("Error! Invalid Track id");
        }

        $journal_details = Journal::where('nid', $request->nid)->first();
		
		if($journal_details->subtitle == "CIS" || $journal_details->subtitle == "CCS" || $journal_details->subtitle == "CMC" || $journal_details->subtitle == "CPD" || $journal_details->subtitle == "CAR" || $journal_details->subtitle == "CMM" || $journal_details->subtitle == "ACAMC")
		{

			$image_file_name = $journal_details->image_file_name;
			if ($image_file_name == "") {
				$image_file_name = 'no_image.jpg';
			}

			$journal_id = $journal_details->journal_id;

			$epubArticles      = Article::GetTrackList($journal_id, $section_id, 0);
			$epubArticlesCount = count($epubArticles);

			$json_output['journal_details'] = array(
				'journal_id'       => $journal_details->journal_id,
				'journal_title'    => $journal_details->title,
				'journal_subtitle' => $journal_details->subtitle,
				'issn'             => $journal_details->issn,
				'eissn'            => $journal_details->eissn,
				'price'            => $journal_details->price,
				'image_file_name'  => $image_file_name,
				'total_article'    => $epubArticlesCount,
			);

			//Free or Open access

			//Check Free / Open Access on Epub/quick track / express track Article
			$freeArticleList = ContentAccess::GetFreeOpenAccessArticles($journal_id, 1);
			if ($freeArticleList) {
				foreach ($freeArticleList as $fdata) {
					$arr[] = $fdata->ArticleID;
				}
				$freeArticleList = $arr;
			}
			$OpenAccessArticleList = ContentAccess::GetFreeOpenAccessArticles($journal_id, 2);
			if ($OpenAccessArticleList) {
				foreach ($OpenAccessArticleList as $odata) {
					$arr[] = $odata->ArticleID;
				}
				$OpenAccessArticleList = $arr;
			}

			$cnt = 0;

			foreach ($epubArticles as $row) {

				$subscribed = false;

				if ($uid != "") {

					if (ContentAccess::CheckPerpetualAccess($uid, $row->ArticleID, 'article')[0]->total > 0) {
						$subscribed = true;
					}

				}

				$json_output['article'][$cnt]['article_section'] = $row->article_section;
				$json_output['article'][$cnt]['article_nid']     = $row->nid;
				$json_output['article'][$cnt]['article_id']      = $row->article_id;
				$json_output['article'][$cnt]['pubmed_id']       = $row->pmid;
				$json_output['article'][$cnt]['article_doi']     = $row->doi;
				$json_output['article'][$cnt]['article_title']   = $row->title;
				$json_output['article'][$cnt]['abstract']        = $this->RemoveIllegalCharacters($row->abstract);
				$json_output['article'][$cnt]['first_page']      = $row->first_page;
				$json_output['article'][$cnt]['last_page']       = $row->last_page;
				$json_output['article'][$cnt]['page_count']      = $row->page_count;
				$json_output['article'][$cnt]['article_type']    = $row->article_type_name;

				$article_authors = Author::GetAuthorsByContentId($row->ArticleID, 'article_id');
				if ($article_authors) {
					$AuthorNames = '';
					foreach ($article_authors as $author) {
						if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
					}

					$AuthorNames = rtrim($AuthorNames, ', ');

					$pos = strrpos($AuthorNames, ",");
					if ($pos) {
						$str         = substr($AuthorNames, 0, $pos);
						$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
						$AuthorNames = $str . " and " . $str2;
					}

					$json_output['article'][$cnt]['author'] = $AuthorNames;
				} else {

				}
				$json_output['article'][$cnt]['url'] = "https://www.eurekaselect.com/article/" . $row->ArticleID;

				//if it is epub article
				if ($section_id == "1") {

					if (trim($row->epub_type) == "") {
						$epub_type = "epub-article";
					} else {
						$epub_type = $row->epub_type;
					}

					$json_output['article'][$cnt]['epub_type'] = $epub_type;

				}

				if (in_array($row->ArticleID, $freeArticleList) or in_array($row->ArticleID, $OpenAccessArticleList)) {
					$json_output['article'][$cnt]['access_type'] = "free";
				}

				if ($subscribed == true) {
					$json_output['article'][$cnt]['access_type'] = "subscribed";
				}
				$json_output['article'][$cnt]['article_created_on'] = $row->created;

				$cnt++;
			}

			if ($request->format == 'xml') {

				$xml = json2xml(json_encode($json_output));
				$xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
				$xml = str_replace(']]&gt;',']]>',$xml);
				return Response::make($xml, '200')->header('Content-Type', 'text/xml');
				//return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

			} else {

				return response()->json($json_output, 200);
			}
		}
    }

    /*
     * Date: 22-12-2018
     * Author: Muhammad Arshad
     * Parameter: article id = article id
     * Description:  this function will return the  article detail
     */

    public function services_article(Request $request)
    {

        $journal_details = Article::GetArticleDetail($request->article_id);
		
		if($journal_details->subtitle == "CIS" || $journal_details->subtitle == "CCS" || $journal_details->subtitle == "CMC" || $journal_details->subtitle == "CPD" || $journal_details->subtitle == "CAR" || $journal_details->subtitle == "CMM" || $journal_details->subtitle == "ACAMC")
		{

			if (!empty($journal_details)) {

				$image_file_name = $journal_details->image_file_name;
				if ($image_file_name == "") {
					$image_file_name = 'no_image.jpg';
				}

				$journal_id = $journal_details->journal_id;

				//Free or Open access articles level
				$Open_Access_Article_List = ContentAccess::GetFreeOpenAccessArticles($journal_id, 2);

				$json_output['labels'] = array(
					'issn_print'        => 'ISSN(Print)',
					'issn_online'       => 'ISSN(Online)',
					'volume'            => 'VOLUME',
					'issue'             => 'ISSUE',
					'price'             => 'Price',
					'authors'           => 'Author(s)',
					'pages'             => 'Pages',
					'page'              => 'Page',
					'doi'               => 'DOI',
					'abstract'          => 'Abstract',
					'affiliation'       => 'Affiliation',
					'keywords'          => 'Keywords',
					'graphicalabstract' => 'Graphical Abstract');

				$json_output['journal_details'] = array(
					'journal_id'       => $journal_details->journal_id,
					'journal_title'    => '<![CDATA[ ' . $journal_details->journal_title . ' ]]>',
					'journal_subtitle' => $journal_details->subtitle,
					'issn'             => $journal_details->issn,
					'eissn'            => $journal_details->eissn,
					'price'            => $journal_details->sell_price,
					'volume'           => $journal_details->volume,
					'issue_title'      => $journal_details->issue,
					'image_file_name'  => $image_file_name,
				);

				$article_id = $journal_details->article_id;

				$article_title = '<![CDATA[ ' . $this->RemoveIllegalCharacters($journal_details->title) . ' ]]>';
				$issue_id      = $journal_details->issue_id;
				$volume_id     = $journal_details->volume_id;

				$DownloadAccess = false;
				//check if article is free or open access

				$is_epub = $journal_details->is_epub;
				if (ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $article_id, "a") > 0) {
					$DownloadAccess = true;
				}

				if (!$DownloadAccess && ($is_epub == 0)) {
					if (ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i") > 0) {
						$DownloadAccess = true;
					}

				}

				if (!$DownloadAccess && ($is_epub == 0)) {
					if (ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $volume_id, "v") > 0) {
						$DownloadAccess = true;
					}

				}

				$converted_res = ($DownloadAccess) ? 'true' : 'false';

				$openaccessarticle = ContentAccess::GetFreeOpenAccessArticlesbyarticleID($article_id);
				if ($openaccessarticle) {
					$data = $openaccessarticle[0];
				}
				// print_r($data);die;
				$json_output['download_acccess'] = $converted_res;

				$graphical_abstract = "";
				if ($journal_details->graph_abs_lg_filename != "") {

					$url = "https://www.eurekaselect.com";
					if ($is_epub == "0") {

						$graphical_abstract = $url . "/images/graphical-abstract/" . strtolower($journal_details->subtitle) . "/" . $journal_details->volume . "/" . $journal_details->issue . "/" . $journal_details->graph_abs_lg_filename;

					} else {

						switch ($is_epub) {

							case "1":
								$folder = "EPUB";
								break;
							case "2":
								$folder = "QUICKTRACK";
								break;
							case "3":
								$folder = "EXPRESSTRACK";
								break;
							case "4":
								$folder = "ABSTRACT";
								break;
						}

						$graphical_abstract = $url . "/images/graphical-abstract/" . strtolower($journal_details->subtitle) . "/" . $journal_details->volume . "/" . $folder . "/" . $journal_details->graph_abs_lg_filename;

					}
				}

				$json_output['article_details']['article_id']    = $journal_details->article_id;
				$json_output['article_details']['is_epub']       = $journal_details->is_epub;
				$json_output['article_details']['article_type']  = $journal_details->type_name;
				$json_output['article_details']['article_title'] = $article_title;
				$json_output['article_details']['pubmed_id']     = $journal_details->pmid;
				$json_output['article_details']['article_id']    = $journal_details->article_id;

				if ($journal_details->is_epub > 0) {
					$pub_date = '';
				} else {
					$pub_date = $journal_details->year . "-" . $journal_details->month . "-" . "1";
					$pub_date = strftime("%d %B ,%Y", strtotime($pub_date));
				}
				$json_output['article_details']['article_url']        = "https://www.eurekaselect.com/article/" . $article_id;
				$json_output['article_details']['podcast_url']        = $journal_details->podcast;
				$json_output['article_details']['first_page']         = $journal_details->first_page;
				$json_output['article_details']['last_page']          = $journal_details->last_page;
				$json_output['article_details']['page_count']         = $journal_details->page_count;
				$json_output['article_details']['article_doi']        = $journal_details->doi;
				$json_output['article_details']['graphical_abstract'] = $graphical_abstract;
				$json_output['article_details']['publish_date']       = $pub_date;
				$json_output['article_details']['elocator']           = $journal_details->elocator;
				
				if ($openaccessarticle) {
					$json_output['article_details']['content_access_start_date'] = $data->from_date;
					$json_output['article_details']['content_access_end_date']   = $data->to_date;
					$json_output['article_details']['is_perpetual']              = $data->perpetual;
					$json_output['article_details']['article_access']            = $converted_res;
				}
				$affiliation     = '';
				$article_authors = Author::getAuthorDataById($article_id, 'article_id');

				if ($article_authors) {
					$AuthorNames = '';

					foreach ($article_authors as $author) {
						if ($author->is_principle == 1) {
							$AuthorNames .= $author->authors . '*' . ',  ';
							$affiliation .= $author->affiliation . ', ';
						} else {
							$AuthorNames .= $author->authors . ',  ';
							$affiliation .= $author->affiliation . ', ';
						}
					}

					$AuthorNames = rtrim($AuthorNames, ', ');
					$affiliation = rtrim($affiliation, ', ');

					$pos = strrpos($AuthorNames, ",");
					if ($pos) {
						$str         = substr($AuthorNames, 0, $pos);
						$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
						$AuthorNames = $str . " and " . $str2;
					}

					$json_output['article_details']['authors']     = '<![CDATA[ ' . $this->RemoveIllegalCharacters($AuthorNames) . ' ]]>';
					$json_output['article_details']['affiliation'] = '<![CDATA[ ' . $this->RemoveIllegalCharacters($affiliation) . ' ]]>';
				} else {

				}

				$abstract                                   = html_entity_decode($this->RemoveIllegalCharacters($journal_details->abstract));
				$json_output['article_details']['abstract'] = '<![CDATA[ ' . $abstract . ' ]]>';

				$keywords   = Keywords::getKeywordDataById($article_id, "article_id");
				$varkeyword = '';
				if (!empty($keywords)) {
					foreach ($keywords as $keyword) {
						$varkeyword .= $keyword->keyword . ',';
					}
				}
				$json_output['article_details']['keywords'] = '<![CDATA[ ' . rtrim($varkeyword, ',') . ' ]]>';
				$json_output['article_details']['aff']      = '<![CDATA[ ' . $this->RemoveIllegalCharacters($affiliation) . ' ]]>';

				if ($request->format == 'xml') {
					$xml = json2xml(json_encode($json_output));
					$xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
					$xml = str_replace(']]&gt;',']]>',$xml);
					return Response::make($xml, '200')->header('Content-Type', 'text/xml');
					//return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

				} else {

					return response()->json($json_output, 200);
				}


			} else {
				$json_output['error'] = 'No record Found';
				return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
			}
		}
		else
		{
				$json_output['error'] = 'You are not authorized';
				return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
		}

    }

    /*
     * Date: 22-12-2018
     * Author: Muhammad Arshad
     * Parameter: param1 = journal_id
    param2 = Type number (1=editor Choice, 2 = Highlighted , 3 = Popular
     * Description:  This web service will display special articles like "editor Choice", "Highlighted" and "Popular" artciles
     */

    public function services_special_articles(Request $request)
    {

        $nid            = $request->nid;
        $type           = $request->type;
        $FreeVolumeList = array();
        $freeArticleList = array();
        $FreeIssueList  =   array();
        $OpenAccessVolumeList =  array();
        $OpenAccesIssueList =  array();
        $OpenAccessArticleList =  array();
		
        if ($type == "0" or $type == "" or $type > 3) {
            $type = "1";
        }
	
        $journal_details = Journal::where('nid', $request->nid)->first();
		
		if($journal_details){
			$image_file_name = $journal_details->image_file_name;
			if ($image_file_name == "") {
				$image_file_name = 'no_image.jpg';
			}


			$journal_id = $journal_details->journal_id;

			$pagesize     = $request->pagesize ? $request->pagesize : 0;
			$epubArticles = Article::GetSpecialArticles($journal_id, $type, $pagesize);
			
			$epubArticlesCount = $epubArticles->count();

			$free_open_access    = 0;
			$param['journal_id'] = $journal_id;
			//Free or Open access volume level
			$param['access_type'] = 1; //openaccess volume list
			$FreeVolumeList = ContentAccess::GetContentAccessVolumeList($param);
			if ($FreeVolumeList) {
				foreach ($FreeVolumeList as $ovl) {
					$ovl_array[] = $ovl->content_type_id;
				}
				$FreeVolumeList = $ovl_array;
            }else{
               $FreeVolumeList = array();
			}
			$param['access_type'] = 2; //openaccess volume list
			$OpenAccessVolumeList = ContentAccess::GetContentAccessVolumeList($param);
			if ($OpenAccessVolumeList) {
				foreach ($OpenAccessVolumeList as $ovl) {
					$ovl_array[] = $ovl->content_type_id;
				}
				$OpenAccessVolumeList = $ovl_array;
            }else{
               $OpenAccessVolumeList = array();
			}
			//Free or Open access issue level
			$param['access_type'] = 1; //free issue list
			$FreeIssueList        = ContentAccess::GetContentAccessIssueList($param);
			if ($FreeIssueList) {
				foreach ($FreeIssueList as $fil) {
					$fil_array[] = $fil->content_type_id;
				}
				$FreeIssueList = $fil_array;
            }else{
               $FreeIssueList = array();
			}
			$param['access_type'] = 2; //openaccess issue list
			$OpenAccesIssueList   = ContentAccess::GetContentAccessIssueList($param);
			if ($OpenAccesIssueList) {
				foreach ($OpenAccesIssueList as $oil) {
					$oil_array[] = $oil->content_type_id;
				}
				$OpenAccesIssueList = $oil_array;
            }else{
               $OpenAccesIssueList = array();
			}

			//Free or Open access article level
			$param['access_type'] = 1; //free article list
			$freeArticleList      = ContentAccess::GetContentAccessArticleList($param);
			if ($freeArticleList) {
				foreach ($freeArticleList as $ail) {
					$ail_array[] = $ail->content_type_id;
				}
				$freeArticleList = $ail_array;
            }else{
               $freeArticleList = array();
			}
			$param['access_type']  = 2; //openaccess article list
			$OpenAccessArticleList = ContentAccess::GetContentAccessArticleList($param);
			if ($OpenAccessArticleList) {
				foreach ($OpenAccessArticleList as $ail) {
					$ail_array[] = $ail->content_type_id;
				}
				$OpenAccessArticleList = $ail_array;
            }else{
               $OpenAccessArticleList = array();
			}

			$cnt = 0;
			
			$json_output['journal_details'] = array(
				'journal_id'       => $journal_details->journal_id,
				'journal_title'    => $journal_details->title,
				'journal_subtitle' => $journal_details->subtitle,
				'issn'             => $journal_details->issn,
				'eissn'            => $journal_details->eissn,
				'price'            => $journal_details->price,
				'image_file_name'  => $image_file_name,
				'total_article'    => $epubArticlesCount,
			);
			
			foreach ($epubArticles as $row) {
				$json_output['article'][$cnt]['volume_year']   = $row->volume_year;
				$json_output['article'][$cnt]['volume']        = $row->volume_name;
				$json_output['article'][$cnt]['issue']         = $row->issue;
				$json_output['article'][$cnt]['article_nid']   = $row->article_nid;
				$json_output['article'][$cnt]['article_id']    = $row->article_id;
				$json_output['article'][$cnt]['pubmed_id']     = $row->pmid;
				$json_output['article'][$cnt]['article_title'] = $row->title;
				$json_output['article'][$cnt]['abstract']      = '<![CDATA[' . $this->RemoveIllegalCharacters($row->abstract) . ']]>';
				$json_output['article'][$cnt]['first_page']    = $row->first_page;
				$json_output['article'][$cnt]['last_page']     = $row->last_page;
				$json_output['article'][$cnt]['page_count']    = $row->page_count;
				$json_output['article'][$cnt]['article_doi']   = $row->doi;
				$json_output['article'][$cnt]['article_type']  = $row->type;

				$article_authors = Author::GetAuthorsByContentId($row->article_id, 'article_id');
				if ($article_authors) {
					$AuthorNames = '';
					foreach ($article_authors as $author) {
						if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
					}

					$AuthorNames = rtrim($AuthorNames, ', ');

					$pos = strrpos($AuthorNames, ",");
					if ($pos) {
						$str         = substr($AuthorNames, 0, $pos);
						$str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
						$AuthorNames = $str . " and " . $str2;
					}

					$json_output['article'][$cnt]['author'] = '<![CDATA[' . $this->RemoveIllegalCharacters($AuthorNames) . ']]>';
				} else {

				}
				$json_output['article'][$cnt]['url'] = "https://www.eurekaselect.com/article/" . $row->article_id;

				//if it is epub article
				if ($row->is_epub == "1") {

					if (trim($row->epub_type) == "") {
						$epub_type = "epub-article";
					} else {
						$epub_type = $row->epub_type;
					}

					$json_output['article'][$cnt]['epub_type'] = $epub_type;

				}

				//  print("hello = ".$row['article_id']); exit;

				if (in_array($row->article_id, $freeArticleList) or in_array($row->article_id, $OpenAccessArticleList)) {
					$json_output['article'][$cnt]['access_type'] = 'free';
				}
				
				if (in_array($row->volume_id, $FreeVolumeList) or in_array($row->volume_id, $OpenAccessVolumeList)) {
					$json_output['article'][$cnt]['access_type'] = 'free';
				}

				if (in_array($row->issue_id, $FreeIssueList) or in_array($row->issue_id, $OpenAccesIssueList)) {
					$json_output['article'][$cnt]['access_type'] = 'free';
				}

				$cnt++;
			}
			
			if ($request->format == 'xml') {

				$xml = json2xml(json_encode($json_output));
				$xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
				$xml = str_replace(']]&gt;',']]>',$xml);
				return Response::make($xml, '200')->header('Content-Type', 'text/xml');
				//return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

			} else {

				return response()->json($json_output, 200);
			}
		}

    }

    /*
     * Date: 24-12-2018
     * Author: Muhammad Arshad
     * Parameter: param1 = journal_id
    param2 = volumeno (optional)
    param3 = issueno (optional)
    param4 = pagesize (optional)
     * Description:  This web service will get the most downloaded  artciles
     */
    public function services_most_download_articles(Request $request)
    {

        $journal_nid = $request->journal_nid;
        $volumeno    = $request->volumeno;
        $issueno     = $request->issueno;
        $pagesize    = $request->pagesize;

        $journal_details = Journal::where('nid', $journal_nid)->first();

        if (!empty($journal_details)) {

            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }

            $journal_id = $journal_details->journal_id;

            $json_output['journal_details'] = array(
                'journal_id'       => $journal_details->journal_id,
                'journal_title'    => $journal_details->title,
                'journal_subtitle' => $journal_details->subtitle,
                'issn'             => $journal_details->issn,
                'eissn'            => $journal_details->eissn,
                'price'            => $journal_details->price,
                'image_file_name'  => $image_file_name,
            );

            $free_open_access = 0;

            $articlesArray = Journal::getMostDownloadedArticles($journal_nid, $volumeno, $issueno, $pagesize);

            //6=Editorial
            //14=Preface
            //18=Acknowledgement
            //21=Biography
            $article_type_arr = array("6", "14", "18", "21");
            $cnt              = 0;
            foreach ($articlesArray as $row) {
                if (!in_array($row->art_type, $article_type_arr)) {

                    $json_output['article'][$cnt]['volume']        = $row->volume;
                    $json_output['article'][$cnt]['issue']         = $row->issue;
                    $json_output['article'][$cnt]['month']         = $row->month;
                    $json_output['article'][$cnt]['year']          = $row->year;
                    $json_output['article'][$cnt]['article_nid']   = $row->article_nid;
					$json_output['article'][$cnt]['article_id']   = $row->article_id;
                    $json_output['article'][$cnt]['pubmed_id']     = $row->pmid;
                    $json_output['article'][$cnt]['article_title'] = $row->article_title;
                    $json_output['article'][$cnt]['first_page']    = $row->first_page;
                    $json_output['article'][$cnt]['last_page']     = $row->last_page;
                    $json_output['article'][$cnt]['page_count']    = $row->page_count;
                    $json_output['article'][$cnt]['article_doi']   = $row->article_doi;
					$json_output['article'][$cnt]['article_type']  = $row->article_type_name;

                    $article_authors = Author::GetAuthorsByContentId($row->article_id, 'article_id');
                    if ($article_authors) {
                        $AuthorNames = '';
                        foreach ($article_authors as $author) {
                            if ($author->is_principle == 1) {$AuthorNames .= $author->authors . '*' . ',  ';} else { $AuthorNames .= $author->authors . ',  ';}
                        }

                        $AuthorNames = rtrim($AuthorNames, ', ');

                        $pos = strrpos($AuthorNames, ",");
                        if ($pos) {
                            $str         = substr($AuthorNames, 0, $pos);
                            $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                            $AuthorNames = $str . " and " . $str2;
                        }

                        $json_output['article'][$cnt]['author'] = $AuthorNames;
                    } else {
                        $json_output['article'][$cnt]['author'] = '';
                    }

                    $cnt++;

                }

            }

            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    } //function most downloaded article
	
	/*
     * Date: 24-12-2018
     * Author: Muhammad Arshad
     * Parameter: param1 = journal_nid
   
     * Description:  This web service will get the related journals
     */
    
    public function services_related_journals(Request $request)
    {	

		if (isset($request->pagesize)) {
            $pagesize = $request->pagesize;
        } else {
            $pagesize = 10;
        }

        $journal_nid = $request->journal_nid;     

        $journal_details = Journal::where('nid', $journal_nid)->first();

        if (!empty($journal_details)) {

            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }

            $journal_id = $journal_details->journal_id;          

          
            $related_journal     = Subject::RelatedJournalBySubjectId($journal_id,$pagesize);            
            
            $cnt              = 0;
			$json_output=array();
			if(!empty($related_journal)){
				foreach ($related_journal as $row) {
					
						$json_output['journal_details'][$cnt]['journal_id']       = $row->journal_id;
						$json_output['journal_details'][$cnt]['journal_nid']      = $row->journal_nid;
						$json_output['journal_details'][$cnt]['journal_title']    = $row->title;
						$json_output['journal_details'][$cnt]['journal_subtitle'] = $row->subtitle;
						$json_output['journal_details'][$cnt]['issn']             = $row->issn;
						$json_output['journal_details'][$cnt]['eissn']            = $row->eissn;
						$json_output['journal_details'][$cnt]['keyword']          = $row->keyword;
						$json_output['journal_details'][$cnt]['description']      = $row->description;
						$json_output['journal_details'][$cnt]['journal_insight_url']  = $row->journal_insight_url;
						$json_output['journal_details'][$cnt]['image_file_name']      = $row->image_file_name;
						$json_output['journal_details'][$cnt]['journal_doi']          = $row->doi;
						
						
						$cnt++;                

				}

				if ($request->format == 'xml') {

					$xml = json2xml(json_encode($json_output));
					$xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
					$xml = str_replace(']]&gt;',']]>',$xml);
					return Response::make($xml, '200')->header('Content-Type', 'text/xml');

					//return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

				} else {

					return response()->json($json_output, 200);
				}
			}else{
				$json_output['error'] = 'No Record Found';
				return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
			}
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    } //function related journals
	
    /*
     * Date: 28-12-2018
     * Author: Muhammad Arshad
     * Parameter: param1 = search text

     * Description:  This web service will get the search result from amazon cloud search
     */

    public function services_search(Request $request)
    {

        if ($request->searchvalue == '') {

            $json_output['results'] = '0';
            return response()->json($json_output, 200);
        }
        if ($request->searchvalue == "DOI") {
            $jms_ref = $request->pagesize;
            return $this->services_get_doi($jms_ref, $request);
        } else {
            $request->btnjournalsearch       = '';
            list($results, $page, $pagesize, $pagename) = app('App\Http\Controllers\SearchController')->amazon_search_get_webservicedata($request,'ws');
            $results                         = json_decode($results);
            
            $tot_record                      = $results->hits->found;

            if ($results) {

                $json_output['tot_record'] = $tot_record;
                $json_output['page']       = $page;
                $json_output['pagesize']   = $pagesize;
                $json_output['status']     = 1;
                $a                         = 0;
                $c                         = 0;
                $v                         = 0;

                for ($i = 0; $i < count($results->hits->hit); $i++) {

                    //$title = trim($results->hits->hit[$i]->fields->title);
                    //echo $title;die;
                    //$row = $results[$i];
                    $genre = $results->hits->hit[$i]->fields->genre;

                    if ($genre === 'article') {

                        $json_output['article'][$a]['article_id']  = $results->hits->hit[$i]->fields->id;
                        $json_output['article'][$a]['article_nid'] = $results->hits->hit[$i]->fields->nid;
                        $json_output['article'][$a]['doi'] = $results->hits->hit[$i]->fields->doi;

                        $article_title                               = isset($results->hits->hit[$i]->fields->title) ? trim($results->hits->hit[$i]->fields->title) : '';
                        $article_title                               = strip_tags($article_title);
                        $article_title                               = str_replace('&amp;ndash;', '&ndash;', $article_title);
                        $article_title                               = str_replace('&ndash;', '&#x02013;', $article_title);
                        $json_output['article'][$a]['article_title'] = htmlspecialchars($this->RemoveIllegalCharacters($article_title));
                        $abstract                                    = isset($results->hits->hit[$i]->fields->abstract) ? trim($results->hits->hit[$i]->fields->abstract) : '';
                        $abstract                                    = strip_tags($abstract);
                        $abstract                                    = str_replace('&amp;ndash;', '&ndash;', $abstract);
                        $abstract                                    = str_replace('&rsquo;', "'", $abstract);
                        $abstract                                    = str_replace('&ndash;', '&#x02013;', $abstract);
                        $json_output['article'][$a]['abstract']      = "<![CDATA[ " . htmlspecialchars($abstract) . " ]]>";

                        $json_output['article'][$a]['journal_title'] = "<![CDATA[ " . htmlspecialchars($results->hits->hit[$i]->fields->journal_ebook_title) . " ]]>";

                        $pub_date = $results->hits->hit[$i]->fields->issue_publication_date;

                        if ($pub_date == 0) {
                            $month      = strftime("%B", strtotime($pub_date));
                            $year       = strftime("%Y", strtotime($pub_date));
                            $issue_date = "01 " . $month . " " . $year;
                        } else {
                            $day        = strftime("%d", strtotime($pub_date));
                            $month      = strftime("%B", strtotime($pub_date));
                            $year       = strftime("%Y", strtotime($pub_date));
                            $issue_date = $day . " " . $month . " " . $year;
                        }
                        $json_output['article'][$a]['journal_subtitle'] = $results->hits->hit[$i]->fields->subtitle;
                        if (isset($results->hits->hit[$i]->fields->issn)) {
                            $json_output['article'][$a]['journal_issn'] = isset($results->hits->hit[$i]->fields->issn) ? $results->hits->hit[$i]->fields->issn : '';
                        }
                        if (isset($results->hits->hit[$i]->fields->eissn)) {
                            $json_output['article'][$a]['journal_eissn'] = isset($results->hits->hit[$i]->fields->eissn) ? $results->hits->hit[$i]->fields->eissn : '';
                        }

                        $json_output['article'][$a]['volume']     = $results->hits->hit[$i]->fields->volume_title;
                        $json_output['article'][$a]['issue']      = $results->hits->hit[$i]->fields->issue_title;
                        $json_output['article'][$a]['issue_date'] = $issue_date;
                        if(isset($results->hits->hit[$i]->fields->first_page)){
                            $json_output['article'][$a]['first_page'] = $results->hits->hit[$i]->fields->first_page;
                        }
                        if(isset($results->hits->hit[$i]->fields->last_page)){
                            $json_output['article'][$a]['last_page'] = $results->hits->hit[$i]->fields->last_page;
                        }					
						

                        $article_authors = Author::GetAuthorsByContentId($results->hits->hit[$i]->fields->id, 'article_id');
                        $cAuthorNames    = '';
                        $cAuthorAff      = '';
                        if ($article_authors) {
                            foreach ($article_authors as $cauthor) {
                                if ($cauthor->is_principle == 1) {
                                    $cAuthorNames = $cauthor->authors . '*' . ',  ';
                                } else {
                                    $cAuthorNames = $cauthor->authors . ',  ';
                                }
                                $cAuthorAff = $cauthor->affiliation;
                            }
                        }
                        $json_output['article'][$a]['author']      = "<![CDATA[ " . $cAuthorNames . " ]]>";
                        $json_output['article'][$a]['affiliation'] = "<![CDATA[ " . $cAuthorAff . " ]]>";
                        $a++;
                    }

                    //print($art_cd);die;
                    if ($genre === 'chapter') {

                        $json_output['chapter'][$c]['chapter_id']              = $results->hits->hit[$i]->fields->id;
                        $json_output['chapter'][$c]['chapter_nid']             = $results->hits->hit[$i]->fields->nid;
                        $json_output['chapter'][$c]['doi']             			= $results->hits->hit[$i]->fields->doi;
                        $chapter_title                                         = $results->hits->hit[$i]->fields->title;
                        $chapter_title                                         = strip_tags($chapter_title);
                        $chapter_title                                         = str_replace('&amp;ndash;', '&ndash;', $chapter_title);
                        $chapter_title                                         = str_replace('&ndash;', '&#x02013;', $chapter_title);
                        $json_output['chapter'][$c]['chapter_title']           = htmlspecialchars($chapter_title);
                        $json_output['chapter'][$c]['ebook_name']              = "<![CDATA[ " . htmlspecialchars($results->hits->hit[$i]->fields->journal_ebook_title) . " ]]>";
                        
                        $abstract                                              = isset($results->hits->hit[$i]->fields->abstract) ? $results->hits->hit[$i]->fields->abstract : '';
                        $abstract                                              = strip_tags($abstract);
                        $abstract                                              = str_replace('&amp;ndash;', '&ndash;', $abstract);
                        $abstract                                              = str_replace('&rsquo;', "'", $abstract);
                        $abstract                                              = str_replace('&ndash;', '&#x02013;', $abstract);
                        $json_output['chapter'][$c]['abstract']                = "<![CDATA[ " . htmlspecialchars($abstract) . " ]]>";
                        $json_output['chapter'][$c]['volume']                  = $results->hits->hit[$i]->fields->volume_title;
                        $json_output['chapter'][$c]['volume_publication_date'] = $results->hits->hit[$i]->fields->volume_publication_date;
                        if(isset($results->hits->hit[$i]->fields->first_page)){
                            $json_output['chapter'][$c]['first_page']              = $results->hits->hit[$i]->fields->first_page;
                        }
                        if(isset($results->hits->hit[$i]->fields->last_page)){
                            $json_output['chapter'][$c]['last_page']               = $results->hits->hit[$i]->fields->last_page;
                        }

                        $chapter_authors = Author::GetAuthorsByContentId($results->hits->hit[$i]->fields->id, 'chapter_id');
                        $cAuthorNames    = '';
                        $cAuthorAff      = '';
                        if ($chapter_authors) {
                            foreach ($chapter_authors as $cauthor) {
                                if ($cauthor->is_principle == 1) {
                                    $cAuthorNames = $cauthor->authors . '*' . ',  ';
                                } else {
                                    $cAuthorNames = $cauthor->authors . ',  ';
                                }
                                $cAuthorAff = $cauthor->affiliation;
                            }
                        }
                        $json_output['chapter'][$c]['author']      = $cAuthorNames;
                        $json_output['chapter'][$c]['affiliation'] = $cAuthorAff;

                        $c++;
                    }
                    if ($genre === 'ebookvolume') {

                        $json_output['ebook'][$v]['ebook_volume_id'] = $results->hits->hit[$i]->fields->id;
                        $json_output['ebook'][$v]['volume_nid']      = $results->hits->hit[$i]->fields->nid;
                        $json_output['ebook'][$v]['doi']      			= $results->hits->hit[$i]->fields->doi;
                        $json_output['ebook'][$v]['volume']          = htmlspecialchars($results->hits->hit[$i]->fields->volume_title);
                        $json_output['ebook'][$v]['ebook_name']      = "<![CDATA[ " . htmlspecialchars($results->hits->hit[$i]->fields->journal_ebook_title) . " ]]>";

                        $ebook_authors = Author::GetAuthorsByContentId($results->hits->hit[$i]->fields->id, 'ebook_volume_id');
                        $cAuthorNames  = '';
                        $cAuthorAff    = '';
                        if ($ebook_authors) {
                            foreach ($ebook_authors as $cauthor) {
                                if ($cauthor->is_principle == 1) {
                                    $cAuthorNames = $cauthor->authors . '*' . ',  ';
                                } else {
                                    $cAuthorNames = $cauthor->authors . ',  ';
                                }
                                $cAuthorAff = $cauthor->affiliation;
                            }
                        }
                        $json_output['ebook'][$v]['author']      = "<![CDATA[ " . $cAuthorNames . " ]]>";
                        $json_output['ebook'][$v]['affiliation'] = "<![CDATA[ " . $cAuthorAff . " ]]>";

                    }

                    //$pub_date="";
                    //$issue_date="";
                }
                /*$countByjournal = $facet_fields->journal_title;

            if($countByjournal){
            foreach($countByjournal as $key=>$value){

            $json_output['journal']['journal_name'] = htmlspecialchars($key);
            $json_output['journal']['articlecount'] = $value;
            }
            }*/
            } else {
                $json_output['status'] = 0;
            }

        } //if else
        //dd($json_output);

        if ($request->format == 'xml') {

            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');
            //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        } else {
            
            foreach($json_output['article'] as $k=>$val){
                foreach($val as $key=>$value){           
                    $value=str_replace("<![CDATA[","",$value);
                    $val[$key]=str_replace("]]>","",$value);
                }
                $json_output['article'][$k]= $val;
            }
            
            return response()->json($json_output, 200);
        }

    }

    public function services_get_doi($jms_refno, $request)
    {

        $article_details = Article::where('jms_ref_no', '=', $jms_refno)->first();
		
		if($article_details){
			$json_output['article']['article_ID'] = $article_details->article_id;
			$json_output['article']['jms_ref_no'] = $article_details->jms_ref_no;

			$doi = trim($article_details->doi);
			$pmid = trim($article_details->pmid);
			$elocator = trim($article_details->elocator);
			$title = trim($article_details->title);
		}
        if (empty($doi)) {
            $doi = 0;
			$pmid =0;
			$elocator=0;
			$title = 0;
        } else {
            $doi = $article_details->doi;
        }
		
        $json_output['article']['article_doi']   = $doi;
        $json_output['article']['pubmed_id']     = $pmid;
		$json_output['article']['elocator']     = $elocator;
        $json_output['article']['article_title'] = $title;

        //if ($request->format == 'xml') {

            $xml = json2xml(json_encode($json_output));
            $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
            $xml = str_replace(']]&gt;',']]>',$xml);
            return Response::make($xml, '200')->header('Content-Type', 'text/xml');

            //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

        //} else {

        //    return response()->json($json_output, 200);
        //}

    }
	
	public function services_IFA(Request $request)
    {

        $journal_id = $request->journal_id;       

        $journal_details = Journal::where('journal_id', $journal_id)->first();

        if (!empty($journal_details)) { 
            
            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }

            $ifa  = file_get_contents(url('instructions-for-authors/'.strtolower($journal_details->subtitle).'-instructions-for-authors.html') ) ;
            
            $json_output['journal_details'] = array(
                'journal_id'       => $journal_details->journal_id,
                'journal_title'    => $journal_details->title,
                'journal_subtitle' => $journal_details->subtitle,
                'issn'             => $journal_details->issn,
                'eissn'            => $journal_details->eissn,                
                'image_file_name'  => $image_file_name,
                'ifa'    => $ifa,
            );

                  
            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }
	
	public function services_EditorialPolicy(Request $request)
    {

        $journal_id = $request->journal_id;       

        $journal_details = Journal::where('journal_id', $journal_id)->first();

        if (!empty($journal_details)) { 
            
            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }

            $policies  = file_get_contents(url('editorial-policies/'.strtolower($journal_details->subtitle).'-editorial-policies.html') ) ;
            
            $json_output['journal_details'] = array(
                'journal_id'       => $journal_details->journal_id,
                'journal_title'    => $journal_details->title,
                'journal_subtitle' => $journal_details->subtitle,
                'issn'             => $journal_details->issn,
                'eissn'            => $journal_details->eissn,                
                'image_file_name'  => $image_file_name,
                'editorial_policies'    => $policies,
            );
                        
                  
            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }
	public function services_EABM(Request $request)
    {

        $journal_id = $request->journal_id;       

        $journal_details = Journal::where('journal_id', $journal_id)->first();

        if (!empty($journal_details)) { 
            
            $image_file_name = $journal_details->image_file_name;
            if ($image_file_name == "") {
                $image_file_name = 'no_image.jpg';
            }

            $eabm  = file_get_contents(url('editorial-board/'.strtolower($journal_details->subtitle).'-editorial-board.html') ) ;
            
            $json_output['journal_details'] = array(
                'journal_id'       => $journal_details->journal_id,
                'journal_title'    => $journal_details->title,
                'journal_subtitle' => $journal_details->subtitle,
                'issn'             => $journal_details->issn,
                'eissn'            => $journal_details->eissn,                
                'image_file_name'  => $image_file_name,
                'editorial_board'    => $eabm,
            );
                        
                  
            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }
	
	function OrderStatus(Request $request) { 
        
        
        $param  = $request->order_id;
        
        if(strrpos($param,"@") > 0) $email = $param; else $order_id = $param;
        
		
        
        $query = "select * from uc_orders ";
        
        if(strrpos($param,"@") > 0) 
            $query .= " where primary_email= '".$email. "'";
        else 
            $query .= " where order_id= ".$order_id;
        
        $result = DB::select($query);
        if($result){        
        
        $cnt = 0;

        foreach ($result as $item) {   

            $order_id = $item->order_id;
            
            $json_output[$cnt] = array(
                'order_id'          =>  $order_id,
                'order_status'       => $item->order_status,
                'primary_email'    => $item->primary_email,                
                'order_amount'             => number_format($item->order_total,2),
                'order_date'            => strftime("%b %d, %Y",$item->created),                                
            ); 

            $query2 = "select * from uc_order_products where order_id = ".$order_id;        
            $result2 = DB::select($query2); 
            $ord_prd = "";  

            foreach ($result2 as $item2) {        
            
                $json_output[$cnt]['products']['product'] = "<![CDATA[".$item2->title."]]>";
                $json_output[$cnt]['products']['price'] = number_format($item2->price,2);
            }
           $cnt ++;
        }
        
        if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {

                return response()->json($json_output, 200);
            }
        } else {
            $json_output['error'] = 'No Record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }
    }
	
    public function RemoveIllegalCharacters($str) {

    /*
        Part of the problem is that you aren't treating the target as a UTF-8 string; you need the /u modifier for that. Also, in UTF-8 
        any non-ASCII character is represented by two or more bytes, all of them in the range \x80..\xFF. Try this:
        \p{Cc} is the Unicode property for control characters, and the u causes both the regex and the target string to be treated as UTF-8.
    */
    //$str = html_entity_decode($str);
    return preg_replace('/\p{Cc}+/u', ' ', $str);

    //return preg_replace("/[^()-+={}[],%@~:<>?a-zA-Z0-9#&;\.,\/\s]/","",$str);
    
    //return  preg_replace("/[^(\x20-\x7F)]*/","", $str);

    }

    /*
     * Date: 14-07-2022
     * Author: Imran Khan
     * Parameter: journal id
     * Description:  this function will return the specific journal sections
     */
    public function GetJournalSection(Request $request)
    {
        $journal = Journal::where('journal_id', $request->journal_id)->first();

        if($journal)
        {
            $param['journal_id'] = $journal->journal_id;
            $param['journal_id'] = $journal->journal_id;
            $param['status'] = 1; //Active section
            $param['paginate'] = 30;
            
            $result = Journal::GetJournalSection($param);
            $cnt    = 0;
            foreach ($result as $row) {
                $json_output['section'][$cnt]['journal_id']                 = $row->journal_id;
                $json_output['section'][$cnt]['journal_subtitle']           = $row->subtitle;
                $json_output['section'][$cnt]['journal_title']              = $row->title;
                $json_output['section'][$cnt]['section_id']                 = $row->js_id;
                $json_output['section'][$cnt]['section_code']               = $row->js_code;
                $json_output['section'][$cnt]['section_title']              = $row->js_title;
                $json_output['section'][$cnt]['section_description']        = $this->RemoveIllegalCharacters($row->js_description);
                $json_output['section'][$cnt]['section_aims_and_scope']     = $this->RemoveIllegalCharacters($row->js_aims_and_scope);
                $json_output['section'][$cnt]['section_url']                = "https://www.eurekaselect.com/journal/".$row->journal_id."/section/".$row->js_id."";

                $cnt++;
            }

           // dd($json_output);

            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                $xml = str_replace(']]&gt;',']]>',$xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } 
            else 
            {

                return response()->json($json_output, 200);
            }
        } 
        else 
        {
            $json_output['error'] = 'No record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }

    /*
     * Date: 15-07-2022
     * Author: Imran Khan
     * Parameter: journal id
     * Description:  this function will return the specific section articles
     */
    public function GetJournalSectionArticles(Request $request)
    {
        $param['js_id'] = $request->section_id;

        $journal_section = Journal::GetJournalSection($param)->first();

        if($journal_section)
        {
            $article_list = Article::getAllArticlesByIssueID(0,20, $journal_section->journal_id, $journal_section->js_id);

            if($article_list)
            {
                $cnt    = 0;
                foreach ($article_list as $row) {

                    $AuthorNames     = '';
                    $article_authors = Author::GetAuthorsByContentId($row->article_id, 'article_id');
                    if (!empty($article_authors)) {
                        $AuthorNames = '';
                        foreach ($article_authors as $author) {
                            if ($author->is_principle == 1) {
                                $AuthorNames .= $author->authors . '*' . ',  ';
                            } else {
                                $AuthorNames .= $author->authors . ',  ';
                            }
                        }

                        $AuthorNames = rtrim($AuthorNames, ', ');
                    }

                    $pos = strrpos($AuthorNames, ",");
                    if ($pos) {
                        $str         = substr($AuthorNames, 0, $pos);
                        $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                        $AuthorNames = $str . " and " . $str2;
                    }

                    $json_output['section'][$cnt]['section_id']            = $row->js_id;
                    $json_output['section'][$cnt]['section_title']            = $row->js_title;
                    $json_output['section'][$cnt]['article_id']            = $row->article_id;
                    $json_output['section'][$cnt]['title']      = $this->RemoveIllegalCharacters($row->title);
                    $json_output['section'][$cnt]['first_page']         = $row->first_page;
                    $json_output['section'][$cnt]['last_page']         = $row->last_page;
                    $json_output['section'][$cnt]['page_count']          = $row->page_count;
                    $json_output['section'][$cnt]['abstract']   = $this->RemoveIllegalCharacters($row->abstract);
                    $json_output['section'][$cnt]['article_type_name']    = $row->article_type_name;
                    $json_output['section'][$cnt]['volume_name']     = $row->volume_name;
                    $json_output['section'][$cnt]['issue'] = $row->issue;
                    $json_output['section'][$cnt]['authors'] = $AuthorNames;

                    $cnt++;
                }

                if ($request->format == 'xml') {

                    $xml = json2xml(json_encode($json_output));
                    $xml = str_replace('&lt;![CDATA[','<![CDATA[',$xml);
                    $xml = str_replace(']]&gt;',']]>',$xml);
                    return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                    //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

                } 
                else 
                {

                    return response()->json($json_output, 200);
                }
            } 
            else 
            {
                $json_output['error'] = 'No record Found';
                return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
            }
        }

    }

    /*
     * Date: 28-09-2022
     * Author: Imran Khan
     * Parameter: 
     * Description:  this function will get data from JMS and store into database
     */
    public function ImportJMSContent(Request $request)
    {

        $data = json_decode(file_get_contents('php://input'), true);
        //$jsonData = json_decode($data);
		$jsonData = (object) $data['manuscript'];
		
        if($jsonData)
            {
                if(isset($jsonData->ms_id))
                {
                    $ms_id = $jsonData->ms_id;
                    $jms_ref_no = $jsonData->reference_number;
                    $journal_code = $jsonData->journal_code;
                    $art_type = $jsonData->article_type;
                    $is_epub = $jsonData->is_epub;
                    $add_content = array();

                    $data['jms_ref_no'] = $jms_ref_no;
                    $data['is_epub'] = $is_epub;
                    $jms_article = JMSContent::GetJMSContentByRef($data);

                    if($jms_article)
                    {
                        $message = "Manuscript Already Exist";
                        return $message;
                    }
                    else
                    {
                    $add_content = array(
                        'journal_code'  => $journal_code,
                        'ms_id'         => $ms_id,
                        'jms_ref_no'    => $jms_ref_no,
                        'art_type'      => $art_type,
                        'content'       => json_encode($data),
                        'is_epub'       => $is_epub,
                            'datetime'      => time()
                    );

                        JMSContent::AddJMSContent($add_content);
                        $message = "Manuscript Add Successfully";
                        return $message;
                    }

                }
        }
    }

    /*
     * Date: 28-11-2022
     * Author: Imran Khan
     * Parameter:journal_code, volume, issue
     * Description:  Getting journal issue
     */

    public function services_issue_detail(Request $request)
    {   
        $param = array();
        $param['jcode'] = $request->jcode;
        $param['volume'] = $request->volume;
        $param['issue'] = $request->issue;

			$issue = Issue::GetIssueDetail($param);

			if($issue)
			{
				if($issue->is_uploaded == 1)
				{
					if($issue->type == 0)
					{
						$status = 'Issue live';
					}
					else if($issue->type == 1)
					{
						$status = 'Issue live and thematic issue';
					}
					else if($issue->type == 2)
					{
						$status = 'Issue live and in-process';
					}
				}
				else if($issue->is_uploaded == 0)
				{
					if($issue->type == 1)
					{
						$status = 'Issue not live and thematic issue';
					}
					else if($issue->type == 2)
					{
						$status = 'Issue not live and in-process';
					}
					else
					{
						$status = 'Issue not live';
					}
				}

				$json_output['issue_detail'] = array(
					'journal_title'    => $issue->journal_title,
					'journal_subtitle' => $issue->subtitle,
					'issn'             => $issue->issn,
					'eissn'            => $issue->eissn,
					'volume'           => $issue->volume_name,
					'issue'            => $issue->issue_title,
					'is_uploaded'      => $issue->is_uploaded,
					'type'             => $issue->type,
					'message'          => $status
				);
				return response()->json($json_output, 200);
			}
			else 
			{
				$json_output['error'] = 'No record Found';
				return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
			}

    }
	
	 /*
     * Date: 19-06-2023
     * Author: Muhammad Arshad
     * Parameter: Journal code/volume number/issue number
     * Description:  this function will return the issue detail ith article list
     */

     public function services_issue_toc_alert(Request $request)
     {
 
        $param = array();
        $param['jcode'] = $request->jcode;
        $param['volume'] = $request->volume;
        $param['issue'] = $request->issue;

        $hcdate_year = date('Y');
        $hcdate_month = date('m');
        $hcdate_day = date('d');

        $check = DB::table('webservice_report_counter')->selectRaw('count(*) as htotal');
        $check = $check->whereRaw('to_days(from_unixtime(created_on)) = to_days(CURDATE())');        
        $check = $check->where('user_id', '=', 5);
        $hc_row = $check->get()->toArray()[0];
        
        if ($hc_row->htotal >= 12) {

            $json_output['error'] = 'Limit Exceeded';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

        $issue = Issue::GetIssueDetail($param);
        $issue_id = $issue->issue_id;
        //dd($issue);
        if($issue)
        {
            if($issue->is_uploaded == 1)
            {
                if($issue->type == 0)
                {
                    $status = 'Issue live';
                }
                else if($issue->type == 1)
                {
                    $status = 'Issue live and thematic issue';
                }
                else if($issue->type == 2)
                {
                    $status = 'Issue live and in-process';
                }
            }
            else if($issue->is_uploaded == 0)
            {
                if($issue->type == 1)
                {
                    $status = 'Issue not live and thematic issue';
                }
                else if($issue->type == 2)
                {
                    $status = 'Issue not live and in-process';
                }
                else
                {
                    $status = 'Issue not live';
                }
            }

            $json_output['issue_detail'] = array(
                'journal_title'    => $issue->journal_title,
                'journal_subtitle' => $issue->subtitle,
                'issn'             => $issue->issn,
                'eissn'            => $issue->eissn,
                'volume'           => $issue->volume_name,
                'issue'            => $issue->issue_title,
                'is_uploaded'      => $issue->is_uploaded,
                'type'             => $issue->type,
                'message'          => $status,
                'issue_url'        => 'https://www.eurekaselect.com/issue/' . $issue_id
            );
        }
         $journal_details = Issue::GetIssue(array('issue_id' => $issue_id));
 
         if (!empty($journal_details) && !empty($journal_details->all())) {
 
             $journal_details = $journal_details[0];
             $journal_id = $journal_details->journal_id;
             $volume_id  = $journal_details->volume_id;
             $issue_id   = $journal_details->issue_id;
             
             
             $articlesArray = Article::getAllArticlesByIssueID($issue_id);
             //rint_r($articlesArray);die;
             $cnt          = 0;
             $data_article = '';
             foreach ($articlesArray as $row) {
                 $subscribed = false; 
                 
                 $article_title                                          = html_entity_decode($row->title, ENT_QUOTES, 'UTF-8'); //iconv("UTF-8", "UTF-8//IGNORE", $row->title);
                 $json_output['article'][$cnt]['article_title']          = $this->RemoveIllegalCharacters($article_title);
                 
 
				 $where['article_id'] = $row->article_id;
                 $join['author_affiliation'] = 'LEFT';
                 
                  $volume_authors = Author::GetAuthors($where, $join);

                 if ($volume_authors) {
                    $jcnt=0;
                     foreach ($volume_authors as $author) {
                          
                        $json_output['article'][$cnt]['authors'][$jcnt]['first_name'] = $author->first_name;
                        $json_output['article'][$cnt]['authors'][$jcnt]['last_name'] = $author->last_name;
                        $json_output['article'][$cnt]['authors'][$jcnt]['email'] = $author->email;
                        $json_output['article'][$cnt]['authors'][$jcnt]['affiliation'] = $author->institution;
                        $json_output['article'][$cnt]['authors'][$jcnt]['city'] = $author->city;
                        $json_output['article'][$cnt]['authors'][$jcnt]['country'] = $author->country;

                        $jcnt++;
                     }
                        
				 }
                 $cnt++;
             }
 
            $user_details['user_id'] = 5;
            $user_details['report_type'] = "services_issue_toc_alert";
            $user_details['ip_address'] = $request->ip();           
            $user_details['created_on'] = time();
            $user_details['status'] = 1;
 
             if ($request->format == 'xml') {
                $user_details['report_format'] = "XML";    
                DB::table('webservice_report_counter')->insert($user_details);

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[', '<![CDATA[', $xml);
                $xml = str_replace(']]&gt;', ']]>', $xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

                //return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');

            } else {
                $user_details['report_format'] = "JSON";
                DB::table('webservice_report_counter')->insert($user_details);

                return response()->json($json_output, 200);
            }

        } else {
            $json_output['error'] = 'No record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }

    }

    /*
     * Date: 17-08-2023
     * Author: Muhammad Zubair
     * Parameter: journal_id
     * Description:  This function will return the indexing agency of journal and details of journal
     */
    public function GetIndexingAgency(Request $request)
    {
        $journal_id = $request->journal_id;
		
		$journal = Journal::GetJournalById($journal_id);

        if (!empty($journal)) {

        $json_output['journal_details']['aims_and_scope']       = $journal->aims_and_scope;
        $json_output['journal_details']['ranking_and_category'] = $journal->ranking_and_category;
		$json_output['journal_details']['ScopusCiteScore'] 		= $journal->ScopusCiteScore;
		$json_output['journal_details']['issn_print'] 			= $journal->issn;
		$json_output['journal_details']['issn_online']			= $journal->eissn;

        }

        $indexing_list = Indexing::GetIndexingTitlebyJournalId($journal_id);

        if (!empty($indexing_list)) {

            $json_output['indexing_agency']['title'] = $indexing_list->indexing_title;

            if ($request->format == 'xml') {

                $xml = json2xml(json_encode($json_output));
                $xml = str_replace('&lt;![CDATA[', '<![CDATA[', $xml);
                $xml = str_replace(']]&gt;', ']]>', $xml);
                return Response::make($xml, '200')->header('Content-Type', 'text/xml');

            } else {
                return response()->json($json_output, 200);
            }

        } else {
            $json_output['error'] = 'No record Found';
            return Response::make(json2xml(json_encode($json_output)), '200')->header('Content-Type', 'text/xml');
        }
	}

}
