<?php

namespace App\Http\Controllers;

use App\Http\Controllers\PaypalExpress;
use App\Http\Controllers\MigsController;
use App\Http\Controllers\UserController;
use App\Models\Article;
use App\Models\Author;
use App\Models\MultiLangAuthor;
use App\Models\BundleOffer;
use App\Models\ContentAccess;
use App\Models\Country;
use App\Models\Download;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Issue;
use App\Models\Journal;
use App\Models\Keywords;
use App\Models\Log;
use App\Models\MarkList;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Subject;
use App\Models\Shareable;
use App\Models\UserAccess\UserAccess;
use App\Models\Volume;
use App\Models\Discipline;
use App\Models\MultiLanguage;
use App\Models\MultiLangArticle;
use App\Models\MultiLanguageKeywords;
use App\Models\MultiLangAuthorAffiliation;
use App\Rules\Captcha;
use App\User;
use Auth;
use Cookie;
use DB;
use File;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;

class ArticleController extends BenthamController
{

    public function index(Request $request)
    {
        $editPermission   = false;
        $deletePermission = false;
        $volume_search    = array();
        $issue_search     = array();

        $param['journal_id']   = $journal_id   = $request->get('journal_id');
        $param['volume_id']    = $volume_id    = $request->get('volume_id');
        $param['issue_id']     = $issue_id     = $request->get('issue_id');
        $param['title_search'] = $title_search = $request->get('title_search');
        $param['doi_search']    = $doi_search = $request->get('doi_search');
        $param['article_type'] = $article_type = $request->get('article_type');

        // Get Volume , issue from ajax call
        $frm_search = $request->get('frm_search');
        $ajx_search = $request->get('ajx_search');
        $module     = $request->get('module');

        ///------------------------------------------------------///
        // ------------Get Volume , Issue from ajax call---------///
        ///------------------------------------------------------///
        if ($ajx_search != null && $ajx_search == true) {
            if ($module == 'volume') {
                if (!empty($journal_id)) {
                    $p['journal_id'] = $journal_id;
                    $volume_search   = Volume::GetVolumeTitleById($p);
                    return response()->json(array('volume_search' => $volume_search), 200);
                }
            }
            if ($module == 'issue') {
                if (!empty($volume_id)) {
                    $p['volume_id'] = $volume_id;
                    $issue_search   = Issue::GetIssueTitleById($p);
                    return response()->json(array('issue_search' => $issue_search), 200);
                }
            }
        } else {

            if ($frm_search != null && $frm_search == true) {
                $article_list = Article::GetArticleList($param);
                if (!empty($journal_id)) {
                    $p['journal_id'] = $journal_id;
                    $volume_search   = Volume::GetVolumeTitleById($p);
                }
                if (!empty($volume_id)) {
                    $p['volume_id'] = $volume_id;
                    $issue_search   = Issue::GetIssueTitleById($p);
                }
            }

            if ($frm_search == null && $ajx_search == null) {
                $volume_search = array();
                $year_search   = array();
                $article_list  = array();
            }

            $journal_search = Journal::GetJournalTitle();

            if (checkPermission('article', 'edit')) {
                $editPermission = true;
            }
            if (checkPermission('article', 'delete')) {
                $deletePermission = true;
            }
            // dd($article_list);
            return View::make('admin.article.article', with(['article_list' => $article_list, 'volume_search' => $volume_search, 'journal_search' => $journal_search, 'issue_search' => $issue_search, 'param' => $param, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission]));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function add()
    {
        $journal = Journal::GetJournalTitle();
        return View::make('admin.article.article_form')->with(['journal' => $journal]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id, Request $request)
    {
        $ajx_search    = $request->get('ajx_search');
        $article_exist = $request->get('article_exist');

        if ($ajx_search == true && $article_exist == true) {
            $journal_id = $request->get('journal_id');
            $volume_id  = $request->get('volume_id');
            $issue_id   = $request->get('issue_id');
            $article_no = $request->get('article_no');

            $article = Article::where('journal_id', $journal_id)
                ->where('volume_id', $volume_id)
                ->where('issue_id', $issue_id)
                ->where('article_no', $article_no)->first();

            // $volume_name = isset($ebook_volume->volume_name) ? $ebook_volume->volume_name : null;
            return response()->json(array('article' => $article), 200);
        } else {
            $journal_id = $request->get('journal_id');

            if (!empty($journal_id)) {
                $param_j['journal_id'] = $journal_id;
                $volume                = Volume::GetVolumeTitleById($param_j);

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

            $volume_id = $request->get('volume_id');

            if (!empty($volume_id)) {
                $param['volume_id'] = $volume_id;
                $issues             = Issue::GetIssueTitleById($param);
                return response()->json(array('issue_search' => $issues), 200);
            }

            $article_type    = Article::GetArticleTypeList();
            $journal         = Journal::GetJournalTitle();
            $country         = Country::GetCountryList();
            $selected_author = "";
        }
        return View::make('admin.article.article_form')->with(['journal' => $journal, 'article_type' => $article_type, 'country' => $country, 'selected_author' => $selected_author]);
    }

    public function update(Request $request, $article_id)
    {
        if (isset($request->update_article_form)) {
            $result = $this->UpdateArticle($request, $article_id);
        }
        if (isset($request->upload_files)) {
            $result = $this->UploadFiles($request, $article_id);
        }
        if (isset($request->submit_meta)) {
            $result = $this->SubmitMeta($request, $article_id);
        }
        if (isset($request->submit_references)) {
            $result = $this->SubmitReferences($request, $article_id);
        }
        if (isset($request->submit_multi_language)) {
            $result = $this->submitMultiLanuage($request, $article_id);
        }

        if ($result[0] == false) {
            $validator = $result[1];
            return back()->withInput()->withErrors($validator);
        } else {
            $article_id = $result[1];
            return Redirect::to('admin/articles/' . $article_id . '/edit');
        }
    }

    public function UpdateArticle($request, $article_id)
    {   
        $animated_abs_file_path = "";
        $validator              = Validator::make(
            $request->all(),
            [
                'article_no'   => 'required',
                'title'        => 'required',
                'article_type' => 'required',
                'file_name'    => 'mimes:pdf',
                'first_page'   => 'required',
                'last_page'    => 'required',
                'page_count'   => 'required',
                'doi'          => 'unique:article,doi,' . $article_id . ',article_id',
                'elocator'     => 'unique:article,elocator,' . $article_id . ',article_id',
            ]
        );

        if ($validator->fails()) {

            return array(false, $validator);
        } else {
            // try transaction start here for data integrity
            try {
                DB::beginTransaction();
                $log_article  = array();
                $log_authors  = array();
                $log_keywords = array();
                $log_meta     = array();

                $selected_article = Article::GetArticleById($article_id);
                $issue_id         = 0;
                $is_epub          = $request->is_epub;
                /*   if ($selected_article->issue_id > 0) {
                $issue_id = $selected_article->issue_id;
                } else {*/
                if (isset($request->issue_id)) {
                    $issue_id = $request->issue_id;
                }
/*                }
 */
                $journal_id = $request->journal_id;
                $volume_id     = $request->volume_id;

                if ($is_epub == 0) {
                    $file_path = Article::getArticlePath($issue_id, $journal_id);
                } else {
                    $file_path = Article::getArticlePath(0, $journal_id);
                    if ($is_epub == 1) {
                        $file_path .= 'EPUB/';
                        $issue_id  = 0;
                        $epub_type = "epub-article";
                    } else if ($is_epub == 2) {
                        $file_path .= 'QUICKTRACK/';
                        //$node['vol'] = 0;
                        $issue_id  = 0;
                        $epub_type = 0;
                    } else if ($is_epub == 3) {
                        $file_path .= 'EXPRESSTRACK/';
                        //$node['vol'] = 0;
                        $issue_id  = 0;
                        $epub_type = 0;
                    } else if ($is_epub == 5) {
                        $file_path .= 'SUPPLEMENTARY/';
                        $epub_type = 0;
                    }

                    $issue_id = 0;
                }
                // $selected_article = Article::GetArticleById($article_id);

                // Add Keywords
                $keywords_input = $request->get("keyword");
                //-------------------Insert into Keywords table---------------
                if ($keywords_input != "") {
                    Keywords::DeleteKeywords($article_id, 'article_id');
                    $keywordsArray = explode(",", $keywords_input);
                    if (!empty($keywordsArray)) {

                        for ($a = 0; $a < count($keywordsArray); $a++) {
                            $add_keywords[] = array(
                                'keyword' => $keywordsArray[$a],
                                'article_id'                      => $article_id,
                            );
                            $log_keywords['article_keywords'][$a] = $add_keywords;
                        }
                    }
                    Keywords::AddKeywords($add_keywords);
                } else {
                    Keywords::DeleteKeywords($article_id, 'article_id');
                }

                $arr = explode("/", $request->get("doi")); //if doi is entered

                if (trim($arr[0]) != "10.2174" || $request->get("doi") == "") {
                    //checking if publisher code is correct

                    $doi = Article::GetArticleDOI($journal_id, $volume_id, $issue_id, $request->get("article_no"), $is_epub);
                } else {

                    $doi = $request->get("doi");
                }

                if (empty($request->get("elocator")) || $request->get("elocator") == "") {
                    $elocator = 'e'.date('dmy').$selected_article->nid;
                } else {
                    $elocator = $request->get("elocator");
                }


                //$abstract = htmlentities($request->get("abstract"));
                $abstract = htmlspecialchars($request->input('abstract'), ENT_QUOTES); 
                $abstract = str_replace("'", "''", $abstract);

                $user                     = Auth::user();
                $update_obj['jms_ref_no'] = $request->get("jms_ref_no");
                $update_obj['title']      = $request->get("title");
                $update_obj['article_no'] = $request->get("article_no");
                $update_obj['art_type']   = $request->get("article_type");
                $update_obj['doi']        = $doi;
                $update_obj['elocator']   = $elocator;
                $update_obj['citation']   = $request->get("citation");

                $update_obj['is_epub']   = isset($is_epub) ? $is_epub : '';
                $update_obj['epub_type'] = isset($epub_type) ? $epub_type : '';

                //if(empty($selected_article->publish_on) || $selected_article->publish_on = 0)
                if(isset($selected_article->is_epub) || $selected_article->is_epub == 4)
                {
                    if(isset($request->publish_on))
                    {
                        $update_obj['publish_on'] = strtotime($request->publish_on);
                    }
                }

                if ($is_epub == 0) {
                    $update_obj['epub_normal_date'] = time();
                }
                if ($is_epub == 4) {
                    $update_obj['epub_abstract_date'] = time();
                }
                if ($is_epub == 1) {
                    $update_obj['epub_full_text_date'] = time();
                }
                if ($is_epub == 2) {
                    $update_obj['epub_qucik_track_date'] = time();
                }
                if ($is_epub == 3) {
                    $update_obj['epub_express_track_date'] = time();
                }
                if ($is_epub == 5) {
                    $update_obj['epub_supp_date'] = time();
                }

                $update_obj['journal_id']        = $journal_id;
                $update_obj['volume_id']         = $volume_id;
                $update_obj['issue_id']          = $issue_id;
                $update_obj['abstract']          = $abstract;
                $update_obj['animated_abstract'] = $request->get("animated_abstract");
                $update_obj['podcast']           = $request->get("podcast");
                $update_obj['erratum_in']        = $request->get("erratum_in");
                $update_obj['erratum_for']       = $request->get("erratum_for");
                $update_obj['altmetric_score']   = $request->get("altmetric_score");
                $update_obj['altmetric_url']     = $request->get("altmetric_url");
                $update_obj['kudos_url']         = $request->get("kudos_url");
                $update_obj['receivedate']       = $request->get("Received_date");
                $update_obj['revisedate']        = $request->get("Revised_date");
                $update_obj['acceptdate']        = $request->get("Accepted_date");
                $update_obj['pmid']              = $request->get("pm_id");
                $update_obj['file_path']         = $file_path;
                $update_obj['first_page']        = $request->get("first_page");
                $update_obj['last_page']         = $request->get("last_page");
                $update_obj['page_count']        = $request->get("page_count");
                $update_obj['is_uploaded']       = $request->get("is_uploaded");
                $update_obj['is_editor_choice']  = $request->get("is_editor_choice");
                $update_obj['is_popular']        = $request->get("is_popular");
                $update_obj['is_highlighted']    = $request->get("is_highlighted");
                $update_obj['crossmark_enabled'] = $request->get("crossmark_enabled");
                $update_obj['text_mining_urls']  = $request->get("text_mining_urls");
                $update_obj['license_urls']      = $request->get("license_urls");
                $update_obj['last_modified']     = time();
                $update_obj['updated_by']        = $user->id;
                Article::where('article_id', $article_id)->update($update_obj);

                //-----------------------------Insert into log table-----------------------------------

                $article     = Article::GetArticleById($article_id);
                $log_article = (array) $article;
                $meta        = Meta::NodeMeta($article->nid);
                $log_meta    = (array) $meta;
                $log         = array_merge($log_article, $log_keywords);
                $add_log     = array(
                    'content_id'      => $article_id,
                    'content_type_id' => config('constants.log_content_types.Article'),
                    'action'          => config('constants.log_action_types.update'),
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {
                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return redirect()->back()->withInput()->withErrors($validator);
            }

            //return redirect()->route('article.index')->with('Success', 'Article has been updated.');

            return array(true, $article_id);
        }
    }

    public function UploadFiles($request, $article_id)
    {

        $req = array();

        if (isset($request->file_name)) {
            $req['file_name'] = 'required|mimes:pdf';
        }
        if (isset($request->supplementary_file)) {
            $req['supplementary_file'] = 'mimes:rar,zip';
        }
        if (isset($request->sample_file_name)) {
            $req['sample_file_name'] = 'mimes:pdf';
        }
        if (isset($request->epub_file_name)) {
            $req['epub_file_name'] = 'mimes:epub';
        }
        if (isset($request->prc_file_name)) {
            //$req['prc_file_name'] = 'mimes:mobipocket';
        }
        if (isset($request->mobi_file_name)) {
            $req['mobi_file_name'] = Rule::exist('article')->where(function ($query) {
                return $query->where('prc_filename', '<>', '');
            });
        }
        if (isset($request->html_file)) {
            $req['html_file'] = 'mimes:html';
        }
        if (isset($request->graph_abs_lg_filename)) {
            $req['graph_abs_lg_filename'] = 'mimes:jpeg,jpeg,bmp,png';
        }
        if (isset($request->graph_abs_sm_filename)) {
            $req['graph_abs_sm_filename'] = 'mimes:jpeg,jpeg,bmp,png';
        }
        if (isset($request->oa_image_lg_filename)) {
            $req['oa_image_lg_filename'] = 'mimes:jpeg,jpeg,bmp,png';
        }
        if (isset($request->oa_image_sm_filename)) {
            $req['oa_image_sm_filename'] = 'mimes:jpeg,jpeg,bmp,png';
        }

        $validator = Validator::make($request->all(), $req);

        if ($validator->fails()) {

            return array(false, $validator);
        } else {
            $article = Article::GetArticleById($article_id);

            if ($article->is_epub == 0) {
                $path = Article::getArticlePath($article->issue_id, $article->journal_id);
            } else {
                $path = Article::getArticlePath(0, $article->journal_id);
                if ($article->is_epub == 1) {
                    $path .= 'EPUB/';
                    $issue_id  = 0;
                    $epub_type = "epub-article";
                } else if ($article->is_epub == 2) {
                    $path .= 'QUICKTRACK/';
                    //$node['vol'] = 0;
                    $issue_id  = 0;
                    $epub_type = 0;
                } else if ($article->is_epub == 3) {
                    $path .= 'EXPRESSTRACK/';
                    //$node['vol'] = 0;
                    $issue_id  = 0;
                    $epub_type = 0;
                } else if ($article->is_epub == 5) {
                    $path .= 'SUPPLEMENTARY/';
                    $epub_type = 0;
                }

                $issue_id = 0;
            }

            //----------------------Upload Article files-------------------------------
            $article_file_name       = '';
            $supplementary_file_name = '';
            $html_file_name          = '';
            $epub_file_name          = '';
            $prc_file_name           = '';
            $mobi_file_name          = '';
            $graph_abs_lg_file_name  = '';
            $graph_abs_lg_file_name  = '';

            $file_path = config('constants.admin.root_path') . $path;
            //dd($file_path);

            if ($request->hasFile('file_name')) {
                $file_name         = $request->file('file_name');
                $article_file_name = $file_name->getClientOriginalName();

                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }
                $file_name->move($file_path, $article_file_name);
                $upload_article_files['file_name'] = $article_file_name;
            }
            //----------------------Upload supplementar files-------------------------------
            if ($request->hasFile('supplementary_file')) {
                $supplementary_file      = $request->file('supplementary_file');
                $supplementary_file_name = $supplementary_file->getClientOriginalName();
                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }

                $supplementary_file->move($file_path, $supplementary_file_name);
                $upload_article_files['supplementary_filename'] = $supplementary_file_name;
            }
            //----------------------Upload html files-------------------------------
            if ($request->hasFile('html_file')) {
                $html_file      = $request->file('html_file');
                $html_file_name = $html_file->getClientOriginalName();
                if (!is_dir($file_path . 'html')) {
                    mkdir($file_path . 'html', 0755, true);
                }
                $html_file->move($file_path . 'html', $html_file_name);
                $upload_article_files['html_filename'] = $html_file_name;
            }
            //----------------------Upload epub files-------------------------------
            if ($request->hasFile('epub_file')) {
                $epub_file      = $request->file('epub_file');
                $epub_file_name = $epub_file->getClientOriginalName();
                if (!is_dir($file_path . 'epub')) {
                    mkdir($file_path . 'epub', 0755, true);
                }
                $epub_file->move($file_path . 'epub', $epub_file_name);
                $upload_article_files['epub_filename'] = $epub_file_name;
            }
            //----------------------Upload prc files-------------------------------
            if ($request->hasFile('prc_file')) {
                $prc_file      = $request->file('prc_file');
                $prc_file_name = $prc_file->getClientOriginalName();
                if (!is_dir($file_path . 'prc')) {
                    mkdir($file_path . 'prc', 0755, true);
                }
                $prc_file->move($file_path . 'prc', $prc_file_name);
                $upload_article_files['prc_filename'] = $prc_file_name;
            }
            //----------------------Upload mobi files-------------------------------
            if ($request->hasFile('mobi_file')) {
                $mobi_file      = $request->file('mobi_file');
                $mobi_file_name = $mobi_file->getClientOriginalName();
                if (!is_dir($file_path . 'prc')) {
                    mkdir($file_path . 'prc', 0755, true);
                }
                $mobi_file->move($file_path . 'prc', $mobi_file_name);
                //$upload_article_files['prc_filename'] = $mobi_file_name;
            }
            //----------------------Upload Graphical Abstract Large files-------------------------------

            $article_detail      = Article::GetArticleDetail($article_id);
            $graph_abs_file_path = public_path() . '/images/graphical-abstract/' . strtolower($article_detail->jour_subtitle) . '/' . $article_detail->volume . '/' . $article_detail->issue . '/';

            if ($request->hasFile('graph_abs_lg_filename')) {
                $graph_abs_lg           = $request->file('graph_abs_lg_filename');
                $graph_abs_lg_file_name = $graph_abs_lg->getClientOriginalName();
                if (!is_dir($graph_abs_file_path)) {
                    mkdir($graph_abs_file_path, 0755, true);
                }
                $graph_abs_lg->move($graph_abs_file_path, $graph_abs_lg_file_name);
                $upload_article_files['graph_abs_lg_filename'] = $graph_abs_lg_file_name;
            }
            //----------------------Upload Graphical Abstract Small files-------------------------------
            if ($request->hasFile('graph_abs_sm_filename')) {
                $graph_abs_sm           = $request->file('graph_abs_sm_filename');
                $graph_abs_sm_file_name = $graph_abs_sm->getClientOriginalName();
                if (!is_dir($graph_abs_file_path)) {
                    mkdir($graph_abs_file_path, 0755, true);
                }
                $graph_abs_sm->move($graph_abs_file_path, $graph_abs_sm_file_name);
                $upload_article_files['graph_abs_sm_filename'] = $graph_abs_sm_file_name;
            }
            //----------------------Upload OA Image Abstract Large files-------------------------------
           
            $article_detail      = Article::GetArticleDetail($article_id);
            $oa_image_file_path = public_path() . '/images/oa_image/' . strtolower($article_detail->jour_subtitle) . '/' . $article_detail->volume . '/' . $article_detail->issue . '/';

            if ($request->hasFile('oa_image_lg_filename')) {
                $oa_image_lg           = $request->file('oa_image_lg_filename');
                $oa_image_lg_filename = $oa_image_lg->getClientOriginalName();
                if (!is_dir($oa_image_file_path)) {
                    mkdir($oa_image_file_path, 0755, true);
                }
                $oa_image_lg->move($oa_image_file_path, $oa_image_lg_filename);
                $upload_article_files['oa_image_lg_filename'] = $oa_image_lg_filename;
            }

            //----------------------Upload OA Image Abstract Small files-------------------------------
           
            $article_detail      = Article::GetArticleDetail($article_id);
            $oa_image_file_path = public_path() . '/images/oa_image/' . strtolower($article_detail->jour_subtitle) . '/' . $article_detail->volume . '/' . $article_detail->issue . '/';

            if ($request->hasFile('oa_image_sm_filename')) {
                $oa_image_sm           = $request->file('oa_image_sm_filename');
                $oa_image_sm_filename = $oa_image_sm->getClientOriginalName();
                if (!is_dir($oa_image_file_path)) {
                    mkdir($oa_image_file_path, 0755, true);
                }
                $oa_image_sm->move($oa_image_file_path, $oa_image_sm_filename);
                $upload_article_files['oa_image_sm_filename'] = $oa_image_sm_filename;
            }

            $user = Auth::user();
            if ($article->file_name == '') {
                $upload_article_files['created']       = time();
                $upload_article_files['created_by']    = $user->id;
                $upload_article_files['last_modified'] = time();
            } else {
                $upload_article_files['updated_by']    = $user->id;
                $upload_article_files['last_modified'] = time();
                $upload_article_files['file_path']     = $path;
            }
            Article::where('article_id', $article_id)->update($upload_article_files);
            return array(true, $article_id);
        }
    }

    public function SubmitMeta($request, $article_id)
    {
        //-------------------Insert into Node Meta table---------------
        $article = Article::GetArticleById($article_id);
        Meta::DeleteMeta($article->nid);
        $add_node_meta = array('nid' => $article->nid,
            'title'                      => $request->get('title'),
            'abstract'                   => $request->get('meta_abstract'),
            'canonical_url'              => $request->get('meta_canonical_url'),
            'copyright'                  => $request->get('meta_copyright'),
            'description'                => $request->get('meta_description'),
            'keywords'                   => $request->get('meta_keywords')
        );

        $node_meta = Meta::AddNodeMeta($add_node_meta);
        //----------------------------------------------------------------

        return array(true, $article_id);
    }

    public function SubmitReferences($request, $article_id)
    {
        //-------------------Insert into Article Citation table---------------
        $article = Article::GetArticleById($article_id);
        Article::DeleteReferences($article_id);

        $ref = array();

        foreach ($request->cite_for as $key => $value) {
            if ($key == "crossref" && !empty($value)) {
                $ref[] = array(
                    'article_id' => $article_id,
                    'cite_for'                  => "open_references_crossref",
                    'citation_data'             => $value
                );
            }

            if ($key == "pubmed" && !empty($value)) {
                $ref[] = array(
                    'article_id' => $article_id,
                    'cite_for'                  => "open_references_pubmed",
                    'citation_data'             => $value
                );
            }

            if ($key == "pmc" && !empty($value)) {
                $ref[] = array(
                    'article_id' => $article_id,
                    'cite_for'                  => "open_references_pmc",
                    'citation_data'             => $value
                );
            }

            if ($key == "html" && !empty($value)) {
                $ref[] = array(
                    'article_id' => $article_id,
                    'cite_for'                  => "open_references_html",
                    'citation_data'             => $value
                );
            }
        }

        Article::AddReferences($ref);

        return array(true, $article_id);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {

        $ajax   = $request->get('ajax');
        $action = $request->get('action');
        $method = $request->get('method');

        if ($ajax == true) {

            if ($method == 'author') {
                if ($action == 'SELECT') {
                    return $this->ajax_SELECT($request);
                } else if ($action == 'INSERT') {
                    return $this->ajax_INSERT($request);
                } else if ($action == 'DELETE') {
                    return $this->ajax_DELETE($request);
                } else if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE($request);
                }
            } else if ($method == 'abstract_details') {
                if ($action == 'SELECT') {
                    return $this->ajax_SELECT_Abstrct_Details($request);
                } else if ($action == 'INSERT') {
                    return $this->ajax_INSERT_Abstrct_Details($request);
                } else if ($action == 'DELETE') {
                    return $this->ajax_DELETE_Abstrct_Details($request);
                } else if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE_Abstrct_Details($request);
                }
            } else if ($method == 'funder_details') {

                if ($action == 'SELECT') {
                    return $this->ajax_SELECT_Funder_Details($request);
                } else if ($action == 'INSERT') {
                    return $this->ajax_INSERT_Funder_Details($request);
                } else if ($action == 'DELETE') {
                    return $this->ajax_DELETE_Funder_Details($request);
                } else if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE_Funder_Details($request);
                }
            } else if ($method == 'Affiliation') {

                if ($action == 'SELECT') {
                    return $this->ajax_SELECT_Author_Affiliation($request);
                } else if ($action == 'INSERT') {
                    return $this->ajax_INSERT_Author_Affiliation($request);
                } else if ($action == 'DELETE') {
                    return $this->ajax_DELETE_Author_Affiliation($request);
                } else if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE_Author_Affiliation($request);
                }
            }
        } else {
            if (isset($request->submit_article_form)) {
                $result = $this->InsertArticle($request);

                if ($result[0] == false) {
                    $validator     = $result[1];
                    $volume_search = $result['volume_search'];
                    $issue_search  = $result['issue_search'];
                    return back()->with(['volume_search' => $volume_search, 'issue_search' => $issue_search])->withInput()->withErrors($validator);
                } else {
                    $article_id = $result[1];
                    return Redirect::to('admin/articles/' . $article_id . '/edit');
                }
            }
        }
    }

    public function edit(Request $request, $id)
    {
        $user = Auth::user()->id;

        $ajx_search    = $request->get('ajx_search');
        $article_exist = $request->get('article_exist');

        if ($ajx_search === true && $article_exist === true) {
            return response()->json(array('test' => $article_exist), 200);

            $param['journal_id'] = $journal_id = $request->get('journal_id');
            $param['volume_id']  = $volume_id  = $request->get('volume_id');
            $param['issue_id']   = $issue_id   = $request->get('issue_id');
            $param['article_no'] = $issue_id = $request->get('issue_id');

            $article = Article::GetArticleList($param);

            //$volume_name = isset($ebook_volume->volume_name) ? $ebook_volume->volume_name : null;
            return response()->json(array('article' => $article), 200);
        } else {

            $journal_id = $request->get('journal_id');

            if (!empty($journal_id)) {
                $param_j['journal_id'] = $journal_id;
                $volume                = Volume::GetVolumeTitleById($param_j);
                return response()->json(array('volume_search' => $volume), 200);
            }

            $volume_id = $request->get('volume_id');

            if (!empty($volume_id)) {
                $param['volume_id'] = $volume_id;
                $issues             = Issue::GetIssueTitleById($param);

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

            $article_data = $this->getArticleData($id);

            $article       = $article_data['article'];
            $journal       = $article_data['journal'];
            $volume        = "";
            $issue         = $article_data['issue'];
            $article_type  = $article_data['article_type'];
            $keyword       = $article_data['keyword'];
            $selected_meta = $article_data['meta_tags'];
            $references    = $article_data['references'];

            $refernce['open_references_html']     = "";
            $refernce['open_references_crossref'] = "";
            $refernce['open_references_pubmed']   = "";
            $refernce['open_references_pmc']      = "";

            foreach ($references as $value) {
                if ($value->cite_for == "open_references_html") {
                    $refernce['open_references_html'] = $value->citation_data;
                } else if ($value->cite_for == "open_references_crossref") {
                    $refernce['open_references_crossref'] = $value->citation_data;
                } else if ($value->cite_for == "open_references_pubmed") {
                    $refernce['open_references_pubmed'] = $value->citation_data;
                } else if ($value->cite_for == "open_references_pmc") {
                    $refernce['open_references_pmc'] = $value->citation_data;
                }
            }
            for ($i = 2000; $i <= date('Y'); $i++) {
                $year[$i] = $i;
            }

            $country                  = Country::GetCountryList();
            $selected_author          = Author::getAuthorDataById($id, 'article_id');
            $selected_abstract_detail = Article::GetArticleAbstractDetail($id, 'article_id');

            $journal = Journal::GetJournalTitle();

            $p['journal_id'] = $article->journal_id;
            $volume_search   = Volume::GetVolumeTitleById($p);

            $p['volume_id'] = $article->volume_id;
            $issue_search   = Issue::GetIssueTitleById($p);

            // get multilanguage
            $multilanguage = MultiLanguage::select('language_id', 'language_title')->where('isactive', 1)->get();
            $multilanguagearticle = MultiLangArticle::join('multilanguage', 'multilanguage.language_id', '=', 'multilanguage_article.language_id')
                ->leftjoin('multilanguage_keywords', function ($join) {
                    $join->on("multilanguage_keywords.language_id", "=", "multilanguage_article.language_id")
                        ->on("multilanguage_keywords.article_id", "=", "multilanguage_article.article_id");
                })
                ->where('multilanguage_article.article_id', $id)
                ->select('multilanguage_article.*', 'multilanguage.language_title', 'multilanguage_keywords.keyword')
                ->get();

            return View::make('admin.article.article_form', with(['user' => $user, 'article' => $article, 'issue' => $issue, 'article_type' => $article_type, 'journal' => $journal, 'volume' => $volume, 'year' => $year, 'selected_meta' => $selected_meta, 'keyword' => $keyword, 'refernce' => $refernce, 'selected_author' => $selected_author, 'selected_abstract_detail' => $selected_abstract_detail, 'country' => $country, 'volume_search' => $volume_search, 'issue_search' => $issue_search, 'multilanguage' => $multilanguage, 'multilanguagearticle' => $multilanguagearticle]));
        }
    }

    public function InsertArticle($request)
    {
        $animated_abs_file_path = "";
        $input                  = $request->all();
        $validator              = Validator::make($request->all(), [
            'journal_id'   => 'required',
            'volume_id'    => 'required',
            'article_no'   => 'required',
            'title'        => 'required',
            'article_type' => 'required',
            'first_page'   => 'required',
            'last_page'    => 'required',
            'page_count'   => 'required',
            'elocator'     => 'unique:article,elocator'
        ]);

        // process the login
        if ($validator->fails()) {
            $p['journal_id'] = $request->get("journal_id");
            $volume_search   = Volume::GetVolumeTitleById($p);

            $p['volume_id'] = $request->get("volume_id");
            $issue_search   = Issue::GetIssueTitleById($p);

            return array(false, $validator, 'volume_search' => $volume_search, 'issue_search' => $issue_search);
        } else {
            // try transaction start here for data integrity
            try {
                DB::beginTransaction();
                //---------------Log Array--------------
                $log_article  = array();
                $log_authors  = array();
                $log_keywords = array();
                $log_meta     = array();

                $user     = Auth::user();
                $add_node = array(
                    'type'     => 'article',
                    'title'    => $request->get("title"),
                    'language' => 'en',
                    'uid'      => $user->id,
                    'status'   => 1,
                    'created'  => time(),
                    'changed'  => time(),
                );
                $node_id = Node::Add($add_node);

                $is_epub    = $request->get("is_epub");
                $issue_id   = $request->get("issue_id");
                $journal_id = $request->get("journal_id");
                $volume_id  = $request->get("volume_id");

                $jobj = Journal::GetJournalById($journal_id);

                if ($jobj->journal_on == 'S1') {
                    $jms_ref_no = 0;
                }
                if ($is_epub == 0) {
                    $file_path = Article::getArticlePath($issue_id, $journal_id);
                } else {
                    $file_path = Article::getArticlePath(0, $journal_id);
                    if ($is_epub == 1) {
                        $file_path .= 'EPUB/';
                        $issue_id  = 0;
                        $epub_type = "epub-article";
                    } else if ($is_epub == 2) {
                        $file_path .= 'QUICKTRACK/';
                        //$node['vol'] = 0;
                        $issue_id  = 0;
                        $epub_type = 0;
                    } else if ($is_epub == 3) {
                        $file_path .= 'EXPRESSTRACK/';
                        //$node['vol'] = 0;
                        $issue_id  = 0;
                        $epub_type = 0;
                    } else if ($is_epub == 5) {
                        $file_path .= 'SUPPLEMENTARY/';
                        $epub_type = 0;
                    }

                    $issue_id = 0;
                }

                $arr = explode("/", $request->get("doi")); //if doi is entered

                if (trim($arr[0]) != "10.2174" || $request->get("doi") == "") {
                    //checking if publisher code is correct

                    $doi = Article::GetArticleDOI($journal_id, $volume_id, $issue_id, $request->get("article_no"), $is_epub);
                } else {

                    $doi = $request->get("doi");
                }

                if(empty($request->get("elocator")) || $request->get("elocator") == "")
                {
                    $elocator = 'e'.date('dmy').$node_id;
                }
                else
                {
                    $elocator = $request->get("elocator");
                }

                //$abstract = htmlentities($request->get("abstract"));
                $abstract = htmlspecialchars($request->input('abstract'), ENT_QUOTES); 
                $abstract = str_replace("'", "''", $abstract);

                $article_obj = new article;

                $article_obj->table      = "article";
                $article_obj->nid        = $node_id;
                $article_obj->journal_id = $journal_id;
                $article_obj->volume_id  = $volume_id;
                $article_obj->issue_id   = $issue_id;
                $article_obj->jms_ref_no = $request->get("jms_ref_no");
                $article_obj->title      = $request->get("title");
                $article_obj->article_no = $request->get("article_no");
                $article_obj->art_type   = $request->get("article_type");
                $article_obj->doi        = $doi;
                $article_obj->elocator   = $elocator;
                $article_obj->citation   = $request->get("citation");

                if($request->get("is_uploaded") == 1)
                {
                    $article_obj->publish_on = time();
                }

                $article_obj->is_epub = $is_epub;

                if ($is_epub == 0) {
                    $article_obj->epub_normal_date = time();
                }
                if ($is_epub == 4) {
                    
                    $article_obj->epub_abstract_date = time();
                }
                if ($is_epub == 1) {
                    $article_obj->epub_full_text_date = time();
                }
                if ($is_epub == 2) {
                    $article_obj->epub_qucik_track_date = time();
                }
                if ($is_epub == 3) {
                    $article_obj->epub_express_track_date = time();
                }
                if ($is_epub == 5) {
                    $article_obj->epub_supp_date = time();
                }

                $article_obj->epub_type         = isset($epub_type) ? $epub_type : 0;

                $article_obj->abstract          = $abstract;
                $article_obj->animated_abstract = $request->get("animated_abstract");
                $article_obj->podcast           = $request->get("podcast");
                $article_obj->erratum_in        = $request->get("erratum_in");
                $article_obj->erratum_for       = $request->get("erratum_for");
                $article_obj->altmetric_score   = $request->get("altmetric_score");
                $article_obj->altmetric_url     = $request->get("altmetric_url");
                $article_obj->kudos_url         = $request->get("kudos_url");
                $article_obj->receivedate       = $request->get("Received_date");
                $article_obj->revisedate        = $request->get("Revised_date");
                $article_obj->acceptdate        = $request->get("Accepted_date");
                $article_obj->pmid              = $request->get("pm_id");
                // $article_obj->file_name        = $request->get("file_name");
                $article_obj->file_path         = $file_path;
                $article_obj->first_page        = $request->get("first_page");
                $article_obj->last_page         = $request->get("last_page");
                $article_obj->page_count        = $request->get("page_count");
                $article_obj->is_uploaded       = $request->get("is_uploaded");
                $article_obj->is_editor_choice  = $request->get("is_editor_choice");
                $article_obj->is_popular        = $request->get("is_popular");
                $article_obj->is_highlighted    = $request->get("is_highlighted");
                $article_obj->crossmark_enabled = $request->get("crossmark_enabled");
                $article_obj->text_mining_urls  = $request->get("text_mining_urls");
                $article_obj->license_urls      = $request->get("license_urls");
                $article_obj->last_modified     = time();
                $article_obj->created           = time();
                $article_obj->created_by        = $user->id;
                $article_obj->updated_by        = $user->id;
                $article_obj->save();
                $article_id = $article_obj->id;

                //-------------------Insert into Keywords table---------------
                $keywords_input = $request->get("keyword");
                if ($keywords_input != "") {
                    $keywordsArray = explode(",", $keywords_input);
                    if (!empty($keywordsArray)) {

                        for ($a = 0; $a < count($keywordsArray); $a++) {
                            $add_keywords[] = array(
                                'keyword' => $keywordsArray[$a],
                                'article_id'                      => $article_id,
                            );
                            $log_keywords['article_keywords'][$a] = $add_keywords;
                        }
                        Keywords::AddKeywords($add_keywords);
                    }
                }

                //-----------------------------Insert into log table-----------------------------------

                $article = Article::GetArticleById($article_id);

                $log_article = (array) $article;
                $meta        = Meta::NodeMeta($article->nid);
                $log_meta    = (array) $meta;

                $log     = array_merge($add_node, $log_article, $log_keywords, $log_authors, $log_meta);
                $add_log = array(
                    'content_id'      => $article_id,
                    'content_type_id' => config('constants.log_content_types.Article'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return Redirect::to('admin/articles');
            }

            return array(true, $article_id);
        }
    }

    public function getArticleData($id)
    {
        $article = Article::GetArticleById($id);
        //$article = $article[0];

        $param['journal_id'] = $article->journal_id;
        $journal             = Journal::GetJournalTitle($param);
        $param['volume_id']  = $article->volume_id;
        $volume              = Volume::GetVolumeTitleById($param);

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

        $article_type = Article::GetArticleTypeList();
        $authors      = Author::getAuthorDataById($id, 'article_id');

        $keywords = Keywords::getKeywordDataById($id, 'article_id');

        $keyword = '';
        if (!empty($keywords)) {

            foreach ($keywords as $vals) {

                $keyword .= $vals->keyword . ',';
            }
            $keyword = substr($keyword, 0, -1);
        }

        $meta_tags = Meta::NodeMeta($article->nid);

        $references = Article::GetArticleReferences($id);

        $article_data['article']      = $article;
        $article_data['journal']      = $journal;
        $article_data['volume']       = $volume;
        $article_data['issue']        = $issue;
        $article_data['article_type'] = $article_type;
        $article_data['authors']      = $authors;
        $article_data['keyword']      = $keyword;
        $article_data['meta_tags']    = $meta_tags;
        $article_data['references']   = $references;

        return $article_data;
    }

    public function destroy($article_id = "", Request $request)
    {
        //---------------Log Array--------------
        $article      = array();
        $log_authors  = array();
        $log_author   = array();
        $log_keywords = array();
        $log_keyword  = array();
        $log_meta     = array();
        $log_node     = array();
        $nid          = $request->input('nid');
        $log_meta     = (array) Meta::NodeMeta($nid);
        $log_node     = (array) Node::GetNode($nid);
        $authors      = Author::getAuthorDataById($article_id, 'article_id');
        $keywords     = Keywords::getKeywordDataById($article_id, 'article_id');

        if ($authors) {
            foreach ($authors as $key => $value) {
                $log_author[] = $value;
            }
            $log_authors['author'] = $log_author;
        }

        if ($keywords) {
            foreach ($keywords as $key => $value) {
                $log_keyword[] = $value;
            }
            $log_keywords['article_keywords'] = $log_keyword;
        }

        $article = (array) Article::GetArticleById($article_id);
        try {
// try transaction start here for data integrity

            DB::beginTransaction();
            Node::DeleteNode($nid);
            Meta::DeleteMeta($nid);
            Article::RemoveArticleById($article_id);
            Author::DeleteAuthors($article_id, 'article_id');
            Keywords::DeleteKeywords($article_id, 'article_id');

            //-----------------------------Insert into log table-----------------------------------

            $log     = array_merge($log_node, $article, $log_keywords, $log_authors, $log_meta);
            $add_log = array(
                'content_id'      => $article_id,
                'content_type_id' => config('constants.log_content_types.Article'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);
            //-------------------------------------------------------------------------------------
            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return redirect()->back();
        }
        return redirect()->back()->with('success', 'Article delete successfully.');
    }

    public function insertAuthor($request, $article_id)
    {
        $sequence    = $request->input('sequence');
        $author_type = $request->input('author_type');
        $initials    = $request->input('initials');
        $orcid       = $request->input('orcid');
        $h_index     = $request->input('h_index');
        $first_name  = $request->input('first_name');
        $last_name   = $request->input('last_name');
        $email       = $request->input('email');
        $country     = $request->input('country');
        $affiliation = $request->input('affiliation');

        foreach ($sequence as $key => $vals) {
            $is_principle                   = $request->input('principle_' . $key);
            $add_author['iseditorcoeditor'] = $author_type[$key];
            $add_author['sequence']         = $sequence[$key];
            $add_author['is_principle']     = isset($is_principle) ? $is_principle : 0;
            $add_author['initials']         = $initials[$key];
            $add_author['orcid']            = $orcid[$key];
            $add_author['h_index']          = $h_index[$key];
            $add_author['first_name']       = $first_name[$key];
            $add_author['last_name']        = $last_name[$key];
            $add_author['email']            = $email[$key];
            $add_author['country']          = $country[$key];
            $add_author['article_id']       = $article_id;
            $add_author_data[]              = $add_author;
            Author::insert($add_author);
        }

        return $add_author_data;
    }

    public function ajax_SELECT($request)
    {

        $article_id = $request->get('article_id');
        if (!empty($article_id)) {
            $selected_author = Author::getAuthorDataById($article_id, 'article_id');
            return response()->json(array('selected_author' => $selected_author), 200);
        }
    }

    public function ajax_INSERT($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $add_article['first_name']       = $request->get('first_name');
            $add_article['last_name']        = $request->get('last_name');
            $add_article['initials']         = $request->get('initials');
            $add_article['country']          = $request->get('country');
            $add_article['email']            = $request->get('email');
            $add_article['orcid']            = $request->get('orcid');
            $add_article['h_index']          = $request->get('h_index') ? $request->get('h_index') : 0;
            $add_article['sequence']         = $request->get('sequence');
            $add_article['is_principle']     = $request->get('principle');
            $add_article['iseditorcoeditor'] = $request->get('author_type');
            $add_article['article_id']       = $request->get('article_id');
            $add_article['author_id']        = Author::insertGetId($add_article);

            $add_log = array(
                'content_id'      => $add_article['author_id'],
                'content_type_id' => config('constants.log_content_types.Author'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_article),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_UPDATE($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $author_id = $request->get('author_id');

            $update_author['first_name']       = $request->get('first_name');
            $update_author['last_name']        = $request->get('last_name');
            $update_author['initials']         = $request->get('initials');
            $update_author['country']          = $request->get('country');
            $update_author['email']            = $request->get('email');
            $update_author['h_index']          = $request->get('h_index') ? $request->get('h_index') : 0;
            $update_author['sequence']         = $request->get('sequence');
            $update_author['orcid']            = $request->get('orcid');
            $update_author['is_principle']     = $request->get('principle');
            $update_author['iseditorcoeditor'] = $request->get('author_type');

            Author::where('author_id', $author_id)->update($update_author);

            $author        = Author::getAuthorDataById($author_id, 'author_id');
            $author        = $author[0];
            $log['author'] = (array) $author;

            $add_log = array(
                'content_id'      => $author_id,
                'content_type_id' => config('constants.log_content_types.Author'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_DELETE($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $author_id = $request->get('author_id');

            $author        = Author::getAuthorDataById($author_id, 'author_id');
            $author        = $author[0];
            $log['author'] = $author;

            $selected_affiliation = Article::GetAuthorAffiliation($author_id, 'author_id');

            if ($selected_affiliation != null) {
                $log['affiliation'] = Article::GetAuthorAffiliation($author_id, 'author_id');
            }

            //-----------------------------Insert into log table-----------------------------------

            $add_log = array(
                'content_id'      => $author_id,
                'content_type_id' => config('constants.log_content_types.Author'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            Author::where('author_id', $author_id)->delete();

            if ($selected_affiliation != null) {
                Article::RemoveAuthorAffiliation($author_id, 'author_id');
            }

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }
        return response()->json(array('response' => true), 200);
    }
//----------------Author Affiliation--------------------
    public function ajax_SELECT_Author_Affiliation($request)
    {
        $author_id = $request->get('author_id');
        if (!empty($author_id)) {
            $selected_affiliation = Article::GetAuthorAffiliation($author_id, 'author_id');
            return response()->json(array('selected_affiliation' => $selected_affiliation), 200);
        }
    }

    public function ajax_INSERT_Author_Affiliation($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $add_affiliation['author_id']   = $request->get('author_id');
            $add_affiliation['institution'] = $request->get('institution');
            $add_affiliation['department']  = $request->get('department');
            $add_affiliation['address']     = $request->get('address');
            $add_affiliation['country']     = $request->get('country');
            $add_affiliation['city']        = $request->get('city');
            $add_affiliation['postal_code'] = $request->get('postal_code');
            $add_affiliation['phone']       = $request->get('phone');
            $add_affiliation['fax']         = $request->get('fax');
            $add_affiliation['web_view']    = addslashes(str_replace('"', "'",$request->get('web_view')));
            $add_affiliation['aff_id']      = Article::InsertAuthorAffiliation($add_affiliation);

            $add_log = array(
                'content_id'      => $add_affiliation['aff_id'],
                'content_type_id' => config('constants.log_content_types.Author_Affiliation'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_affiliation),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_UPDATE_Author_Affiliation($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $update_affiliation['aff_id']      = $request->get('aff_id');
            $update_affiliation['institution'] = $request->get('institution');
            $update_affiliation['department']  = $request->get('department');
            $update_affiliation['address']     = $request->get('address');
            $update_affiliation['country']     = $request->get('country');
            $update_affiliation['city']        = $request->get('city');
            $update_affiliation['postal_code'] = $request->get('postal_code');
            $update_affiliation['phone']       = $request->get('phone');
            $update_affiliation['fax']         = $request->get('fax');
            $update_affiliation['web_view']    = addslashes(str_replace('"', "'",$request->get('web_view')));

            Article::UpdateAuthorAffiliation($update_affiliation);

            $add_log = array(
                'content_id'      => $update_affiliation['aff_id'],
                'content_type_id' => config('constants.log_content_types.Author_Affiliation'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($update_affiliation),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_DELETE_Author_Affiliation($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $aff_id = $request->get('aff_id');

            $affiliation = Article::GetAuthorAffiliation($aff_id, 'aff_id');

            $add_log = array(
                'content_id'      => $aff_id,
                'content_type_id' => config('constants.log_content_types.Author_Affiliation'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($affiliation),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            Article::RemoveAuthorAffiliation($aff_id, 'aff_id');
            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }
        return response()->json(array('response' => true), 200);
    }

    //------------------------------------------------------------//
    public function ajax_SELECT_Abstrct_Details($request)
    {

        $article_id = $request->get('article_id');
        if (!empty($article_id)) {
            $selected_abstract_detail = Article::GetArticleAbstractDetail($article_id, 'article_id');
            return response()->json(array('selected_abstract_detail' => $selected_abstract_detail), 200);
        }
    }

    public function ajax_INSERT_Abstrct_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $add_abstract['article_id']        = $request->get('article_id');
            $add_abstract['sequence']          = $request->get('sequence');
            $add_abstract['field_name']        = $request->get('field_name');
            $add_abstract['field_description'] = $request->get('description');
            $add_abstract['abstract_id']       = Article::InsertArticleAbstractDetail($add_abstract);

            $add_log = array(
                'content_id'      => $add_abstract['abstract_id'],
                'content_type_id' => config('constants.log_content_types.Article_Abstract'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_abstract),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }
        return response()->json(array('insert' => $add_abstract), 200);
    }

    public function ajax_UPDATE_Abstrct_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $abstract_id = $request->get('abstract_id');

            $update_article['abstract_id']       = $request->get('abstract_id');
            $update_article['sequence']          = $request->get('sequence');
            $update_article['field_name']        = $request->get('field_name');
            $update_article['field_description'] = $request->get('description');

            Article::UpdateAbstractDetail($update_article);

            $add_log = array(
                'content_id'      => $abstract_id,
                'content_type_id' => config('constants.log_content_types.Article_Abstract'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($update_article),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_DELETE_Abstrct_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $abstract_id = $request->get('abstract_id');

            $abstract_detail = (array) Article::GetArticleAbstractDetail($abstract_id, 'abstract_id');

            $add_log = array(
                'content_id'      => $abstract_id,
                'content_type_id' => config('constants.log_content_types.Article_Abstract'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($abstract_detail),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);
            Article::RemoveAbstractDetail($abstract_id);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    //-----------------------Funders----------------
    public function ajax_SELECT_Funder_Details($request)
    {

        $article_id = $request->get('article_id');
        if (!empty($article_id)) {
            $selected_funder_detail = Article::GetArticleFunderDetail($article_id, 'article_id');
            return response()->json(array('selected_funder_detail' => $selected_funder_detail), 200);
        }
    }

    public function ajax_INSERT_Funder_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $add_funder['article_id']          = $request->get('article_id');
            $add_funder['funder_name']         = $request->get('funder_name');
            $add_funder['funder_registry_ids'] = $request->get('funder_registry_ids');
            $add_funder['funder_id']           = $funder_id           = Article::InsertArticleFunderDetail($add_funder);

            $award_number = explode(",", $request->get('award_number'));

            if (count($award_number) > 0) {
                Article::RemoveFunderAwards($funder_id);

                for ($a = 0; $a < sizeof($award_number); $a++) {
                    $update_awards['funder_id']    = $funder_id;
                    $update_awards['article_id']   = $request->get('article_id');
                    $update_awards['award_number'] = $award_number[$a];

                    Article::InsertFunderAwards($update_awards);
                }
            }

            $log = array_merge($add_funder, $update_awards);

            $add_log = array(
                'content_id'      => $funder_id,
                'content_type_id' => config('constants.log_content_types.Article_Funder'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            $add_funder['award_number'] = $request->get('award_number');

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_UPDATE_Funder_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $funder_id = $request->get('funder_id');

            $update_funder['article_id']          = $request->get('article_id');
            $update_funder['funder_id']           = $request->get('funder_id');
            $update_funder['funder_name']         = $request->get('funder_name');
            $update_funder['funder_registry_ids'] = $request->get('funder_registry_ids');

            $id = Article::InsertFunderDetail($update_funder);

            $award_number = explode(",", $request->get('award_number'));

            if (count($award_number) > 0) {
                Article::RemoveFunderAwards($id);

                for ($a = 0; $a < sizeof($award_number); $a++) {
                    /*
                    $update_awards[] = array('funder_id' => $request->get('funder_id'),
                    'article_id'=> $funder_detail[0]->article_id,
                    'award_number'=> ".$value.");
                     */

                    $update_awards['funder_id']    = $id;
                    $update_awards['article_id']   = $request->get('article_id');
                    $update_awards['award_number'] = $award_number[$a];

                    Article::InsertFunderAwards($update_awards);
                }
            }

            $log = array_merge($update_funder, $update_awards);

            $add_log = array(
                'content_id'      => $funder_id,
                'content_type_id' => config('constants.log_content_types.Article_Funder'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ajax_DELETE_Funder_Details($request)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $funder_id = $request->get('funder_id');

            $log = (array) Article::GetArticleFunderDetail($funder_id, 'funder_id');

            $add_log = array(
                'content_id'      => $funder_id,
                'content_type_id' => config('constants.log_content_types.Article_Funder'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($log),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            Article::RemoveFunderDetail($funder_id);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

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

    public function ViewHtml($param)
    {

        list($type, $article_id, $token) = decrypt($param);
        $contenttype                     = 'text/html';
        $article                         = Article::where('article_id', $article_id)->first();
        $file                            = config('constants.admin.root_path') . $article->file_path . 'html/' . $article->html_filename;
        if (file_exists($file)) {

            $fileInfo = pathinfo($file);
            header("Cache-Control: public");
            header('Content-Transfer-Encoding: binary');
            header("Content-Description: File Transfer");
            header("Content-Type: " . $contenttype);
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            //ob_clean();
            flush();

            // Read the file from disk
            $file_content = readfile($file);
        }
        return $file_content;
    }

    public function ReadPDF($param)
    {

        list($type, $article_id, $token) = decrypt($param);
        $contenttype                     = 'application/pdf';
        $article                         = Article::where('article_id', $article_id)->first();
        $file                            = config('constants.admin.root_path') . $article->file_path . $article->file_name;

        if (file_exists($file)) {

            $fileInfo = pathinfo($file);
            header("Cache-Control: public");
            header('Content-Transfer-Encoding: binary');
            header("Content-Description: File Transfer");
            header("Content-Type: " . $contenttype);
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            // ob_clean();
            flush();

            // Read the file from disk
            $file_content = readfile($file);
        }
        //$content = file_get_contents($readurl);
        header("content-type: application/pdf");
        print($file_content);
    }

    public function GetArticleDetails($article_id, $param = "", Request $request)
    {   
		/* if(\Request::ip()=='103.236.135.34'){
           dd($request->doi);
        } */
		
        if($request->article_id == "download" && isset($request->param))
        {
            $article_nid = $request->param;
            $article = Article::where('nid', '=', $article_nid)->first();

            if(!empty($article))
            {
                $article_id = $article->article_id;
                
                $file_path = $this->DirectArticleDownload($request,$article_nid);

                return response()->download($file_path);                        
            }
            else
            {
                return abort(404);
            }
        }
		if($request->article_id == "download" && $request->has('doi'))
        {
            $article_doi = $request->doi;
			
            $article = Article::where('doi', '=', $article_doi)->first();
            

            if(!empty($article))
            {
                $article_nid = $article->nid;
                
                $file_path = $this->DirectArticleDownload($request,$article_nid);

                return response()->download($file_path);                        
            }
            else
            {
                return abort(404);
            }
        }

        $read_download_type="";
        $type = "";
        $view_type="";
        $art_type_array = array("Editorial", "Preface", "Acknowledgement","Biography","Corrigendum","Erratum","Obituary","Retraction Notice","Withdrawal Notice");
        $multi_language = config('constants.multi_language');
        $multi_language_name = $multi_language['ENGLISH'];
        $multilanguage_keywords = '';
        $multilanguage_article = [];
        if ($param != "") {

            $multi_language_name = "en";
            if (array_search($param, $multi_language)) {
                $multi_language_name = $param;
            } else {
            list($type, $article_id, $token) = decrypt($param);
            }

            if($type=="readpdf")
            {
                list($type, $article_id, $token, $read_download_type) = decrypt($param);
                $view_type=$type;
            }
            else if($type=="viewhtml")
            {
                $view_type=$type;
            }
        } 
        $display                     = $this->GetArticleCompleteDetail($article_id);
        $is_epub                     = $display['article']->is_epub;
        $article_id                  = $display['article']->article_id;
        $article_nid                 = $display['article']->article_nid;
        $issue_id                    = $display['article']->issue_id;
        $volume_id                   = $display['article']->volume_id;
        $volume_name                 = $display['article']->volume;
        $journal_id                  = $display['article']->journal_id;
        $DownloadAccess              = false;
        $rental                      = "";
        $bundle_content              = "";
        $content_download_type       = $read_download_type ? $read_download_type : "";
        $access_base_text            = "";
        $terms_popup                 = false;
        $checkIfMarked               = false;
        $restricted_user_access_key  = '';
        $restricted_user_access_type = '';
        $user_access_id              = 0;
        $view_option                 = 0;
        $view_abstract               = 1;
        $view_pdf                    = 0;
        $view_html                   = 0;
        //$param                       = array();

        $count_epub_article = Article::GetTrackList($journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($journal_id, 4, 0)->count();

        $refernce['open_references_html']     = "";
        $refernce['open_references_crossref'] = "";
        $refernce['open_references_pubmed']   = "";
        $refernce['open_references_pmc']      = "";

        foreach ($display['references'] as $value) {
            if ($value->cite_for == "open_references_html") {
                $refernce['open_references_html'] = $value->citation_data;
            } else if ($value->cite_for == "open_references_crossref") {
                $refernce['open_references_crossref'] = $value->citation_data;
            } else if ($value->cite_for == "open_references_pubmed") {
                $refernce['open_references_pubmed'] = $value->citation_data;
            } else if ($value->cite_for == "open_references_pmc") {
                $refernce['open_references_pmc'] = $value->citation_data;
            }
        }

        /*---------------------------------------------------------------*/
        $article_metrics = Article::GetArticleMetrics($article_id);
        // -----------------------------------------------------------

        $disease = Article::CheckArticleInDiseaseContent($article_id);

        $relatedArticle = '';
        if ($disease) {
            $relatedArticle = Article::getDiseaseRalatedArticles($disease[0]);
        }

        $node_meta = Meta::NodeMeta($display['article']->article_nid);
        if (empty($node_meta)) {
            $node_meta              = (object) $node_meta;
            $node_meta->description = substr(ltrim($display['article']->abstract), 0, 155);
            $node_meta->keywords    = $display['article']->title;
        }

        $bundle_offers = BundleOffer::GetBundleList();

        switch ($type) {

            case 'rental':

                if (session()->has('user_id')) {
                    $sparam['article_id'] = $article_id;
                    $sparam['user_id']    = session()->get('user_id');

                    //--------------Article Rental Check-----------------------
                    $rental = Article::CheckArticleRentalAccess($sparam);
                    //dd(count($rental)); // echo 1; return;

                    if (count($rental) > 0) {
                        $rental         = $rental[0];
                        $DownloadAccess = false;
                    } else {
                        return Redirect::to('/article/' . $article_id);
                    }
                }
                else {

                        return Redirect::to('/article/' . $article_id);
                    }
                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $terms_popup = false;

                return View::make('article')->with('article', $display['article'])->with('rental', $rental)->with('bundle_offers', $bundle_offers)->with('bundle_content', $bundle_content)->with('DownloadAccess', $DownloadAccess)->with('journal', $display['journal'])->with('kword', $display['kword'])->with('article_authors', $display['article_authors'])->with('article_metrics', $article_metrics)->with('content_download_type', $content_download_type)->with('relatedArticle', $relatedArticle)->with('related_journal', $display['related_journal'])->with('related_ebook', $display['related_ebook'])->with('node_meta', $node_meta)->with('access_base_text', $access_base_text)->with('terms_popup', $terms_popup)->with('restricted_user_access_key', $restricted_user_access_key)->with('restricted_user_access_type', $restricted_user_access_type)->with('checkIfMarked', $checkIfMarked)->with('refernce', $refernce)->with('view_pdf', 1)->with('param', $param)->with('user_access_id', $user_access_id)->with('count_epub_article', $count_epub_article)->with('count_epub_abstract', $count_epub_abstract);

                break;

            case 'readrentalpdf':

                if (session()->has('user_id')) {
                    $sparam['article_id'] = $article_id;
                    $sparam['user_id']    = session()->get('user_id');

                    //--------------Article Rental Check-----------------------
                    $rental = Article::CheckArticleRentalAccess($sparam);
                    //dd(count($rental)); // echo 1; return;

                    if (count($rental) > 0) {
                        $rental         = $rental[0];
                        $DownloadAccess = false;
                    } else {
                        Session::flash('message', " Article Rental Has Been Expired");

                        return Redirect::to('/article/' . $article_id);
                    }
                } else {

                        return Redirect::to('/article/' . $article_id);
                    }

                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $terms_popup = false;

                return View::make('article')->with('article', $display['article'])->with('rental', $rental)->with('bundle_offers', $bundle_offers)->with('bundle_content', $bundle_content)->with('DownloadAccess', $DownloadAccess)->with('journal', $display['journal'])->with('kword', $display['kword'])->with('article_authors', $display['article_authors'])->with('article_metrics', $article_metrics)->with('content_download_type', $content_download_type)->with('relatedArticle', $relatedArticle)->with('related_journal', $display['related_journal'])->with('related_ebook', $display['related_ebook'])->with('node_meta', $node_meta)->with('access_base_text', $access_base_text)->with('terms_popup', $terms_popup)->with('restricted_user_access_key', $restricted_user_access_key)->with('restricted_user_access_type', $restricted_user_access_type)->with('checkIfMarked', $checkIfMarked)->with('refernce', $refernce)->with('view_pdf', 1)->with('param', $param)->with('user_access_id', $user_access_id)->with('count_epub_article', $count_epub_article)->with('count_epub_abstract', $count_epub_abstract);

                break;

            default:
                if (isset($_GET['trendmd-shared'])) {
                    session(['uc_cart_id' => $_GET['trendmd-shared']]);
                } else {
                    session()->forget('trendmd_shared');
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // Access Denail Report
                // Check If User has Access but on this Article
                $this->AddAccessDenail($DownloadAccess, $journal_id, $article_id);
                //----------------------------------------------------------------

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

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

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

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

                        $return = $this->CheckUserAccessOnArticle($request, $articles, $user_access, $restricted_user_access_key, $content_download_type, $clientIP, $user_id);
                        if ($return == false) {
                            return back();
                                    }
                        }

                            if($user_id > 0)
                            {

                                $this->setUserDownloadSession($request, $user_id);
                            
                            $add_download_count = array(
                                    'user_id'               => $user_id,
                                'journal_id'            => $journal_id,
                                'volume_id'             => $volume_id,
                                'issue_id'              => $issue_id,
                                'article_id'            => $article_id,
                                'timestamp'             => time(),
                                    'ip_address'            =>  \Request::ip(),
                                'content_download_type' => $content_download_type,
                                'is_agree'              => 1,
                                'download_file_type'    => 5,
                                'session_id'            => session()->get('last_session_userid'),
                            );

                            Article::AddArticleDownload($add_download_count);

                                $add_download_count['investigation_type']=6;
                                $add_download_count['ip_address']=ip2long(\Request::ip());
                                $this->AddAccessInvestigation($request,$add_download_count);
                            }
                        }                           
                    }
                    elseif($view_type=="viewhtml")
                    {
                        $view_html = 1;
                        $view_abstract   = 0;
                     }
                }
                // View abstract add investigation
                if (Auth::user() && $view_abstract == 1) {
                    if (empty($content_download_type)) {
                          $content_download_type='D';
                        }

                    $add_investigation = array(
                        'user_id'               => Auth::user()->id,
                        'journal_id'            => $journal_id,
                        'volume_id'             => $volume_id,
                        'issue_id'              => $issue_id,
                        'article_id'            => $article_id,
                        'ip_address'            => ip2long(\Request::ip()),
                        'content_download_type' => $content_download_type,
                        'investigation_type'    => 1,
                    );

                    $add_investigation['ip_address']=ip2long(\Request::ip());
                    $this->AddAccessInvestigation($request,$add_investigation);
                 }

                $article         = $display['article'];
                $journal         = $display['journal'];
                $kword           = $display['kword'];
                $article_authors = $display['article_authors'];
                $related_journal = $display['related_journal'];
                $related_ebook   = $display['related_ebook'];
                // dd($view_option);
				
                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $terms_popup = false;
                /*
                                multi-language
                            */
                $multilanguage_article  = '';
                            $multijournal_title = '';
                if ($multi_language_name == $multi_language['CHINESE']) {
                    $language_id = MultiLanguage::where('short_code', $multi_language['CHINESE'])->pluck('language_id')->first();
                    $multilanguage_labels = MultiLanguage::getMultipleLanguageLable($language_id);
                    $multilanguage_article = MultiLangArticle::where(['language_id' => $language_id, 'article_id' => $article_id])->get()->first();
                    $multilanguage_keywords = MultiLanguageKeywords::where(['language_id' => $language_id, 'article_id' => $article_id])->pluck('keyword')->first();
                    // dd($multilanguage_keywords);

                    // get articles authors
                    $article_authors = MultiLangAuthor::getMultiLangAuthorDataById($article_id, 'article_id');
                                // get journal name
                                $multijournal_title = DB::table('multilanguage_journal')->where('multilanguage_journal.journal_id',$journal_id)->where('language_id',$language_id)->pluck('multilanguage_journal.title')->first();

                } else {
                    $language_id = MultiLanguage::where('short_code', $multi_language['ENGLISH'])->pluck('language_id')->first();
                    $multilanguage_labels = MultiLanguage::getMultipleLanguageLable($language_id);
                }

                // get lables for multi-language
                $multi_language_lable = [];
                foreach ($multilanguage_labels as $row) {
                    $multi_language_lable[$row->source_lang_label] = $row->target_lang_label;
                }
                            $has_multi_lang = MultiLangArticle::where('article_id',$article_id)->select('id')->first();
                            
                            return View::make('article', with(['view_option' => $view_option, 'rental' => $rental, 'bundle_offers' => $bundle_offers, 'bundle_content' => $bundle_content, 'DownloadAccess' => $DownloadAccess, 'article_metrics' => $article_metrics, 'content_download_type' => $content_download_type, 'relatedArticle' => $relatedArticle, 'node_meta' => $node_meta, 'access_base_text' => $access_base_text, 'terms_popup' => $terms_popup, 'restricted_user_access_key' => $restricted_user_access_key, 'restricted_user_access_type' => $restricted_user_access_type, 'checkIfMarked' => $checkIfMarked, 'refernce' => $refernce, 'article' => $article, 'journal' => $journal, 'kword' => $kword, 'article_authors' => $article_authors, 'related_journal' => $related_journal, 'related_ebook' => $related_ebook, 'user_access_id' => $user_access_id, 'type' => $type, 'param' => $param, 'view_abstract' => $view_abstract, 'view_pdf' => $view_pdf, 'view_html' => $view_html,'multi_language_name'=>$multi_language_name,'multi_language_lable' => $multi_language_lable,'multilanguage_article'=>$multilanguage_article,'multilanguage_keywords'=>$multilanguage_keywords,'has_multi_lang' => $has_multi_lang,'multijournal_title'=>$multijournal_title]))->with('count_epub_article', $count_epub_article)->with('count_epub_abstract', $count_epub_abstract);
        }
    }

    public function GetArticleCompleteDetail($article_id)
    {
        $kword           = "";
        $article         = Article::GetArticleDetail($article_id);
        $journal         = Journal::GetJournalById($article->journal_id);
        $related_journal = Subject::RelatedjournalBySubjectId($article->journal_id);
        $related_ebook   = Subject::RelatedJournaleBookBySubjectId($article->journal_id);
        $keywords        = Keywords::getKeywordDataById($article_id, 'article_id');
        $references      = Article::GetArticleReferences($article_id);

        if (!empty($keywords)) {
            if (count($keywords) > 0) {
                foreach ($keywords as $keys) {
                   if(!empty($keys->keyword)){
                     $kword = $kword . '<a target="_blank" class="btn-link" href="'.url("/search?searchvalue=".$keys->keyword).'">'.$keys->keyword . '</a>, ';
                        }
                }
                $kword = rtrim($kword, ', ');
            }
        }

        $article_authors = Author::getAuthorDataById($article_id, 'article_id');

        $bundle_offers = BundleOffer::GetBundleList();

        return with(['article' => $article, 'journal' => $journal, 'kword' => $kword, 'article_authors' => $article_authors, 'related_journal' => $related_journal, 'related_ebook' => $related_ebook, 'references' => $references, 'bundle_offers' => $bundle_offers]);
    }

    public function ExportCitation(Request $request)
    {
        $output       = "";
        $keywords     = "";
        $article_info = Article::GetArticleDetail($request->article_id);
        $export_file  = $request->input('export_file');
        $content      = $request->input('content');
        $keywords     = Keywords::getKeywordDataById($request->article_id, 'article_id');
        $authors      = Author::getAuthorDataById($request->article_id, 'article_id');
        $abstract     = strip_tags(html_entity_decode($article_info->abstract, ENT_NOQUOTES, 'UTF-8'));

        if ($export_file == "ris" && ($content == "citation" || $content == "citation_abstract")) {

            $output = "TY  - Journal ";
            $output .= "\r\nT1  - " . trim($article_info->title);
            $output .= "\r\nJO  - " . trim($article_info->journal_title);
            $output .= "\r\nVL  - " . trim($article_info->volume);
            $output .= "\r\nIS  - " . trim($article_info->issue);
            $output .= "\r\nSP  - " . trim($article_info->first_page);
            $output .= "\r\nEP  - " . trim($article_info->last_page);
            $output .= "\r\nPY  - " . trim($article_info->year);
            $output .= "\r\nT2  - " . trim($article_info->formerly_title);

            foreach ($authors as $author) {

                $output .= "\r\nAU  - " . trim($author->authorsRIS);
            }

            $output .= "\r\nSN  - " . trim($article_info->issn) . '/' . trim($article_info->eissn);
            $output .= "\r\nDO  - http://dx.doi.org/" . trim($article_info->doi);
            $output .= "\r\nUR  - http://" . $_SERVER['HTTP_HOST'] . "/article/$article_info->article_id";

            if (!empty($keywords)) {
                if (count($keywords) > 0) {
                    foreach ($keywords as $keys) {
                        $output .= "\r\nKW  - " . trim($keys->keyword);
                    }
                }
            }

            if ($content == "citation_abstract") {
                $output .= "\r\nAB  - " . trim($abstract);
            }
            $output .= "\r\nER  - ";

            header("Content-type: text/html");
            header("Content-Disposition: attachment; filename=export_citation.ris");
            echo $output;
            exit;
        } elseif ($export_file == "bibtex" && ($content == "citation" || $content == "citation_abstract")) {
            $output .= "\r\n @article{" . $authors[0]->authorsRIS . " " . $article_info->year;
            $output .= "\r\n Title = " . $article_info->title;
            $output .= "\r\n Journal = " . $article_info->journal_title;
            $output .= "\r\n volume = " . $article_info->volume;
            $output .= "\r\n Number = " . $article_info->issue;
            $output .= "\r\n Pages = " . $article_info->first_page . '-' . $article_info->last_page;
            $output .= "\r\n Year = " . $article_info->year;
            $output .= "\r\n ISSN = " . $article_info->issn . '/' . $article_info->eissn;
            $output .= "\r\n DOI = " . $article_info->doi;
            $output .= "\r\n URL = http://" . $_SERVER['HTTP_HOST'] . "/article/$article_info->article_id";

            foreach ($authors as $author) {

                $output .= "\r\n Author = " . trim($author->authorsRIS);
            }

            if (!empty($keywords)) {
                if (count($keywords) > 0) {
                    foreach ($keywords as $keys) {
                        $output .= "\r\n Keywords = " . trim($keys->keyword);
                    }
                }
            }

            if ($content == "citation_abstract") {
                $output .= "\r\n Abstract = " . $article_info->abstract;
            }
            $output .= "\r\n }";

            header("Content-type: text/html");
            header("Content-Disposition: attachment; filename=export_citation.bib");
            echo $output;
            exit;
        } elseif ($export_file == "text" && ($content == "citation" || $content == "citation_abstract")) {

            $output = "\r\n";

            foreach ($authors as $author) {

                $output .= trim($author->authorsRIS) . ",";
            }
            $output .= $article_info->title . ",";
            $output .= $article_info->journal_title . ",";
            $output .= "\r\nvolume " . $article_info->volume . ",";
            $output .= " issue " . $article_info->issue . ",";
            $output .= " pages " . $article_info->first_page . "-" . $article_info->last_page . ",";
            $output .= " year " . $article_info->year . ",";
            $output .= " issn " . $article_info->issn . "/" . $article_info->eissn . ",";
            $output .= " doi " . $article_info->doi . ",";
            $output .= "\r\n(http://" . $_SERVER['HTTP_HOST'] . "/article/$article_info->article_id" . ",";
            if ($content == "citation_abstract") {
                $output .= "\r\nAbstract: " . $article_info->abstract;
            }

            if (!empty($keywords)) {
                if (count($keywords) > 0) {
                    foreach ($keywords as $keys) {
                        $output .= trim($keys->keyword);
                    }
                }
            }
            header("Content-type: text/html");
            header("Content-Disposition: attachment; filename=export_citation.txt");
            echo $output;
            exit;
        }
    }
    public function DownlodFile(Request $request)
    {   
        $SecondsGap = 30; //default is 30 sec

        $param = Crypt::decrypt($request->param);

        $article_id                 = '';
        $file_type                  = '';
        $content_download_type      = '';
        $restricted_user_access_key = '';
        $clientIP                   = ip2long($request->ip());
        $user_id                    = isset(Auth::user()->id) ? Auth::user()->id : 0;

        list($article_id, $file_type, $content_download_type, $restricted_user_access_key, $user_access_id) = explode("||", $param);


        $file_path = '';
        $article   = Article::where('article_id', $article_id)->first();

        $user_access = UserAccess::where('user_access_id', $user_access_id)->first();

        if (!empty($user_access)) {
            $user_id = $user_access->user_id;
        } elseif ($user_id == 0) {
            if (isset($request->dduser)) {
                $user_id = Crypt::decrypt($request->dduser);
            } else {
               $user_id = session()->get('user_id'); 
           } 
        }

        //--Shareable user check
        if (isset($request->shareable_link)) {

            $shareable = Shareable::where('link', '=', $request->shareable_link)->first();
            $user_id = $shareable->user_id;
        }
        //----------Discipline Article----------
        if ($content_download_type == "D") {
            $d_param['disc_user_access_id']     = $request->disc_user_access_id;
            $discipline_access = Discipline::GetDisciplineAccess($d_param);
            $discipline_access = $discipline_access[0];

            $d_param['user_id'] = $discipline_access->id;
            $d_param['article_id'] = $article_id;
            $d_param['dc_user_id'] = $request->dc_user_id;

            $article_download = Discipline::GetDisciplineDownloadArticle($d_param);

            if ($article_download->count() >= $discipline_access->download_per_article) {
                Session::flash('message', "Article download limit exceeded");
                return back();
            }
        }


        if ($user_id > 0) {
            $article_gap = Article::ArticleDownloadGap($user_id, $article_id, $SecondsGap);
            if ($article_gap->rcd > 0) {

                $last_session_userid = $request->session()->getId() . "-" . microtime(true);
                session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_articles set timestamp=" . time() . ", session_id='" . session()->get('last_session_userid') . "' where id='" . $article_gap->id . "'");
                Session::flash('message', " Cannot download, try again after $SecondsGap seconds");
                return back();
            }
        } else if (Cookie::get('name') !== null) {
            Session::flash('message', " Cannot download, try again after $SecondsGap seconds");
            return back();
        } else {
            //Cookie::forget('name');
            //Session::forget('message');
            Cookie::queue('name', time(), 1);
        }

        if ($file_type == 'pdf') {
            $download_file_type = 1;
            $investigation_type = 2;
            $file_path          = config('constants.admin.root_path') . $article->file_path . $article->file_name;
        }
        if ($file_type == 'supplementary') {
            $download_file_type = 0;
            $file_path          = config('constants.admin.root_path') . $article->file_path . $article->supplementary_filename;
        }
        if ($file_type == 'html') {
            $download_file_type = 2;
             $investigation_type = 3;
            $param              = encrypt(array('viewhtml', $article_id, config('constants.admin.token')));
            $file_path          = redirect()->route('article', ['article_id' => $article_id, 'param' => $param]);
        }
        if ($file_type == 'epub') {
            $download_file_type = 3;
            $investigation_type = 4;
            $file_path          = config('constants.admin.root_path') . $article->file_path . 'epub/' . $article->epub_filename;
        }
        if ($file_type == 'prc') {
            $download_file_type = 4;
            $investigation_type = 5;
            $file_path          = config('constants.admin.root_path') . $article->file_path . 'prc/' . $article->prc_filename;
        }

        if (file_exists($file_path) || $file_type == 'html') {
            // check User Access On Article befor Download
            if (!empty($user_access)) {

                $return = $this->CheckUserAccessOnArticle($request, $article, $user_access, $restricted_user_access_key, $content_download_type, $clientIP, $user_id);
                if ($return == false) {
                    return back();
                }
            }

            if ($file_type != 'supplementary') {
                if ($user_id > 0 && isset($article->article_id)) {

                    $this->setUserDownloadSession($request, $user_id);
                    
                    $add_download_count = array(
                        'user_id'               => $user_id,
                        'journal_id'            => $article->journal_id,
                        'volume_id'             => $article->volume_id,
                        'issue_id'              => $article->issue_id,
                        'article_id'            => $article->article_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'content_download_type' => $content_download_type,
                        'is_agree'              => 1,
                        'download_file_type'    => $download_file_type,
                        //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                        'session_id'            => session()->get('last_session_userid'),
                    );

                   $last_download_count = Article::AddArticleDownload($add_download_count);

                    $add_download_count['investigation_type']=$investigation_type;
                
                    $add_download_count['ip_address']=ip2long(\Request::ip());

                    $last_inv_id = $this->AddAccessInvestigation($request,$add_download_count);



                    // --------if discipline link exist-------- 
                    if ($content_download_type == "D") {
                        $add_discipline_article = array(
                        'disc_user_access_id'   => $discipline_access->disc_user_access_id,
                        'discipline_id'         => $discipline_access->discipline_id,
                        'user_id'               => $user_id,
                        'dc_user_id'            => $request->dc_user_id,
                        'journal_id'            => $article->journal_id,
                        'volume_id'             => $article->volume_id,
                        'issue_id'              => $article->issue_id,
                        'article_id'            => $article->article_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'is_agree'              => 1,
                        'download_file_type'    => $download_file_type,
                        'session_id'            => session()->get('last_session_userid'),
                        );

                        Discipline::AddDisciplineDownloadArticle($add_discipline_article);
                    }
                    //-------discipline End-----------

                    // --------if direct download link exist-------- 
                    if ((isset($request->download_type) && isset($request->download_email)) &&  $request->download_type == "direct_download") {

                        $add_user_access_article = array(
                        'user_access_id'        => $user_access_id,
                        'download_count_id'     => $last_download_count,
                        'investigation_id'      => $last_inv_id,
                        'user_id'               => $user_id,
                        'user_email'            => $request->download_email,
                        'journal_id'            => $article->journal_id,
                        'volume_id'             => $article->volume_id,
                        'issue_id'              => $article->issue_id,
                        'article_id'            => $article->article_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'is_agree'              => 1,
                        'download_file_type'    => 1,
                        'content_download_type' => $content_download_type,
                        );

                        UserAccess::AddUserAccessDownloadArticle($add_user_access_article);
                    }
                    //-------direct download End-----------

                    // --------if shareable link exist--------
                    if (isset($request->shareable_link)) {

                        $add_shareable_link = array(
                        'shareable_link_id' => $shareable->shareable_link_id,
                            'sl_user_id'        => $user_id,
                        'investigation_id'  => $last_inv_id,
                            'content_id'        => $article->article_id,
                        'sl_content_type'   => $download_file_type,
                        'sl_downloaded_on'  => time(),
                        'sl_ip'             => ip2long($request->ip()),
                        );
                        $downloaded = $shareable->downloaded + 1;
                    DB::select("update shareable_link set downloaded=".$downloaded." where shareable_link_id=".$shareable->shareable_link_id);

                        Shareable::AddShareableDownload($add_shareable_link);
                    }
                    //-------direct download End-----------

                }

            }

            if ($file_type == 'html') {
                return $file_path;
            } else {
                return response()->download($file_path);
            }

        } else {

            Session::flash('message', " File does not exist!");
            return back();
        }

    }

    public function DownlodBundleFile(Request $request)
    {
        $SecondsGap = 30; //default is 30 sec

        $param = Crypt::decrypt($request->param);

        $article_id                 = '';
        $file_type                  = '';
        $content_download_type      = '';
        $restricted_user_access_key = '';
        $clientIP                   = ip2long($request->ip());
        $user_id                    = isset(Auth::user()->id) ? Auth::user()->id : 0;

        list($article_id, $file_type, $content_download_type, $restricted_user_access_key, $user_access_id) = explode("||", $param);

        if (Auth::user()->id > 0) {
            $bundle_content = BundleOfferController::BundleOfferUserAccess($user_id);
            $article_gap    = Article::ArticleDownloadGap($user_id, $article_id, $SecondsGap);
            if ($article_gap->rcd > 0) {

                $last_session_userid = $request->session()->getId() . "-" . microtime(true);
                session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_articles set timestamp=" . time() . ", session_id='" . session()->get('last_session_userid') . "' where id='" . $article_gap->id . "'");
                Session::flash('message', " Cannot download, try again after $SecondsGap seconds");
                return back();
            } else if ($bundle_content->article == 0) {

                Session::flash('message', " Article Bundle Limit Completed");
                return back();
            }
        } else if (Cookie::get('name') !== null) {
            Session::flash('message', " Cannot download, try again after $SecondsGap seconds");
            return back();
        } else {
            //Cookie::forget('name');
            //Session::forget('message');
            Cookie::queue('name', time(), 1);
        }

        $file_path = '';
        $article   = Article::where('article_id', $article_id)->first();

        if ($file_type == 'pdf') {
            $download_file_type = 1;
            $investigation_type = 2;
            $file_path          = config('constants.admin.root_path') . $article->file_path . $article->file_name;
        }
        if ($file_type == 'supplementary') {
            $download_file_type = 0;
            $file_path          = config('constants.admin.root_path') . $article->file_path . $article->supplementary_filename;
        }
        if ($file_type == 'html') {
            $download_file_type = 2;
            $investigation_type = 3;
            $param              = encrypt(array('viewhtml', $article_id, config('constants.admin.token')));
            $file_path          = redirect()->route('article', ['article_id' => $article_id, 'param' => $param]);
        }
        if ($file_type == 'epub') {
            $download_file_type = 3;
            $investigation_type = 4;
            $file_path          = config('constants.admin.root_path') . $article->file_path . 'epub/' . $article->epub_filename;
        }
        if ($file_type == 'prc') {
            $download_file_type = 4;
            $investigation_type = 5;
            $file_path          = config('constants.admin.root_path') . $article->file_path . 'prc/' . $article->prc_filename;
        }

        if (file_exists($file_path) || $file_type == 'html') {

            if ($file_type != 'supplementary') {
                if (Auth::user()->id > 0 && isset($article->article_id)) {
                    $this->setUserDownloadSession($request, Auth::user()->id);
                    $add_download_count = array(
                        'user_id'               => isset(Auth::user()->id) ? Auth::user()->id : 0,
                        'journal_id'            => $article->journal_id,
                        'volume_id'             => $article->volume_id,
                        'issue_id'              => $article->issue_id,
                        'article_id'            => $article->article_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'content_download_type' => $content_download_type,
                        'is_agree'              => 1,
                        'download_file_type'    => $download_file_type,
                        //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                        'session_id'            => session()->get('last_session_userid'),
                    );

                    Article::AddArticleDownload($add_download_count);

                    $add_download_count['investigation_type']=$investigation_type;

                    $this->AddAccessInvestigation($request,$add_download_count);

                    if ($content_download_type == 'B') {
                        $add_bundle_count = array(
                            'user_id'               => isset(Auth::user()->id) ? Auth::user()->id : 0,
                            'bundle_offer_order_id' => $request->bundle_offer_order_id,
                            'content_id'            => $article->article_id,
                            'content_type'          => 'a',
                            'downloaded_on'         => time(),
                            'ip'                    => $request->ip(),
                        );

                        BundleOffer::AddBundleOfferOrderContent($add_bundle_count);
                    }
                }
            }

            if ($file_type == 'html') {
                return $file_path;
            } else {
                return response()->download($file_path);
            }
        } else {

            Session::flash('message', " File does not exist!");
            return back();
        }
    }

    public function AddAccessInvestigation($request,$data)
    {   
        $SecondsGap = 30;
        $timestamp  = time();
        $user_id = $data['user_id'];

        if ($data['user_id'] != 0 && $data['article_id'] != 0) {

            $query_check = "select * from access_investigation_report where (user_id = ".$data['user_id']." and article_id = ".$data['article_id']." ) and (unix_timestamp(CURRENT_TIMESTAMP())-timestamp) <= 3 order by timestamp desc ";
            $result_check = DB::select($query_check);  

            if (count($result_check) == 0) {

                $query = "select * from access_investigation_report where (user_id = ".$data['user_id']." and article_id = ".$data['article_id']." and investigation_type= ".$data['investigation_type'].") and (unix_timestamp(CURRENT_TIMESTAMP())-timestamp) <= $SecondsGap order by timestamp desc ";

                $gap_res = DB::select($query);  

                if ($gap_res) {

                    $last_inv_session_userid = $request->session()->getId() . "-" . microtime(true);
                    session(['last_inv_session_userid' => $last_inv_session_userid]);
                    DB::select("update access_investigation_report set timestamp=" . time() . ", session_id='" . session()->get('last_inv_session_userid') . "' where id='" . $gap_res[0]->id . "'");
                } else {

                    if ($data['user_id'] != 0 && $data['article_id'] != 0) {

                       $this->setUserInvestigationSession($request, $user_id);
                       
                       $id = DB::table('access_investigation_report')->insertGetId(
                            [
                                'journal_id' => $data['journal_id'],
                                        'volume_id' => $data['volume_id'],
                                        'issue_id' => $data['issue_id'],
                                        'article_id' => $data['article_id'],
                                        'user_id' => $data['user_id'],
                                        'content_download_type' => $data['content_download_type'],
                                        'investigation_type' => $data['investigation_type'],
                                        'timestamp' => $timestamp,
                                        'ip_address' => $data['ip_address'],
                                        'session_id' => session()->get('last_inv_session_userid'),
                                        ]
                                );

                        return $id;
                    }
                }
            }
        }
    }

    public function Article_AddtoCart(Request $request)
    {

        dd($request->param);
    }

    public function MultiUserOrder(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $order_id      = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            EbookVolume::UpdateEbookOrder($order_id, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id'] = $request->get('order_id');
            $param['email']    = $request->get('email');
            $param['ebook_id'] = $request->get('ebook_id');
            $param['status']   = $request->get('status');

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetMultiUserOrder($param, true);

            foreach ($order_list as $k => $v) {
                $order_list[$k]->discount_amount = '';
                if (!empty($v->discount_rate)) {
                    $dis_rate                        = ($v->actual_amount / 100) * $v->discount_rate;
                    $discount_amount                 = $v->actual_amount - $dis_rate;
                    $order_list[$k]->discount_amount = $discount_amount;
                }
            }

            $page    = 'multiuserorder';
            $heading = 'Multiuser Order';

            $ebook_search = Ebook::GetEbookTitle();

            if (!empty($export)) {

                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with(['ebook_search' => $ebook_search, 'heading' => $heading, 'page' => $page, 'param' => $param, 'order_list' => $order_list]));
            }
        }
    }

    public function FullTextInquiryView(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $inquiry_id    = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            Article::UpdateFullTextInquiryOrder($inquiry_id, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id'] = $request->get('order_id');
            $param['email']    = $request->get('email');
            $param['status']   = $request->get('status');

            // 2019-06-18 10:38:41

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetFullTextInquiryOrder($param, true);

            $page    = 'fulltext';
            $heading = 'Full-text Inquiry Order Detail';

            if (!empty($export)) {
                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with(['heading' => $heading, 'page' => $page, 'param' => $param, 'order_list' => $order_list]));
            }
        }
    }

    public function PrintVersionOrder(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $poid          = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            Article::UpdatePrintVersionOrder($poid, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id'] = $request->get('order_id');
            $param['email']    = $request->get('email');
            $param['ebook_id'] = $request->get('ebook_id');
            $param['status']   = $request->get('status');

            // 2019-06-18 10:38:41

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetPrintVersionOrder($param, true);

            foreach ($order_list as $k => $v) {
                $order_list[$k]->discount_amount = '';
                if (!empty($v->discount_rate)) {
                    $dis_rate                        = ($v->actual_amount / 100) * $v->discount_rate;
                    $discount_amount                 = $v->actual_amount - $dis_rate;
                    $order_list[$k]->discount_amount = $discount_amount;
                }
            }

            $page    = 'printorder';
            $heading = 'Print Version Order Details';

            $ebook_search = Ebook::GetEbookTitle();

            if (!empty($export)) {
                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with([
                    'ebook_search' => $ebook_search,
                    'heading'                                                         => $heading,
                    'page'                                                            => $page,
                    'param'                                                           => $param,
                    'order_list'                                                      => $order_list
                ]));
            }
        }
    }

    public function PreOrder(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $inquiry_id    = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            Article::UpdatePreOrder($inquiry_id, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id']   = $request->get('order_id');
            $param['email']      = $request->get('email');
            $param['ebook_id']   = $request->get('ebook_id');
            $param['ebook_type'] = $request->get('ebook_type');

            // 2019-06-18 10:38:41

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetPreOrder($param, true);

            $page    = 'preorder';
            $heading = 'Pre Order';

            $ebook_search = Ebook::GetEbookTitle();

            if (!empty($export)) {
                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with(['ebook_search' => $ebook_search, 'heading' => $heading, 'page' => $page, 'param' => $param, 'order_list' => $order_list]));
            }
        }
    }

    public function ReprintOrder(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $reprint_id    = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            Article::UpdateReprintOrder($reprint_id, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id'] = $request->get('order_id');
            $param['email']    = $request->get('email');

            // 2019-06-18 10:38:41

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetReprintOrder($param, true);

            $page    = 'reprintorder';
            $heading = 'Reprint Order';

            if (!empty($export)) {
                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with(['heading' => $heading, 'page' => $page, 'param' => $param, 'order_list' => $order_list]));
            }
        }
    }

    public function EprintOrder(Request $request)
    {
        $ajax = $request->get('ajax');

        if ($ajax == true) {
            $reprint_id    = $request->get('pk_id');
            $toggle_status = $request->get('toggle_status');

            $update_inquiry['status']       = $toggle_status;
            $update_inquiry['last_updated'] = now();

            Article::UpdateReprintOrder($eprint_id, $update_inquiry);

            return response()->json(array('result' => true), 200);
        } else {
            $export = $request->get('export');

            $param['order_id'] = $request->get('order_id');
            $param['email']    = $request->get('email');

            // 2019-06-18 10:38:41

            $from_date = $request->get('from_date');
            if (!empty($from_date)) {
                $param['from_date'] = date("Y-m-d", strtotime($from_date));
            }

            $to_date = $request->get('to_date');
            if (!empty($to_date)) {
                $param['to_date'] = date("Y-m-d", strtotime($to_date));
            }

            $param['limit'] = isset($export) ? null : 10;
            $order_list     = Article::GetEprintOrder($param, true);

            $page    = 'eprintorder';
            $heading = 'ePrint Order';

            if (!empty($export)) {
                $this->generateReport($order_list, $page);
                exit;
            } else {
                return view('admin.article.web_form_report', with(['heading' => $heading, 'page' => $page, 'param' => $param, 'order_list' => $order_list]));
            }
        }
    }

    public function WebFormReport(Request $request)
    {
        if ($request->report == 'fulltext') {
            return $this->FullTextInquiryView($request);
        } elseif ($request->report == 'multiuserorder') {
            return $this->MultiUserOrder($request);
        } elseif ($request->report == 'printorder') {
            return $this->PrintVersionOrder($request);
        } elseif ($request->report == 'preorder') {
            return $this->PreOrder($request);
        } elseif ($request->report == 'reprintorder') {
            return $this->ReprintOrder($request);
        } elseif ($request->report == 'eprintorder') {
            return $this->EprintOrder($request);
        } elseif ($request->report == 'rentalorder') {
            return $this->RentalOrderAdmin($request);
        } elseif ($request->report == 'issuepurchase') {
            return $this->IssuePurhase($request);
        } elseif ($request->report == 'journalsubscriptionorder') {
            return $this->JournalSubscriptionOrder($request);
        }
    }

    public function JournalSubscriptionOrder(Request $request)
    {

        $journal_search = Journal::GetJournalTitle();

        $from_date = $request->get('from_date');
        if (!empty($from_date)) {
            $param['from_date'] = date("Y-m-d", strtotime($from_date));
        }

        $to_date = $request->get('to_date');
        if (!empty($to_date)) {
            $param['to_date'] = date("Y-m-d", strtotime($to_date));
        }

        $param['journal_id']   = $journal_id   = $request->get('journal_id');
        $param['user_email']   = $user_email   = $request->get('user_email');
        $param['status']       = $status       = $request->get('status');
        $param['paginate']     = true;

        $journal_subscrition           = Journal::GetSubscritionOrderDetail($param);
        
       // dd($journal_subscrition);
        
        return View::make('admin.orders.journal_subscription_list', with(['journal_subscrition' => $journal_subscrition,'journal_search' => $journal_search, 'param' => $param]));
    }
    public function IssuePurhase(Request $request)
    {
        $journal_search = "";
        $volume_search  = "";
        $issue_search   = "";

        $thankyou = false;
        if ($request->ajx_search != null && $request->ajx_search == true) {
            return $this->getSearch($request);
        }

        $journal_search = Journal::GetJournalTitle();

        $param['journal_id']   = $journal_id   = $request->get('journal_id');
        $param['volume_id']    = $volume_id    = $request->get('volume_id');
        $param['issue_id']     = $issue_id     = $request->get('issue_id');
        $param['user_email']   = $user_email   = $request->get('user_email');
        $param['issue_status'] = $issue_status = $request->get('issue_status');
        $param['status']       = $status       = $request->get('status');
        $param['paginate']     = true;

        // Get Volume , issue from ajax call
        $frm_search = $request->get('frm_search');

        $issue_order = Issue::GetIssuePurchaseDetail($param);

        if (!empty($journal_id)) {
            $p['journal_id'] = $journal_id;
            $volume_search   = Volume::GetVolumeTitleById($p);
        }
        if (!empty($volume_id)) {
            $p['volume_id'] = $volume_id;
            $issue_search   = Issue::GetIssueTitleById($p);
        }

        // dd($article_search);
        return View::make('admin.orders.issue_purchase_list', with(['issue_order' => $issue_order, 'volume_search' => $volume_search, 'journal_search' => $journal_search, 'issue_search' => $issue_search, 'param' => $param]));
    }
    //-------------Article-Reprint-Eprint-Order-----------------//
    public function RentalOrderAdmin(Request $request, $article_id = null)
    {
        $volume_search  = "";
        $issue_search   = "";
        $article_search = "";

        $thankyou = false;
        if ($request->ajx_search != null && $request->ajx_search == true) {
            return $this->getSearch($request);
        }

        $journal_search = Journal::GetJournalTitle();

        if ($request->type == "list") {

            $param['journal_id']    = $journal_id    = $request->get('journal_id');
            $param['volume_id']     = $volume_id     = $request->get('volume_id');
            $param['issue_id']      = $issue_id      = $request->get('issue_id');
            $param['article_id']    = $article_id    = $request->get('article_id');
            $param['user_name']     = $name     = $request->get('user_name');
            $param['rental_status'] = $rental_status = $request->get('rental_status');
            $param['order_status']  = $order_status  = $request->get('order_status');
            $param['paginate']      = true;

            // Get Volume , issue from ajax call
            $frm_search = $request->get('frm_search');

            $article_rental = Article::GetArticleRentalDetail($param);

            if (!empty($journal_id)) {
                $p['journal_id'] = $journal_id;
                $volume_search   = Volume::GetVolumeTitleById($p);
            }
            if (!empty($volume_id)) {
                $p['volume_id'] = $volume_id;
                $issue_search   = Issue::GetIssueTitleById($p);
            }
            if (!empty($issue_id)) {
                $p['issue_id']  = $issue_id;
                $article_search = Article::GetArticleList($p);
            }

            // dd($article_search);
            return View::make('admin.orders.article_rental_list', with(['article_rental' => $article_rental, 'volume_search' => $volume_search, 'journal_search' => $journal_search, 'issue_search' => $issue_search, 'article_search' => $article_search, 'param' => $param]));
        } else if ($request->submit == true) {

            try {
// try transaction start here for data integrity
                $validator = Validator::make($request->all(), [
                    'email' => 'required|string|email|max:255',

                ]);

                if (isset($validator)) {
                    if ($validator->fails()) {
                        return back()->withInput()->withErrors($validator);
                    }
                }

                DB::beginTransaction();

                $user = Auth::user();

                //-------------------Insert into rental order Table---------------

                $journal_rental = Journal::GetJournalRentalDetail($request->rental, 'rental_id');
                $journal_rental = $journal_rental[0];

                $timenow      = time();
                $current_time = strtotime($timenow);

                $timefrom = date('Y-m-d H:i:s', strtotime($current_time . ' + ' . $journal_rental->rental_hours . ' hours'));

                $from_time = strtotime($timefrom);

                $add_details['article_id']       = $request->article_id;
                $add_details['rental_id']        = $request->rental;
                $add_details['user_name']        = $request->display_name;
                $add_details['user_email']       = $request->email;
                $add_details['user_country']     = $request->country;
                $add_details['rental_id']        = $request->rental;
                $add_details['user_id']          = $user->id;
                $add_details['guest']            = $user->name;
                $add_details['rental_date_from'] = $timenow;
                $add_details['rental_date_to']   = $from_time;
                $add_details['created_on']       = time();
                $add_details['last_modified']    = time();
                $add_details['order_status']     = 'I';
                $add_details['ip']               = ip2long($request->ip());

                $rental_order_id = Article::AddRentalOrder($add_details);

                $add_log = array(
                    'content_id'      => $rental_order_id,
                    'content_type_id' => config('constants.log_content_types.Article_Rental_Order'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($add_details),
                    'created_dated'   => time(),
                    'created_by'      => $user->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                $param['rental_order_id'] = $rental_order_id;
                $article_rental           = Article::GetArticleRentalDetail($param);
                $article_rental           = $article_rental[0];

                $detail['order_id']      = $article_rental->rental_order_id;
                $detail['journal']       = $article_rental->title;
                $detail['journal_id']    = $article_rental->journal_id;
                $detail['volume']        = $article_rental->volume;
                $detail['issue']         = $article_rental->issue;
                $detail['article_title'] = $article_rental->article;
                $detail['article_id']    = $article_rental->article_id;
                $detail['display_name']  = $article_rental->display_name;
                $detail['email']         = $article_rental->email;
                $detail['country']       = $article_rental->country;
                $detail['hour']          = $article_rental->rental_hours;
                $detail['price']         = $article_rental->rental_price;

                //if Doesnot exist than check/create new User
                $user_details = (array) UserController::CheckAddUserDetails($article_rental);

                $user_id = $user_details['id'];
                if (isset($user_details['password_text'])) {
                    $detail['name']     = $user_details['name'];
                    $detail['password'] = $user_details['password_text'];

                    $user_data = array(
                        'name'     => $detail['name'],
                        'password' => $detail['password'],
                    );
                }

                $detail['display_name'] = $user_details['display_name'];
                $detail['email']        = $user_details['email'];
                $detail['country']      = $user_details['country'];
                $detail['rental_link']  = url("/article/" . $article_rental->article_id);

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_xolva_2', 'email_xolva_2', 'email_support_2');
                $subject = "Rental Article Order Number # " . $rental_order_id . "";

                SendSmtpMail('email_template.rental_article_successfull', $detail, $to, $from, $subject, 'Admin', $cc);

                $migs_transaction                  = 'Success';
                $update_rental['user_id']          = $user_id;
                $update_rental['response_code']    = 0;
                $update_rental['response_message'] = 'Done By Admin';
                $update_rental['transaction_no']   = '';
                $update_rental['email_status']     = 1;
                $update_rental['order_status']     = "C";
                $update_rental['last_modified']    = time();
                $update_rental['rental_status']    = 'S';

                Article::UpdateRentalOrder($rental_order_id, $update_rental);

                $thankyou = true;

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }

            $volume_search  = array();
            $issue_search   = array();
            $article_search = array();
            $article_rental = array();

            return Redirect::to('admin/web_form_report/rentalorder/list')->with('success', 'Rental access has been added.');
        }

        $country = Country::GetCountryList();
        return View::make('admin.orders.article_rental', with(['journal_search' => $journal_search, 'thankyou' => $thankyou, 'country' => $country]));
    }
    public function generateReport($list, $page)
    {
        $filename = $page . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        if ($page == 'preorder') {
            $head_line = array("Order_ID", "Email", "ebook_title", "ebook Type", "last Updated");
        } elseif ($page == 'printorder') {
            $head_line = array("Order_ID", "Name", "Email", "Status", "eBook_Title", "Price", "Order_Date");
        } elseif ($page == 'multiuserorder') {
            $head_line = array("Order_ID", "Name", "Email", "Status", "ebook_title", "Price", "Order_Date");
        } elseif ($page == 'reprintorder' || $page == 'eprintorder') {
            $head_line = array("Order_ID", "Email", "Status", "Article Title", "Volume", "Pages", "Order Date");
        } else {
            $head_line = array("Order_ID", "Name", "Email", "Status", "journal_title", "Volume", "URL", "Article_Title", "Price", "Order_Date");
        }

        $fp = fopen('php://output', 'wb');
        fputcsv($fp, $head_line);

        if ($page == 'preorder') {
            foreach ($list as $order) {
                $line['order_id']   = $order->oid;
                $line['email']      = $order->email;
                $line['book_title'] = $order->ebook_title;

                if ($order->ebook_type == 2 && $order->ebook_status == 2) {
                    $line['ebook_type'] = 'Forthcoming Series';
                } elseif ($order->ebook_type == 1 && $order->ebook_status == 2) {
                    $line['ebook_type'] = 'Forthcoming General eBook';
                } elseif ($order->ebook_type == 2 && $order->ebook_status == 3) {
                    $line['ebook_type'] = 'Future Series';
                } elseif ($order->ebook_type == 1 && $order->ebook_status == 3) {
                    $line['ebook_type'] = 'Future General eBook';
                }
                $line['order_date'] = $order->last_updated;

                fputcsv($fp, $line);
            }
        } elseif ($page == 'printorder') {
            foreach ($list as $order) {
                $line['order_id'] = $order->poid;

                $line['name'] = $order->fname . ' ' . $order->lname;

                $line['email'] = $order->email;

                if ($order->status == "C") {
                    $line['status'] = 'Completed';
                }
                if ($order->status == "F") {
                    $line['status'] = 'Not Complete';
                }
                if ($order->status == "P") {
                    $line['status'] = 'Pending';
                }
                if ($order->status == "E") {
                    $line['status'] = 'Emailed';
                }

                $line['book_title']    = $order->book_title;
                $line['actual_amount'] = $order->amount;
                $line['last_updated']  = $order->last_updated;

                fputcsv($fp, $line);
            }
        } elseif ($page == 'multiuserorder') {
            foreach ($list as $order) {
                $line['order_id'] = $order->oid;

                $line['name'] = $order->name;

                $line['email'] = $order->email;

                if ($order->status == "C") {
                    $line['status'] = 'Completed';
                }
                if ($order->status == "F") {
                    $line['status'] = 'Not Complete';
                }
                if ($order->status == "P") {
                    $line['status'] = 'Pending';
                }
                if ($order->status == "E") {
                    $line['status'] = 'Emailed';
                }

                $line['book_title']    = $order->book_title;
                $line['actual_amount'] = $order->actual_amount;
                $line['last_updated']  = $order->last_updated;

                fputcsv($fp, $line);
            }
        } else if ($page == 'fulltext') {
            foreach ($list as $order) {
                $line['order_id'] = $order->inquiry_id;
                $line['name']     = $order->name;
                $line['email']    = $order->email;

                if ($order->status == "C") {
                    $line['status'] = 'Completed';
                }
                if ($order->status == "F") {
                    $line['status'] = 'Not Complete';
                }
                if ($order->status == "P") {
                    $line['status'] = 'Pending';
                }
                if ($order->status == "E") {
                    $line['status'] = 'Emailed';
                }

                $line['journal_title'] = $order->journal_title;
                $line['volume']        = $order->volume_name;
                $line['Url']           = 'http://www.eurekaselect.com/article/' . $order->article_id;
                $line['article_title'] = $order->article_title;
                $line['price']         = $order->amount;
                $line['order_date']    = $order->created_on;

                fputcsv($fp, $line);
            }
        } elseif ($page == 'reprintorder' || $page == 'eprintorder') {
            foreach ($list as $order) {
                $line['order_id'] = isset($order->reprint_order_id) ? $order->reprint_order_id : $order->eprint_order_id;

                $line['email'] = $order->email;

                if ($order->status == "C") {
                    $line['status'] = 'Completed';
                }
                if ($order->status == "P") {
                    $line['status'] = 'Pending';
                }
                if ($order->status == "E") {
                    $line['status'] = 'Emailed';
                }

                $line['article_title'] = $order->article_title;
                $line['volume_name']   = $order->volume_name;
                $line['reprint_pages'] = isset($order->reprint_pages) ? $order->reprint_pages : $order->eprint_pages;
                $line['last_updated']  = $order->last_updated;

                fputcsv($fp, $line);
            }
        }

        fclose($fp);
    }

    public function FullTextInquiry(Request $request, $article_id)
    {
        if (isset($request->issue_purchase_form) && $request->issue_purchase_form == 'Preview') {
            $validator = Validator::make(
                $request->all(),
                [
                    'name'                 => 'required',
                    'email'                => 'required|string|email|max:255',
                    'captcha' => 'required|captcha'], 
                    ['captcha.captcha' => 'Invalid captcha code.']);

            if ($validator->fails()) {
                return $this->FullTextInquiryForm($request, $article_id, $validator);
            } else {
                return $this->FullTextInquiryPreview($request, $article_id);
            }
        } elseif (isset($request->full_text_inquiry_form) && $request->full_text_inquiry_form == 'Submit') {
            return $this->FullTextInquirySubmit($request, $article_id);
        } else {
            return $this->FullTextInquiryForm($request, $article_id);
        }
    }

    public function FullTextInquiryForm($request, $article_id, $validator = null)
    {
        $article = Article::where('article_id', $article_id)->first();
        //$issue = Issue::where('issue_id',$article->issue_id)->first();
        $volume  = Volume::where('volume_id', $article->volume_id)->first();
        $journal = Journal::where('journal_id', $article->journal_id)->first();

        $session_detail = $request->session()->get('session_detail');
        if (!empty($session_detail)) {
            $detail['name']    = isset($session_detail[0]['name']) ? $session_detail[0]['name'] : '';
            $detail['email']   = isset($session_detail[0]['email']) ? $session_detail[0]['email'] : '';
            $detail['address'] = isset($session_detail[0]['address']) ? $session_detail[0]['address'] : '';
            $detail['phone']   = isset($session_detail[0]['phone']) ? $session_detail[0]['phone'] : '';
        } else {
            $detail['name']    = '';
            $detail['email']   = '';
            $detail['address'] = '';
            $detail['phone']   = '';
        }

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        $page_name = 'full_text_inquiry';

        $latest_issue = Issue::getcurrentissue($article->journal_id);

        $count_epub_article = Article::GetTrackList($article->journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($article->journal_id, 4, 0)->count();

        if (!empty($validator) && $validator->fails()) {
            return view('journal_menu', with(['journal' => $journal, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]))->withErrors($validator);
        } else {
            return view('journal_menu', with(['journal' => $journal, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]));
        }
    }

    public function FullTextInquiryPreview(Request $request, $article_id)
    {

        $session_detail = $request->session()->get('session_detail');

        $detail['name']    = isset($request->name) ? $request->name : $session_detail[0]['name'];
        $detail['email']   = isset($request->email) ? $request->email : $session_detail[0]['email'];
        $detail['address'] = isset($request->address) ? $request->address : '';
        $detail['phone']   = isset($request->phone) ? $request->phone : '';

        $request->session()->forget('session_detail');
        $request->session()->push('session_detail', $detail);

        $article = Article::where('article_id', $article_id)->first();
        $issue   = Issue::where('issue_id', $article->issue_id)->first();
        $volume  = Volume::where('volume_id', $article->volume_id)->first();
        $journal = Journal::where('journal_id', $article->journal_id)->first();

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        $latest_issue = Issue::getcurrentissue($article->journal_id);
        $page_name    = 'full_text_inquiry_preview';

        $count_epub_article = Article::GetTrackList($article->journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($article->journal_id, 4, 0)->count();

        return view('journal_menu', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]));
    }

    public function FullTextInquirySubmit(Request $request, $article_id)
    {
        $user = Auth::user();
        if ($user == null) {
            //echo 'User ip base Is not implemented Yet'; exit;
            //$username=Issue::GetUserNameByIP(); // like trail , corporate etc
        } else {
            $username = $user->name;
        }

        $article = Article::where('article_id', $article_id)->first();
        $issue   = Issue::where('issue_id', $article->issue_id)->first();
        $volume  = Volume::where('volume_id', $article->volume_id)->first();
        $journal = Journal::where('journal_id', $article->journal_id)->first();

        $username  = isset($user) ? $user->id : 0;
        $remote_ip = ip2long($request->ip());
        $name      = $request->name;
        $email     = $request->email;
        $address   = $request->address;
        $phone     = $request->phone;

        $journal_name  = $journal->title;
        $sell_price    = $journal->epub_price;
        $volume_name   = $volume->volume_name;
        $article_title = $article->title;
        //$year= $row->year_name;

        //-------------------Insert into epub Full text Inquiry Order Table---------------

        $add_details['nid']           = $article->nid;
        $add_details['article_id']    = $article->article_id;
        $add_details['article_title'] = $article->title;

        $add_details['name']    = $name;
        $add_details['email']   = $email;
        $add_details['address'] = $address;
        $add_details['phone']   = $phone;

        $add_details['remote_ip']    = $remote_ip;
        $add_details['guest']        = $username;
        $add_details['amount']       = $sell_price;
        $add_details['created_on']   = now();
        $add_details['last_updated'] = now();

        $DownloadAccess = false;
        // Check User Access Volume Level
        $v_param['volume_id']  = $volume->volume_id;
        $v_param['user_id']    = isset($user) ? $user->id : 0;
        $v_param['ip_address'] = $request->ip();

        $ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param, array('volume' => true));

        if (!empty($ua_volume_lvl[0])) {
            $DownloadAccess = $ua_volume_lvl[0]->volume_id;
        }

        if (!$DownloadAccess) {

            // User Access does not exist go for Transaction  and Update Status Pending (P)

            $add_details['status'] = 'P';
            $inquiry_id            = Article::AddFullTextInquiryOrder($add_details);

            $param['inquiry_id'] = $inquiry_id;
            $inquiry_order       = Article::GetFullTextInquiryOrder($param);
            $inquiry_order       = $inquiry_order[0];

            $issue = Article::where('article_id', $inquiry_order->article_id)->first();

            $param['nid']        = $issue->nid;
            $param['inquiry_id'] = $inquiry_order->inquiry_id;
            $param['status']     = 'P';

    //--------------------------MIGS Payment - Temparary Block-------------------------------------
            
           $migs['merchat_id']         = env('migs_id');
            $migs['order_id']           = "ePUB" . $inquiry_order->inquiry_id;
            $migs['amount']             = $inquiry_order->amount;
            $migs['currency_code']      = 'USD';
            $migs['return_url']         = "https://".$_SERVER['HTTP_HOST']."/full-text-inquiry-migs-response/". $migs['order_id'];   
            $migs['cancel_url']         = "https://".$_SERVER['HTTP_HOST']."/full-text-inquiry-migs-response/".$migs['order_id'];   

            $migs_obj = new MigsController;
            $responseCheck = $migs_obj->RequestMigsResponse($migs['order_id']);	
			
            $migs['session_id']         = $responseCheck->session->id;
            return view('migs', with(['migs' => $migs]));
		
    //--------------------------------------MIGS End---------------------------------------  
    //--------------------------Paypal Payment - Temparary Add Here-------------------------------
    /*         $paypal['paypalEnv']      = env('paypalEnv');
            $paypal['paypalURL']      = env('paypalURL');
            $paypal['business']       = env('email_business', '');
            $paypal['invoice']        = 'ePUB' . $inquiry_id;
            $paypal['item_name']      = 'Order# ePUB' . $inquiry_id;
            $paypal['amount']         = $inquiry_order->amount;
            $paypal['currency_code']  = 'USD';
            $paypal['paypalClientID'] = env('paypalClientID');
            $paypal['return']         = url("/full-text-inquiry-paypal-response/");
            return view('paypal', with(['paypal' => $paypal])); 
     */
	 //--------------------------Paypal Payment - End Here-------------------------------

        } else {
            // User Access exist Send Only Email and Update Status Emailed (E)

            $add_details['status']        = 'E';
            $inquiry_id                   = Article::AddFullTextInquiryOrder($add_details);
            $add_details['journal_title'] = $journal->title;

            $to      = $email;
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2') . ',' . env('email_support_2') . ',' . env('email_epub');
            $subject = "Eurekaselect: Epub Abstract Ahead of Print";

            SendSmtpMail('email_template.epub_full_text_inquiry_user_access_thanks', $add_details, $to, $from, $subject, 'Admin', $cc);

            $session_detail = $request->session()->get('session_detail');

            $detail['name']    = isset($request->name) ? $request->name : $session_detail[0]['name'];
            $detail['email']   = isset($request->email) ? $request->email : $session_detail[0]['email'];
            $detail['address'] = isset($request->address) ? $request->address : '';
            $detail['phone']   = isset($request->phone) ? $request->phone : '';

            $request->session()->forget('session_detail');
            $request->session()->push('session_detail', $detail);

            $node_meta = Meta::NodeMeta($journal->nid);

            if (empty($node_meta)) {
                $node_meta                = (object) $node_meta;
                $node_meta->description   = $journal->aims_and_scope;
                $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
                $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
            }

            $latest_issue = Issue::getcurrentissue($article->journal_id);
            $page_name    = 'full_text_inquiry_preview';

            $thankyou = true;

            $count_epub_article = Article::GetTrackList($article->journal_id, 1, 0)->count();
            $count_epub_abstract = Article::GetTrackList($article->journal_id, 4, 0)->count();

            return view('journal_menu', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'thankyou' => $thankyou, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]));
        }
    }

/*    public function FullTextInquiryMigsPayment($request, $inquiry_id) block by Imran Old Code
    {
        $param['inquiry_id'] = $inquiry_id;
        $inquiry_order       = Article::GetFullTextInquiryOrder($param);
        $inquiry_order       = $inquiry_order[0];

        $issue = Article::where('article_id', $inquiry_order->article_id)->first();

        $param['nid']        = $issue->nid;
        $param['inquiry_id'] = $inquiry_order->inquiry_id;
        $param['status']     = 'P';

//-----------------------------------MIGS Payment----------------------------------------------
        $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = "ePUB" . $inquiry_order->inquiry_id;
        $migs['amount']             = $inquiry_order->amount;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/full-text-inquiry-migs-response/". $migs['order_id'];   
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/full-text-inquiry-migs-response/".$migs['order_id'];   

        $migs_obj = new MigsController;
        $responseCheck = $migs_obj->RequestMigsResponse($migs['order_id']);
        $migs['session_id']         = $responseCheck->session->id;

        return view('migs', with(['migs' => $migs]));

    }*/

    public function FullTextInquiryMigsResponse(Request $request)
    {
        $inquiry_id = substr($request->inquiry_id, 4, strlen($request->inquiry_id));
        
        $paypal     = array();

        $param['inquiry_id'] = $inquiry_id;
        $inquiry_order       = Article::GetFullTextInquiryOrder($param);
        $inquiry_order       = $inquiry_order[0];
        $article             = Article::where('article_id', $inquiry_order->article_id)->first();
        $issue               = Issue::where('issue_id', $article->issue_id)->first();
        $volume              = Volume::where('volume_id', $article->volume_id)->first();
        $journal             = Journal::where('journal_id', $article->journal_id)->first();

        $detail['inquiry_id']    = $inquiry_order->inquiry_id;
        $detail['article_id']    = $inquiry_order->article_id;
        $detail['journal_title'] = $journal->title;
        $detail['volume_name']   = $volume->volume_name;
        $detail['article_title'] = $article->title;
        $detail['epub_price']    = $journal->epub_price;
        $detail['name']          = $inquiry_order->name;
        $detail['email']         = $inquiry_order->email;
        $detail['phone']         = $inquiry_order->phone;
        $detail['address']       = $inquiry_order->address;


        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($request->inquiry_id);
        
        if ($apiResponse->result == "SUCCESS") {
            for ($i = 0; $i < sizeof($apiResponse->transaction); $i++) {
				if(isset($apiResponse->transaction[$i]->response->acquirerCode)){
					
                  $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    if ($txnResponseCode == 00) {
            // Standard Receipt Data / Reponse of migs
                    $amount          = $apiResponse->transaction[$i]->transaction->amount;
                    $batchNo         = $apiResponse->transaction[$i]->transaction->acquirer->batch;
                    $message         = $apiResponse->transaction[$i]->response->acquirerMessage;
                    $version         = $apiResponse->transaction[$i]->version;
					$cardType        = $apiResponse->sourceOfFunds->type;
                    $orderInfo       = $apiResponse->transaction[$i]->order->id;
                    $receiptNo       = $apiResponse->transaction[$i]->transaction->receipt;
                    $merchantID      = $apiResponse->transaction[$i]->transaction->acquirer->merchantId;
                    $authorizeID     = $apiResponse->transaction[$i]->transaction->authorizationCode;
                    $merchTxnRef     = $apiResponse->transaction[$i]->order->id;
                    $transactionNo   = $apiResponse->transaction[$i]->transaction->acquirer->transactionId;
                    $acqResponseCode = $apiResponse->transaction[$i]->transaction->acquirer->id;
                    $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    $plain_message   = html_entity_decode($apiResponse->transaction[$i]->response->acquirerMessage, ENT_QUOTES, 'UTF-8');
            $result          = $apiResponse->result;
            $status          = $apiResponse->status;

            $message = 'The transaction Successfully Done';
            $to      = "zafar@benthamscience.net";
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2') . ',' . env('email_support_2');
            $subject = "ePub [ahead of print] Inquiry # ePUB " . $inquiry_id;

            SendSmtpMail('email_template.epub_full_text_inquiry', $detail, $to, $from, $subject, 'Admin', $cc);

            $message = 'Eurekaselect: ePUB Abstract Ahead of Print Order # ' . $inquiry_id;
            $to      = $inquiry_order->email;
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2') . ',' . env('email_support_2');
            $subject = "Epub Full Text Inquiry number # " . $inquiry_id . " (" . $message . ")";

            SendSmtpMail('email_template.epub_full_text_inquiry_thanks', $detail, $to, $from, $subject, 'Admin', $cc);

            $migs_transaction                = 'success';
            $update_inquiry['response_code'] = 0;
            $update_inquiry['status']        = "C";
            $update_inquiry['last_updated']  = now();
            $update_inquiry['email_status']     = 1;

            Article::UpdateFullTextInquiryOrder($inquiry_id, $update_inquiry);
                    }
                }
            }
        }

        elseif($apiResponse->result=="ERROR")
        {
                $migs_transaction = "cancel";
            $update_inquiry['status']       = "F";
            $update_inquiry['last_updated'] = now();

            Article::UpdateFullTextInquiryOrder($inquiry_id, $update_inquiry);

            $paypal['paypalEnv']      = env('paypalEnv');
            $paypal['paypalURL']      = env('paypalURL');
            $paypal['business']       = env('email_business', '');
            $paypal['invoice']        = 'ePUB' . $inquiry_id;
            $paypal['item_name']      = 'Order# ePUB' . $inquiry_id;
            $paypal['amount']         = $inquiry_order->amount;
            $paypal['currency_code']  = 'USD';
            $paypal['paypalClientID'] = env('paypalClientID');
            $paypal['return']         = url("/full-text-inquiry-paypal-response/");
        }

        $page_name = 'full_text_inquiry_preview';

        $session_detail = $request->session()->get('session_detail');
        if (!empty($session_detail)) {
            $detail['name']    = isset($session_detail[0]['name']) ? $session_detail[0]['name'] : '';
            $detail['address'] = isset($session_detail[0]['address']) ? $session_detail[0]['address'] : '';
            $detail['phone']   = isset($session_detail[0]['phone']) ? $session_detail[0]['phone'] : '';
        }

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        $latest_issue = Issue::getcurrentissue($article->journal_id);

        $count_epub_article = Article::GetTrackList($article->journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($article->journal_id, 4, 0)->count();

        return view('journal_menu', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'paypal' => $paypal, 'migs_transaction' => $migs_transaction, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]));
    }

    public function FullTextInquiryPaypalResponse(Request $request)
    {
        $param['inquiry_id'] = $inquiry_id = substr($request->invoice, 4, strlen($request->invoice));
        $inquiry_order       = Article::GetFullTextInquiryOrder($param);
        $inquiry_order       = $inquiry_order[0];
        $article             = Article::where('article_id', $inquiry_order->article_id)->first();
        $issue               = Issue::where('issue_id', $article->issue_id)->first();
        $volume              = Volume::where('volume_id', $article->volume_id)->first();
        $journal             = Journal::where('journal_id', $article->journal_id)->first();

        $detail['inquiry_id']    = $inquiry_order->inquiry_id;
        $detail['article_id']    = $inquiry_order->article_id;
        $detail['journal_title'] = $journal->title;
        $detail['volume_name']   = $volume->volume_name;
        $detail['article_title'] = $article->title;
        $detail['epub_price']    = $journal->epub_price;
        $detail['name']          = $inquiry_order->name;
        $detail['email']         = $inquiry_order->email;
        $detail['phone']         = $inquiry_order->phone;
        $detail['address']       = $inquiry_order->address;

        $paypal_obj = new PaypalExpress;
        $paymentID  = $request->paymentID;
        $token      = $request->token;
        $payerID    = $request->payerID;
        $productID  = $request->invoice;
        // Validate transaction via PayPal API
        $paymentCheck = $paypal_obj->PaypalValidate($paymentID, $token, $payerID, $productID);

        // If the payment is valid and approved
        if ($paymentCheck && $paymentCheck->state == 'approved') {
            // Paypal Payment Done Successfully
            $status  = "C";
            $to      = "zafar@benthamscience.net";
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2') . ',' . env('email_support_2') . ',' . env('email_epub');
            $subject = "ePub [ahead of print] Inquiry # ePUB " . $inquiry_id;

            SendSmtpMail('email_template.epub_full_text_inquiry', $detail, $to, $from, $subject, 'Admin', $cc);

            $message = 'Eurekaselect: ePUB Abstract Ahead of Print Order # ' . $inquiry_id;
            $to      = $inquiry_order->email;
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2') . ',' . env('email_support_2');
            $subject = "Epub Full Text Inquiry number # " . $inquiry_id . " (" . $message . ")";

            SendSmtpMail('email_template.epub_full_text_inquiry_thanks', $detail, $to, $from, $subject, 'Admin', $cc);

            $paypal_transaction                 = 'success';
            $update_inquiry['response_code']    = 0;
            $update_inquiry['response_message'] = $paymentCheck->state . " - " . $paymentCheck->transactions[0]->related_resources[0]->sale->id;
            $update_inquiry['status']           = "C";
            $update_inquiry['email_status']     = 1;
        } else {
            $update_inquiry['response_code'] = "C";
            $update_inquiry['status']        = "F";

            $paypal_transaction = 'failed';
        }

        $update_inquiry['last_updated'] = now();
        $inquiry_id                     = Article::UpdateFullTextInquiryOrder($inquiry_id, $update_inquiry);

        $page_name = 'full_text_inquiry_preview';

        $session_detail = $request->session()->get('session_detail');
        if (!empty($session_detail)) {
            $detail['name']    = isset($session_detail[0]['name']) ? $session_detail[0]['name'] : '';
            $detail['address'] = isset($session_detail[0]['address']) ? $session_detail[0]['address'] : '';
            $detail['phone']   = isset($session_detail[0]['phone']) ? $session_detail[0]['phone'] : '';
        }

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        $latest_issue = Issue::getcurrentissue($article->journal_id);

        $count_epub_article = Article::GetTrackList($article->journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($article->journal_id, 4, 0)->count();

        return view('journal_menu', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'page_name' => $page_name, 'detail' => $detail, 'paypal_transaction' => $paypal_transaction, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract]));
    }

    public function RentalRequest(Request $request, $article_id)
    {

        if (isset($request->rental_request_form) && $request->rental_request_form == 'Preview') {
            $validator = Validator::make(
                $request->all(),
                [
                    'email'                => 'required|string|email|max:255',
                    'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.']);

            if ($validator->fails()) {
                return $this->RentalRequestForm($request, $article_id, $validator);
            } else {
                return $this->RentalRequestPreview($request, $article_id);
            }
        } elseif (isset($request->article_rental_purchase_form) && $request->article_rental_purchase_form == 'Submit') {
            return $this->RentalRequestSubmit($request, $article_id);
        } else {
            return $this->RentalRequestForm($request, $article_id);
        }
    }

    public function RentalRequestForm($request, $article_id, $validator = null)
    {
        $article = Article::where('article_id', $article_id)->first();
        $volume  = Volume::where('volume_id', $article->volume_id)->first();
        $issue   = Issue::where('issue_id', $article->issue_id)->first();
        $journal = Journal::where('journal_id', $article->journal_id)->first();
        $rental  = Journal::GetJournalRentalDetail($article->journal_id, 'journal_id');
        $user    = Auth::user();

        if (isset(Auth::user()->id)) {
            $session_detail         = $request->session()->get('session_detail');
            $detail['display_name'] = isset($user->display_name) ? $user->display_name : '';
            $detail['email']        = isset($user->email) ? $user->email : '';
            $detail['country']      = isset($user->country) ? $user->country : '';
            $detail['rental']       = isset($session_detail['rental']) ? $session_detail['rental'] : '';
        } elseif ($request->session()->has('session_detail')) {

            $session_detail = $request->session()->get('session_detail');

            $detail['display_name'] = isset($session_detail['display_name']) ? $session_detail['display_name'] : '';
            $detail['email']        = isset($session_detail['email']) ? $session_detail['email'] : '';
            $detail['country']      = isset($session_detail['country']) ? $session_detail['country'] : '';
            $detail['rental']       = isset($session_detail['rental']) ? $session_detail['rental'] : '';
        } else {
            $detail['display_name']          = '';
            $detail['email']                 = '';
            $detail['user_type']             = '';
            $detail['password']              = '';
            $detail['password_confirmation'] = '';
            $detail['country']               = '';
            $detail['rental']                = '';
        }

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        $latest_issue = Issue::getcurrentissue($article->journal_id);
        $country      = Country::GetCountryList();

        if (!empty($validator) && $validator->fails()) {
            return view('form.rental_request', with(['journal' => $journal, 'rental' => $rental, 'volume' => $volume, 'issue' => $issue, 'article' => $article, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'country' => $country]))->withErrors($validator);
        } else {
            return view('form.rental_request', with(['journal' => $journal, 'rental' => $rental, 'volume' => $volume, 'issue' => $issue, 'article' => $article, 'detail' => $detail, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue, 'country' => $country]));
        }
    }

    public function RentalRequestPreview(Request $request, $article_id)
    {
        $detail = array();
        if ($request->session()->has('session_detail')) {
            $session_detail         = $request->session()->get('session_detail');
            $detail['display_name'] = isset($request->display_name) ? $request->display_name : $session_detail['display_name'];
            $detail['email']        = isset($request->email) ? $request->email : $session_detail['email'];
            $detail['country']      = isset($request->country) ? $request->country : $session_detail['country'];
            $detail['rental']       = isset($request->rental) ? $request->rental : $session_detail['rental'];
            $country                = Country::GetCountryList("", $request->country);
            $detail['country_name'] = ucfirst(strtolower($country->name));
        } else {
            $detail['display_name'] = isset($request->display_name) ? $request->display_name : '';
            $detail['email']        = isset($request->email) ? $request->email : '';
            $detail['country']      = isset($request->country) ? $request->country : '';
            $detail['rental']       = isset($request->rental) ? $request->rental : '';
            $country                = Country::GetCountryList("", $request->country);
            $detail['country_name'] = ucfirst(strtolower($country->name));
        }

        $request->session()->forget('session_detail');
        if (!empty($detail)) {
            session(['session_detail' => $detail]);
        }

        $article = Article::where('article_id', $article_id)->first();
        $issue   = Issue::where('issue_id', $article->issue_id)->first();
        $volume  = Volume::where('volume_id', $article->volume_id)->first();
        $journal = Journal::where('journal_id', $article->journal_id)->first();
        $rental  = Journal::GetJournalRentalDetail($request->rental, 'rental_id');

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }
        $latest_issue = Issue::getcurrentissue($article->journal_id);

        return view('form.rental_request_preview', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'detail' => $detail, 'rental' => $rental, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue]));
    }

    public function RentalRequestSubmit(Request $request, $article_id)
    {
        try {
// try transaction start here for data integrity
            DB::beginTransaction();

            $user     = Auth::user();
            $username = '';
            $user_id  = 0;
            if ($user) {
                $username = $user->name;
                $user_id  = $user->id;
            }

            //-------------------Insert into rental order Table---------------

            $journal_rental = Journal::GetJournalRentalDetail($request->rental, 'rental_id');
            $journal_rental = $journal_rental[0];

            $timenow      = time();

            $current_time = date("Y-m-d H:i:s");

            
            $timefrom=date('Y-m-d H:i:s',strtotime('+'.$journal_rental->rental_hours.' hour',strtotime($current_time)));

            $from_time = strtotime($timefrom);

            $add_details['article_id']       = $article_id;
            $add_details['rental_id']        = $request->rental;
            $add_details['user_name']        = $request->display_name;
            $add_details['user_email']       = $request->email;
            $add_details['user_country']     = $request->country;
            $add_details['user_id']          = $user_id;
            $add_details['guest']            = $username;
            $add_details['rental_date_from'] = $timenow;
            $add_details['rental_date_to']   = $from_time;
            $add_details['created_on']       = time();
            $add_details['last_modified']    = time();
            $add_details['order_status']     = 'I';
            $add_details['ip']               = ip2long($request->ip());
            $add_details['rental_status']    = 'I';

            $rental_order_id = Article::AddRentalOrder($add_details);

            $add_log = array(
                'content_id'      => $rental_order_id,
                'content_type_id' => config('constants.log_content_types.Article_Rental_Order'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_details),
                'created_dated'   => time(),
                'created_by'      => $user_id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }
//-----------------------------------MIGS Payment (Block Temparary)-------------------------------

        $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = 'RA:' . $rental_order_id;
        $migs['amount']             = $journal_rental->rental_price;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/rental-request-migs-response/". $migs['order_id'];   
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/rental-request-migs-response/".$migs['order_id'];   

        $migs_obj = new MigsController;
        $responseCheck = $migs_obj->RequestMigsResponse($migs['order_id']);
        $migs['session_id']         = $responseCheck->session->id;


        return view('migs', with(['migs' => $migs]));

//-----------------------------------MIGS End-------------------------------
    //--------------------------Paypal Payment - Temparary Add Here-------------------------------
    /*         $paypal['paypalEnv']      = env('paypalEnv');
            $paypal['paypalURL']      = env('paypalURL');
            $paypal['business']       = env('email_business', '');
            $paypal['invoice']        = 'RA:' . $rental_order_id;
            $paypal['amount']         = $journal_rental->rental_price;
            $paypal['currency_code']  = 'USD';
            $paypal['paypalClientID'] = env('paypalClientID');
            $paypal['return']         = url("/rental-request-paypal-response/");
            return view('paypal', with(['paypal' => $paypal]));
     */
	 //--------------------------Paypal Payment - End Here-------------------------------


    }
//-----------------------------------MIGS Payment Response---------------------------------------
    public function RentalRequestMigsResponse(Request $request)
    {
        $param['rental_order_id'] = $rental_order_id = substr($request->rental_order_id, 3, strlen($request->rental_order_id));

        $article_rental           = Article::GetArticleRentalDetail($param);
        $article_rental           = $article_rental[0];

        $detail['order_id']      = $article_rental->rental_order_id;
        $detail['journal']       = $article_rental->title;
        $detail['journal_id']    = $article_rental->journal_id;
        $detail['volume']        = $article_rental->volume;
        $detail['issue']         = $article_rental->issue;
        $detail['article_title'] = $article_rental->article;
        $detail['article_id']    = $article_rental->article_id;
        $detail['display_name']  = $article_rental->display_name;
        $detail['email']         = $article_rental->email;
        $detail['country']       = $article_rental->user_country;
        $detail['hour']          = $article_rental->rental_hours;
        $detail['price']         = $article_rental->rental_price;

        $rental = Journal::GetJournalRentalDetail($article_rental->rental_id, 'rental_id');

        $latest_issue = Issue::getcurrentissue($article_rental->journal_id);
        $article      = Article::where('article_id', $article_rental->article_id)->first();
        $issue        = Issue::where('issue_id', $article->issue_id)->first();
        $volume       = Volume::where('volume_id', $article->volume_id)->first();
        $journal      = Journal::where('journal_id', $article->journal_id)->first();

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        //-----------------migs reponse check---------------------------
        if ($article_rental->order_status == 'C') {
            return Redirect::to('journal/' . $article_rental->journal_id);
        }

        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($request->rental_order_id);
        if($apiResponse->result=="SUCCESS")
        {
            for($i=0;$i<sizeof($apiResponse->transaction);$i++)
            {
				if(isset($apiResponse->transaction[$i]->response->acquirerCode)){
                  $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
              if($txnResponseCode==00)
              {
                // Standard Receipt Data / Reponse of migs
                    $amount          = $apiResponse->transaction[$i]->transaction->amount;
                    $batchNo         = $apiResponse->transaction[$i]->transaction->acquirer->batch;
                    $message         = $apiResponse->transaction[$i]->response->acquirerMessage;
                    $version         = $apiResponse->transaction[$i]->version;
                  $cardType        = $apiResponse->sourceOfFunds->type;
                    $orderInfo       = $apiResponse->transaction[$i]->order->id;
                    $receiptNo       = $apiResponse->transaction[$i]->transaction->receipt;
                    $merchantID      = $apiResponse->transaction[$i]->transaction->acquirer->merchantId;
                    $authorizeID     = $apiResponse->transaction[$i]->transaction->authorizationCode;
                    $merchTxnRef     = $apiResponse->transaction[$i]->order->id;
                    $transactionNo   = $apiResponse->transaction[$i]->transaction->acquirer->transactionId;
                    $acqResponseCode = $apiResponse->transaction[$i]->transaction->acquirer->id;
                    $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    $plain_message   = html_entity_decode($apiResponse->transaction[$i]->response->acquirerMessage, ENT_QUOTES, 'UTF-8');
                  $result          = $apiResponse->result;
                  $status          = $apiResponse->status;

            try {
// try transaction start here for data integrity
                DB::beginTransaction();

                $user     = Auth::user();
                $username = '';
                $user_id  = 0;
                if ($user) {
                    $username = $user->name;
                    $user_id  = $user->id;
                } else {
                    //if Doesnot exist than check/create new User
                    $user_details = (array) UserController::CheckAddUserDetails($article_rental);

                    $user_id = $user_details['id'];
                    if (isset($user_details['password_text'])) {
                        $detail['name']     = $user_details['name'];
                        $detail['password'] = $user_details['password_text'];

                        $user_data = array(
                            'name'     => $detail['name'],
                            'password' => $detail['password'],
                        );

                        if (!Auth::attempt($user_data)) {

                            return redirect()->back();
                        }

                        if (Auth::check()) {
                            // return redirect('users/details');
                        }
                    } else {
                        $detail['name'] = $user_details['name'];
                    }


                    $detail['display_name'] = $user_details['display_name'];
                    $detail['email']        = $user_details['email'];
                }
                $param                 = encrypt(array('readpdf', $article_rental->article_id, config('constants.admin.token')));
                $detail['rental_link'] = route('article', ['article_id' => $article_rental->article_id, 'param' => $param]);

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_xolva_2') . ',' . env('email_support_2');
                $subject = "Rental Article Order Number # " . $rental_order_id . "";

                SendSmtpMail('email_template.rental_article_successfull', $detail, $to, $from, $subject, 'Admin', $cc);

                $migs_transaction                  = 'Success';
                $update_rental['user_id']          = $user_id;
                    $update_rental['response_code']    = $txnResponseCode;
                    $update_rental['response_message'] = $plain_message;
                    $update_rental['transaction_no']   = $transactionNo;
                $update_rental['email_status']     = 1;
                $update_rental['order_status']     = "C";
                $update_rental['last_modified']    = time();
                $update_rental['rental_status']    = 'S';

                Article::UpdateRentalOrder($rental_order_id, $update_rental);

                $country                = Country::GetCountryList("", $detail['country']);
                $detail['country_name'] = ucfirst(strtolower($country->name));

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }

            return view('form.rental_request_preview', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'rental' => $rental, 'detail' => $detail, 'migs_transaction' => $migs_transaction, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue]));
                    }
                }
            }
            }
        elseif($apiResponse->result=="ERROR")
        {

            $migs_transaction               = 'Cancel';
            $update_rental['rental_status'] = 'N';
            $update_rental['order_status']  = 'N';
            Article::UpdateRentalOrder($rental_order_id, $update_rental);

            $paypal['paypalEnv']      = env('paypalEnv');
            $paypal['paypalURL']      = env('paypalURL');
            $paypal['business']       = env('email_business', '');
            $paypal['invoice']        = 'RA:' . $rental_order_id;
            $paypal['amount']         = $article_rental->rental_price;
            $paypal['currency_code']  = 'USD';
            $paypal['paypalClientID'] = env('paypalClientID');
            $paypal['return']         = url("/rental-request-paypal-response/");

            if ($request->session()->has('session_detail')) {
                $session_detail         = $request->session()->get('session_detail');
                $detail['display_name'] = isset($request->display_name) ? $request->display_name : $session_detail['display_name'];
                $detail['email']        = isset($request->email) ? $request->email : $session_detail['email'];
                $detail['country']      = isset($request->country) ? $request->country : $session_detail['country'];
                $detail['rental']       = isset($request->rental) ? $request->rental : $session_detail['rental'];
                $country                = Country::GetCountryList("", $article_rental->user_country);

                $detail['country_name'] = ucfirst(strtolower($country->name));
            }

            return view('form.rental_request_preview', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'detail' => $detail, 'rental' => $rental, 'paypal' => $paypal, 'migs_transaction' => $migs_transaction, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue]));
        }
    }

    public function RentalRequestPaypalResponse(Request $request)
    {
        try {
// try transaction start here for data integrity
            $paypal = array();

            DB::beginTransaction();

            $param['rental_order_id'] = $rental_order_id = substr($request->invoice, 3, strlen($request->invoice));
            $article_rental           = Article::GetArticleRentalDetail($param);
            $article_rental           = $article_rental[0];

            $detail['order_id']      = $article_rental->rental_order_id;
            $detail['journal']       = $article_rental->title;
            $detail['journal_id']    = $article_rental->journal_id;
            $detail['volume']        = $article_rental->volume;
            $detail['issue']         = $article_rental->issue;
            $detail['article_title'] = $article_rental->article;
            $detail['article_id']    = $article_rental->article_id;
            $detail['display_name']  = $article_rental->display_name;
            $detail['email']         = $article_rental->email;
            $detail['country']       = $article_rental->country;
            $detail['hour']          = $article_rental->rental_hours;
            $detail['price']         = $article_rental->rental_price;

            if ($request->session()->has('session_detail')) {
                $session_detail = $request->session()->get('session_detail');

                $detail['display_name'] = isset($request->display_name) ? $request->display_name : $session_detail['display_name'];
                $detail['email']        = isset($request->email) ? $request->email : $session_detail['email'];
                $detail['country']      = isset($request->country) ? $request->country : $session_detail['country'];
                $detail['rental']       = isset($request->rental) ? $request->rental : $session_detail['rental'];
            }
            $rental                 = Journal::GetJournalRentalDetail($article_rental->rental_id, 'rental_id');
            $country                = Country::GetCountryList("", $detail['country']);
            $detail['country_name'] = ucfirst(strtolower($country->name));

            if ($article_rental->order_status == 'C') {
                return Redirect::to('journal/' . $article_rental->journal_id);
            }

            $paypal_obj = new PaypalExpress;

            $paymentID = $request->paymentID;
            $token     = $request->token;
            $payerID   = $request->payerID;
            $productID = $request->invoice;
            // Validate transaction via PayPal API
            $paymentCheck = $paypal_obj->PaypalValidate($paymentID, $token, $payerID, $productID);

            // If the payment is valid and approved
            if ($paymentCheck && $paymentCheck->state == 'approved') {
                $user     = Auth::user();
                $username = '';
                $user_id  = 0;
                if ($user) {
                    $username = $user->name;
                    $user_id  = $user->id;
                }

                $detail['rental_link'] = url("/article/" . $article_rental->article_id);

                // Paypal Payment Done Successfully

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_xolva_2') . ',' . env('email_support_2');
                $subject = "Rental Article Order Number # " . $rental_order_id . "";

                SendSmtpMail('email_template.rental_article_successfull', $detail, $to, $from, $subject, 'Admin', $cc);

                $paypal_transaction             = 'Success';
                $update_rental['response_message'] = $paymentCheck->state;
                $update_rental['transaction_no']   = $paymentCheck->transactions[0]->related_resources[0]->sale->id;
                $update_rental['response_code'] = 0;
                $update_rental['order_status']  = "C";
                $update_rental['user_id']       = $user_id;
                $update_rental['rental_status'] = 'S';
            } else {
                $update_rental['response_code'] = "C";
                $update_rental['order_status']  = "F";
                $update_rental['rental_status'] = 'N';

                $update_rental['response_message'] = 'Transaction Failed with Paypal';
                $paypal_transaction                = 'Failed';
            }
            $update_rental['last_modified'] = time();

            Article::UpdateRentalOrder($rental_order_id, $update_rental);

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

        $latest_issue = Issue::getcurrentissue($article_rental->journal_id);
        $article      = Article::where('article_id', $article_rental->article_id)->first();
        $issue        = Issue::where('issue_id', $article->issue_id)->first();
        $volume       = Volume::where('volume_id', $article->volume_id)->first();
        $journal      = Journal::where('journal_id', $article->journal_id)->first();

        $node_meta = Meta::NodeMeta($journal->nid);
        if (empty($node_meta)) {
            $node_meta                = (object) $node_meta;
            $node_meta->description   = $journal->aims_and_scope;
            $node_meta->keywords      = strip_tags($journal->title . ',' . $journal->subtitle . ',' . $journal->keyword . ',' . $journal->eic_detail . ',' . $journal->impact_factor . ',' . $journal->ranking_and_category . ',scientific journal,STM publisher');
            $node_meta->canonical_url = $url = 'http://' . $_SERVER['HTTP_HOST'] . '/journal/' . $journal->journal_id;
        }

        return view('form.rental_request_preview', with(['journal' => $journal, 'issue' => $issue, 'volume' => $volume, 'article' => $article, 'detail' => $detail, 'rental' => $rental, 'paypal' => $paypal, 'paypal_transaction' => $paypal_transaction, 'node_meta' => $node_meta, 'latest_issue' => $latest_issue]));
    }

    public function RentalAccessComplete(Request $request)
    {
        try {
// try transaction start here for data integrity
            DB::beginTransaction();

            $rental_order_id      = $request->rental_order_id;
            $sparam['user_id']    = session()->get('user_id');
            $sparam['article_id'] = $request->article_id;

            $rental = Article::CheckArticleRentalAccess($sparam);
            //dd($rental); // echo 1; return;
            if (count($rental) < 1) {
                $update_rental['rental_status'] = 'C';
                $update_rental['last_modified'] = time();

                Article::UpdateRentalOrder($rental_order_id, $update_rental);
            }

            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return back();
        }

        return Redirect::to('/article/' . $request->article_id);
    }

    /*
    get Article SGML
     */

    public function article_GetSGML($article_id)
    {

        $article_obj = Article::GetArticleDetail($article_id);

        $SGMFile = str_replace(".pdf", "", $article_obj->file_name) . ".sgm";
        //print("File Name = ".$SGMFile); exit;
        //$fh = fopen($SGMFile, 'w') or die("can't open file");
        //exit;
        $str = "<!DOCTYPE header SYSTEM \"SSSH2.dtd\" >\r\n";
        $str .= "<header>\r\n";
        $str .= "<pinfo>\r\n";
        $str .= "<pnm>Bentham Science Publishers\r\n";
        if ($article_obj->is_epub == 1) {
            $str .= "<loc>epub\r\n";
        } else if ($article_obj->is_epub == 2) {
            $str .= "<loc>quick track\r\n";
        } else if ($article_obj->is_epub == 3) {
            $str .= "<loc>express track\r\n";
        } else {
            $str .= "<loc>direct\r\n";
        }
        $str .= "<jinfo>\r\n";
        $str .= "<jtl>" . $article_obj->journal_title . "\r\n";
        $str .= "<jsbt>\r\n";
        $str .= "<issn>" . $article_obj->issn . "\r\n";
        $str .= "<pubinfo>\r\n";
        if ($article_obj->is_epub == 1) {
            $str .= "<vid>999\r\n";
            $str .= "<iid>999\r\n";
            $str .= "<cd>" . getMonthFromId(Date('m', $article_obj->created)) . " 9999\r\n";
        } else if ($article_obj->is_epub == 2) {
            $str .= "<vid>888\r\n";
            $str .= "<iid>888\r\n";
            $str .= "<cd>" . getMonthFromId(Date('m', $article_obj->created)) . " 8888\r\n";
        } else if ($article_obj->is_epub == 3) {
            $str .= "<vid>777\r\n";
            $str .= "<iid>777\r\n";
            $str .= "<cd>" . getMonthFromId(Date('m', $article_obj->created)) . " 7777\r\n";
        } else {
            $str .= "<vid>" . $article_obj->volume . "\r\n";
            $str .= "<iid>" . $article_obj->issue . "\r\n";

            $yearName = DB::table('year')->select('year')->where('id', '=', $article_obj->year_id)->first();
            $str .= "<cd>" . getMonthFromId($article_obj->month_id) . " " . $yearName->year . "\r\n";
        }

        $str .= "<genhdr language=\"EN\">\r\n";
        $str .= "<artinfo>\r\n";
        $str .= "<altid>\r\n";

        if ($article_obj->type_name == "Review Article") {
            $str .= "<artty type=RV>\r\n";
        } else if ($article_obj->type_name == 'Research Article') {
            $str .= "<artty type=RA>\r\n";
        } else if ($article_obj->type_name == 'Biography') {
            $str .= "<artty type=Biography>\r\n";
        } else if ($article_obj->type_name == 'Book Reviews') {
            $str .= "<artty type=BR>\r\n";
        } else if ($article_obj->type_name == 'Case Studies') {
            $str .= "<artty type=CS>\r\n";
        } else if ($article_obj->type_name == 'Case Report') {
            $str .= "<artty type=CR>\r\n";
        } else if ($article_obj->type_name == 'Clinical Trial') {
            $str .= "<artty type=CT>\r\n";
        } else if ($article_obj->type_name == 'Commentary') {
            $str .= "<artty type=CO>\r\n";
        } else if ($article_obj->type_name == 'Erratum') {
            $str .= "<artty type=ER>\r\n";
        } else if ($article_obj->type_name == 'Letter') {
            $str .= "<artty type=LE>\r\n";
        } else if ($article_obj->type_name == 'Opinion Article') {
            $str .= "<artty type=OP>\r\n";
        } else if ($article_obj->type_name == 'Patent Selections') {
            $str .= "<artty type=PS>\r\n";
        } else if ($article_obj->type_name == 'Study Protocols') {
            $str .= "<artty type=SP>\r\n";
        } else if ($article_obj->type_name == 'Editorial') {
            $str .= "<artty type=ED>\r\n";
        } else if ($article_obj->type_name == 'Preface') {
            $str .= "<artty type=PF>\r\n";
        } else if ($article_obj->type_name == 'Clinical Perspective') {
            $str .= "<artty type=CP>\r\n";
        }

        $str .= "<ppct count =\"" . $article_obj->page_count . "\">\r\n";
        $str .= "<ppf>" . $article_obj->first_page . "\r\n";
        $str .= "<ppl>" . $article_obj->last_page . "\r\n";
        if (($article_obj->is_epub == 1) || ($article_obj->is_epub == 2) || ($article_obj->is_epub == 3)) {
            $str .= "<crn>" . str_replace(".pdf", "", $article_obj->file_name) . "\r\n";
        } else {
            $str .= "<crn>Copyright (c) " . Date("Y") . " Bentham Science Publishers\r\n";
        }
        $str .= "<atl>" . str_replace("&amp;amp;", "&", htmlentities($article_obj->title, ENT_QUOTES, 'UTF-8')) . "\r\n";
        $str .= "<aug>\r\n";

        //Get author data

        $result_authors = Author::getAuthorDataById($article_id, 'article_id');
        $strAff;
        if (!empty($result_authors)) {
            foreach ($result_authors as $author) {

                $str .= "<au>\r\n";
                $str .= "<fnms>" . $author->first_name . "</fnms>\r\n";
                $str .= "<inits>" . $author->initials . "</inits>\r\n";
                $str .= "<snm>" . $author->last_name . "</snm>\r\n";

                if ($author->country == '0') {
                    $country = "";
                } else {
                }

                if ((trim($author->web_view) != "")) {
                    $str .= "<aff>" . rtrim($author->web_view, ',') . "</aff>\r\n";
                } else if (trim($author->author_affiliation) != "") {
                    $str .= "<aff>" . rtrim($author->author_affiliation, ',') . "</aff>\r\n";
                } else if (trim($author->country) != "") {
                    $str .= "<aff>" . $author->country . "</aff>\r\n";
                } else {
                    $str .= "<aff></aff>\r\n";
                }

                $str .= "</au>\r\n";
            }
        }

        $str .= "</aug>\r\n";
        $str .= "<abs>\r\n";
        $str .= "<p>\r\n";
        $str .= str_replace("&amp;amp;", "&", htmlentities($article_obj->abstract, ENT_QUOTES, 'UTF-8')) . "\r\n";
        $str .= "</p>\r\n";
        $str .= "</abs>\r\n";
        $str .= "<doi>" . $article_obj->doi . "</doi>\r\n";

        //Get keyword data
        $str .= "<kwdg>\r\n";

        $result_keywords = Keywords::getKeywordDataById($article_id, 'article_id');
        if (!empty($result_keywords)) {
            foreach ($result_keywords as $data) {
                $str .= "<kwd>" . ltrim(str_replace("&amp;amp;", "&", htmlentities($data->keyword, ENT_QUOTES, 'UTF-8'))) . "</kwd>\r\n";
            }
        }

        $str .= "</kwdg>\r\n";

        $str .= "</header>\r\n";

        header('Cache-Control: must-revalidate');
        header("Content-Type: application/xml");

        header("Content-Disposition: attachment; filename=\"{$SGMFile}\"");
        print($str);
        exit;
    }

    public function DeleteArticleFile(Request $request, $article_id, $file_type)
    {
        $user = Auth::user();
        //-----------------------------Insert into log table-----------------------------------
        $article = Article::GetArticleById($article_id);
        $log     = (array) $article;
        $add_log = array(
            'content_id'      => $article_id,
            'content_type_id' => config('constants.log_content_types.Article'),
            'action'          => config('constants.log_action_types.delete_file'),
            'log_data'        => json_encode($log),
            'created_dated'   => time(),
            'created_by'      => Auth::user()->id,
            'ip'              => ip2long($request->ip()),
        );
        $log = Log::AddLog($add_log);
        //--------------------------------------------------------------
        if ($file_type == "mobi_filename") {
            $filename = config('constants.admin.root_path') . $article->file_path . 'prc/' . basename($article->prc_filename, '.prc') . '.mobi';

            if (file_exists($filename)) {
                File::delete($filename);
            }
        } else {
            $update_article['article_id']    = $article_id;
            $update_article[$file_type]      = null;
            $update_article['last_modified'] = time();
            $update_article['updated_by']    = $user->id;

            Article::where('article_id', $article_id)->update($update_article);
        }
        return redirect()->back();
    }

    //-------------Article-Reprint-Eprint-Order-----------------//
    public function EprintReprintOrder(Request $request, $type, $article_id = null)
    {
        $article        = null;
        $thankyou       = false;
        $journal_search = null;
        if (!empty($article_id)) {
            $this->validate($request, [
                'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.']);

            $article = Article::GetArticleList(array('article_id' => $article_id), array('volume' => true, 'issue' => true));
            $article = $article[0];

            if ($request->back == true) {
                $request->request->add(['reprint_copies_select' => $rpc = $request->preview['reprint_copies']]); //add request
                if ($rpc != 100 && $rpc != 200 && $rpc != 300 && $rpc != 400 && $rpc != 500) {
                    $request->request->add(['reprint_copies_select' => 'other']); //add request
                }

                return Redirect::back()->withInput($request->all());
            } elseif ($request->submit == true) {
                $preview = $request->preview;
                if ($type == 'eprint') {
                    $preview['eprint_copies'] = $preview['reprint_copies'];
                    unset($preview['reprint_copies']);

                    $preview['eprint_pages'] = $article->page_count;
                } elseif ($type == 'reprint') {
                    $preview['reprint_pages'] = $article->page_count;
                }

                $preview['article_id']    = $article->article_id;
                $preview['journal_id']    = $article->journal_id;
                $preview['journal_type']  = $article->journal_type;
                $preview['article_title'] = $article->title;

                $preview['last_updated'] = now();
                $preview['status']       = 'E';
                $preview['remote_ip']    = $request->ip();
                $preview['guest']        = isset(Auth::user()->name) ? Auth::user()->name : 0;
                $preview['pk_id']        = Article::AddReprint($preview, $type);
                $preview['subtitle']     = $article->subtitle;
                $preview['volume_name']  = $article->volume_name;
                $preview['issue_title']  = $article->issue_title;
                $preview['page_count']   = $article->page_count;
                $preview['type']         = $type;

                $to   = $preview['email'];
                $from = env('email_admin', '');
                $cc   = env('email_xolva_2') . ',' . env('email_support_2');

                if ($type == 'eprint') {
                    $subject = "ePrint Inquiry number # " . $preview['pk_id'];
                } elseif ($type == 'reprint') {
                    $subject = "Reprint Inquiry number # " . $preview['pk_id'];
                }

                SendSmtpMail('email_template.eprint_reprint_order', $preview, $to, $from, $subject, 'Admin', $cc);

                $thankyou = true;
            }
        } else {
            if ($request->ajx_search != null && $request->ajx_search == true) {
                return $this->getSearch($request);
            } elseif ($request->search == true) {
                return Redirect::to('order/' . $type . '/' . $request->article_id);
            } else {
                $journal_search = Journal::GetJournalTitle();
            }
        }
        $country = Country::GetCountryList();
        $preview = $request->preview;

        return View::make('form.form_print_order', with(['journal_search' => $journal_search, 'country' => $country, 'type' => $type, 'article' => $article, 'preview' => $preview, 'thankyou' => $thankyou]));
    }

    public function getSearch($request)
    {
        if ($request->module == 'volume') {
            if (!empty($request->journal_id)) {
                $p['journal_id'] = $request->journal_id;
                return response()->json(array('volume_search' => Volume::GetVolumeTitleById($p)), 200);
            }
        }
        if ($request->module == 'issue') {
            if (!empty($request->volume_id)) {
                $p['volume_id'] = $request->volume_id;
                return response()->json(array('issue_search' => Issue::GetIssueTitleById($p)), 200);
            }
        }

        if ($request->module == 'article') {
            if (!empty($request->issue_id)) {
                $p['issue_id'] = $request->issue_id;
                $p['paginate'] = "All";
                return response()->json(array('article_search' => Article::GetArticleList($p)), 200);
            }
        }

        if ($request->module == 'rental') {
            if (!empty($request->journal_id)) {
                return response()->json(array('rental_detail' => Journal::GetJournalRentalDetail($request->journal_id, 'journal_id')), 200);
            }
        }
    }

    public function AddAccessDenail($DownloadAccess, $journal_id, $article_id)
    {
        $user_type = "";
        if (session()->has('ip_base_access') || session()->has('user_base_access')) {
            if (!$DownloadAccess) {
                $access_user_data = session()->get('access_user_data');

                if (!empty($access_user_data[0])) {
                    $user = User::where('id', $access_user_data[0]->user_id)->first();

                    if (!empty($user) && ($user->user_type == 'Org')) {
                        $access_type_id = $access_user_data[0]->access_type_id;

                        if ($access_type_id == 333 || $access_type_id == 777) //corporate
                        {
                            $user_type = 'C';
                        } elseif ($access_type_id == 111 || $access_type_id == 222 || $access_type_id == 888) //trial
                        {
                            $user_type = 'T';
                        } elseif ($access_type_id == 444 || $access_type_id == 555 || $access_type_id == 666) //restricted Token
                        {
                            $user_type = 'R';
                        }

                        if ($user_type != "") {
                            $access_denail_data['jid']        = $journal_id;
                            $access_denail_data['aid']        = $article_id;
                            $access_denail_data['catid']      = 1;
                            $access_denail_data['userid']     = $user->id;
                            $access_denail_data['user_type']  = $user_type;
                            $access_denail_data['created_on'] = time();
                            $access_denail_data['ip_address'] = \Request::ip();

                            UserAccess::InsertArticleAccessDenail($access_denail_data);
                        }
                    }
                }
            }
        }
    }

    public function CheckUserAccessOnArticle($request, $article_detail, $user_access, $restricted_user_access_key, $content_download_type, $clientIP, $user_id)
    {
        if (session()->has('ip_base_access') || session()->has('user_base_access')) {
            $volume_id  = $article_detail->volume_id;
            $issue_id   = $article_detail->issue_id;
            $article_id = $article_detail->article_id;

            // Check User Access Trail (Trail) Volume Level
            $v_param['access_type_id'] = 111;
            $v_param['access_on']      = 'journal_volume';
            $v_param['user_id']        = session()->get('user_id');
            $v_param['ip_address']     = $request->ip();
            $v_param['volume_id']      = $volume_id;

            $trail_access = UserAccess::GetUserAccessOnContent($v_param);


            if (empty($trail_access[0])) {
                // Check User Access Trail (Trail) Issue Level
                $i_param['access_type_id'] = 111;
                $i_param['access_on']      = 'issue';
                $i_param['user_id']        = session()->get('user_id');
                $i_param['ip_address']     = $request->ip();
                $i_param['issue_id']       = $issue_id;

                $trail_access = UserAccess::GetUserAccessOnContent($i_param);
            }

            if (empty($trail_access[0])) {
                // Check User Access Trail (Trail) Article Level
                $a_param['access_type_id'] = 111;
                $a_param['access_on']      = 'article';
                $a_param['user_id']        = session()->get('user_id');
                $a_param['ip_address']     = $request->ip();
                $a_param['article_id']     = $article_id;

                $trail_access = UserAccess::GetUserAccessOnContent($a_param);
            }

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

                $query_download_check = "select count(*) total FROM download_count_articles where issue_id= " . $article_detail->issue_id . " and user_id = " . $user_access->user_id;
                $trial_count          = DB::select($query_download_check);
                $count                = $trial_count[0]->total;

                if ($article_detail->issue_id) {
                    //if article is not epub article
                    if ($count >= 5) {
                        Session::flash('message', "You have Trial Access and you have already downloaded " . $count . " Articles from this Issue");
                        return false;
                    }
                }
            }
            if (DB::select("select block FROM download_total where block = 'y' and uid = " . $user_id . "")) {
                Session::flash('message', " Your download limit has been exceeded!");
                redirect('/bypublication');
            }

            if ($content_download_type == 'P') {
                $res_obj = DB::select("select * FROM perpetual_article_access where user_id = " . $user_id . " and article_id = " . $article_id);
                foreach ($res_obj as $row) {
                    $query1 = DB::select("insert into perpetual_history (user_id, type, type_id, order_id)
                                            values (" . $row->user_id . ",'a'," . $row->article_id . "," . $row->order_id . " )");
                    $query2 = DB::select(" delete from perpetual_article_access where id = " . $row->id);
                }
            } //restrict prepetual ends

            if (!empty($restricted_user_access_key)) {
                $user_name = trim($request->user_name);
                $password  = trim($request->password);

                if ($user_access) {
                    if ($user_access->access_type_id != 666) {
                        $vru_count = UserAccess::VerifyRestrictUser($restricted_user_access_key, $user_name, $password, $user_access);

                        if ($vru_count == 0) {
                            Session::flash('message', " Invalid User Name or Password");
                            return false;
                        }
                    } else {
                        $vru_count = UserAccess::VerifyRestrictUserWithoutKey($restricted_user_access_key, $user_access);
                        if ($vru_count == 0) {
                            Session::flash('message', " Your download limit has been exceeded!");
                            return false;
                        }
                    }
                } else {
                    $vru_count = UserAccess::VerifyRestrictUser($restricted_user_access_key, $user_name, $password, $user_access);
                    if ($vru_count == 0) {
                        Session::flash('message', " Invalid User Name or Password");
                        return false;
                    }
                }

                if ($user_access->access_type_id == 666) {
                    UserAccess::UpdateWithoutKeyRestrictedUserInfo($restricted_user_access_key, $clientIP, $article_id, 'a', $user_access);
                } else {
                    UserAccess::UpdateRestrictedUserInfo($restricted_user_access_key, $user_name, $clientIP, $article_id, 'a', $user_access);
                }
            }
        }

        return true;
    }

    public function DirectDownload(Request $request)
    {  
    $param = array();
    $aparam = array();
    $download_type = array();
    $DownloadAccess = false;
    $content_id = $request->content_id;
    $name = $request->name;
    $email = $request->email;
    $user_id = 0;
    $user_access_id = '';
    $content_download_type  = '';
    $restricted_user_access_key  = '';
    $journal_volume_access = false;
    $article_disease_access = false;
    $journal_issue_access = false;
    $journal_article_access = false;
    $access_base_type = 0;

    if(session()->has('message'))
    {
        if(Session::get('message') != "Success")
        {
            return View::make('direct_download_link', with(['param' => $aparam, 'download_type' => $download_type]));     
        }
    }

     $email_token = sha1(config('constants.admin.mailToken').$content_id.$name.$email);


     if($email_token == $request->link)
     {
        $user = User::where('name', '=', $name)->first();
        if($user)
        {
            //$param['user_id'] = $user_id = $user->id;
            $param['user_id']=null;
            $user_id = $user->id;
            $access_data = UserAccess::CheckUserAccess($user_id);
            // User Access Check
            if(!empty($access_data))
            {
                $article = Article::where('article_id', '=', $content_id)->first();
                // Article existing check
                if(!empty($article))
                {
                    $is_epub        = $article->is_epub;
                    $article_id     = $article->article_id;
                    $article_nid    = $article->article_nid;
                    $issue_id       = $article->issue_id;
                    $volume_id      = $article->volume_id;
                    $journal_id     = $article->journal_id;

                        $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $article_id, "a");
                        if ($article_access[0]->total_count > 0) {
                            $DownloadAccess = true;
                            if ($article_access[0]->access_type == 1) {
                                $content_download_type = 'F';
                            } else {
                                $content_download_type = 'FO';
                            }
                        }

                        //check issue level content access
                        if (!$DownloadAccess && ($is_epub == 0)) {
                            $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i");
                            if ($article_access[0]->total_count > 0) {
                                $DownloadAccess = true;
                                if ($article_access[0]->access_type == 1) {
                                    $content_download_type = 'F';
                                } else {
                                    $content_download_type = 'FO';
                                }
                            }
                        }

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

                            if ($article_access[0]->total_count > 0) {
                                $DownloadAccess = true;
                                if ($article_access[0]->access_type == 1) {
                                    $content_download_type = 'F';
                                } else {
                                    $content_download_type = 'FO';
                                }
                            }
                        }

                        //----------user access id set here-------
                        foreach ($access_data as $row_access_data) {
                            if ($row_access_data->access_type_on == "journal_volume") {
                                $journal_volume_access = true;
                                $access_base_type = $row_access_data->access_base_type;
                                $user_access_id = $row_access_data->user_access_id;
                            }

                            if ($row_access_data->access_type_on == "disease") {
                                $article_disease_access = true;
                                $access_base_type = $row_access_data->access_base_type;
                                $user_access_id = $row_access_data->user_access_id;
                            }
							/*
                           if($row_access_data->access_type_on == "issue" )
                            {
                                $journal_issue_access = true;
                                $access_base_type = $row_access_data->access_base_type;
                                $user_access_id = $row_access_data->user_access_id;
                            }

                           if($row_access_data->access_type_on == "article" )
                            {
                                $journal_article_access = true;
                                $access_base_type = $row_access_data->access_base_type;
                                $user_access_id = $row_access_data->user_access_id;
                            }
							*/
                        }
						

                        if (!$DownloadAccess) 
                        {
                        // Check User Access Volume Level
                        $param['volume_id']  = $article->volume_id;
                        $param['ip_address'] = \Request::ip();
                        $access_on = '';

                        if($journal_volume_access)
                        {
                            $access_on = "volume";
                        }
                        else if($article_disease_access)
                        {
                            $access_on = "disease";
							$param['article_id'] = $article_id;
							$param['disease_access'] = 'article';
                        }
                       /*
                       if($is_epub == 0 && $journal_issue_access )
                        {
                            $param['issue_id']  = $article->issue_id;
                            $access_on = "issue";
                        }

                       if($is_epub == 0 && $journal_article_access)
                        {
                            $param['article_id']  = $article->article_id;
                            $access_on = "article";
                        }
						*/
                         if($access_base_type == 1)
                         {
                            $user_access = UserAccess::GetAllContentUserAccess($param, array($access_on => true));

                            if (empty($user_access[0]))
                            {
                                $param['user_id'] = $user_id;

                                $user_access = UserAccess::GetAllContentUserAccess($param, array($access_on => true));

                                if (!empty($user_access[0]))
                                {
                                    $param['name'] = $request->name;
                                    $param['user_domain'] = substr(strrchr($email, "@"), 1);
                                    $param['user_email'] = $email;

                                    $domain = User::GetUserDomain($param);
                                    // if user domain name exist
                                    if($domain->count() > 0)
                                    {
                                        $param['user_access_id']=$user_access[0]->user_access_id;
                                        $user_access_info = UserAccess::GetUserAccess($param); 

                                        $DownloadAccess              = $user_access[0]->user_access_id;
                                        $user_access_id              = $user_access[0]->user_access_id;
                                        $content_download_type       = $user_access[0]->content_download_type;
                                        $restricted_user_access_key  = $user_access[0]->restricted_user_access_key;
                                    }
                                    else
                                    {
                                        Session::flash("message", "Domain name does't exist");

                                        return View::make('direct_download_link', with(['param' => $aparam, 'download_type' => $download_type])); 
                                    }

                                }
                                else
                                {
                                    Session::flash("message", "You are not authorized access this content");                            
                                }
                            }
                            else
                            {
                                $param['user_access_id']=$user_access[0]->user_access_id;
                                $user_access_info = UserAccess::GetUserAccess($param); 

                                $DownloadAccess              = $user_access[0]->user_access_id;
                                $user_access_id              = $user_access[0]->user_access_id;
                                $content_download_type       = $user_access[0]->content_download_type;
                                $restricted_user_access_key  = $user_access[0]->restricted_user_access_key;
                            }
                        }
                        elseif($access_base_type == 0)
                        {
                            $param['user_id'] = $user_id;
                            $user_access = UserAccess::GetAllContentUserAccess($param, array($access_on => true));

                            if (!empty($user_access[0]))
                            {
                                $param['name'] = $request->name;
                                $param['user_domain'] = substr(strrchr($email, "@"), 1);
                                $param['user_email'] = $email;

                                $domain = User::GetUserDomain($param);
                                // if user domain name exist
                                if($domain->count() > 0)
                                {
                                    $param['user_access_id']=$user_access[0]->user_access_id;
                                    $user_access_info = UserAccess::GetUserAccess($param); 

                                    $DownloadAccess              = $user_access[0]->user_access_id;
                                    $user_access_id              = $user_access[0]->user_access_id;
                                    $content_download_type       = $user_access[0]->content_download_type;
                                    $restricted_user_access_key  = $user_access[0]->restricted_user_access_key;
                                }
                                else
                                {
                                    //********Domain name does't exist********** 
                                    Session::flash("message", "You are not authorized access this content");

                                    return View::make('direct_download_link', with(['param' => $aparam, 'download_type' => $download_type])); 
                                }
                            }
                            else
                            {
                                Session::flash("message", "You are not authorized access this content");                            
                            }
                            }
                        }

                    if($DownloadAccess)
                    {
                        $param['article_id']  = $article->article_id;
                        $param['user_email'] = $email;
                        $article_download = UserAccess::GetUserAccessDownloadArticle($param);

                        if($article_download->count() >= $user->proxy_download)
                        {
                            Session::flash('message', "Article download limit exceeded");
                        }
                        else
                        {
                            Session::flash('message', "Success");

                                $download_type['content_type'] = "article";
                            $download_type['type'] = "direct_download";
                            $download_type['user_email'] = $email;
                            $download_type['user_id'] = Crypt::encrypt($user_id);

                            $aparam = Crypt::encrypt( $article_id.'||'.'pdf'.'||'.$content_download_type.'||'.$restricted_user_access_key.'||'.$user_access_id);
                        }
                    }
                    else
                    {
                        Session::flash("message", "You are not authorized access this content");
                    }

                }
                else
                {
                    Session::flash("message", "Article not found");
                }
            }
            else
            {
                Session::flash("message", "You are not authorized access this content");
            }
        }
        else
        {
            Session::flash("message", "You are not authorized access this content");
        }

     }
     else
     {
        Session::flash("message", "You are not authorized access this content");
     }
        return View::make('direct_download_link', with(['param' => $aparam, 'download_type' => $download_type]));     
    }    

    // OLD Direct Article Download 
    public function DirectArticleDownload($request,$article_nid)
    {  
    $param = array();
    $aparam = array();
    $download_type = array();
    $DownloadAccess = false;
    $content_id = $article_nid;
    $user_id = 0;
    $user_access_id = '';
    $content_download_type  = '';
    $restricted_user_access_key  = '';
    $journal_volume_access = false;
    $journal_issue_access = false;
    $journal_article_access = false;
    $access_base_type = 0;
    $SecondsGap = 30; //default is 30 sec

        //$param['user_id'] = $user_id = $user->id;
            if (session()->has('user_id'))
            {
                $user_id = session()->get('user_id');
            }
            $param['user_id']=$user_id;
            $access_data = UserAccess::CheckUserAccess($user_id);
            // User Access Check
            
               
                $article = Article::where('nid', '=', $content_id)->first();

                // Article existing check
                if(!empty($article))
                {
                    $is_epub        = $article->is_epub;
                    $article_id     = $article->article_id;
                    $article_nid    = $article->article_nid;
                    $issue_id       = $article->issue_id;
                    $volume_id      = $article->volume_id;
                    $journal_id     = $article->journal_id;

                        $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $article_id, "a");
                        if ($article_access[0]->total_count > 0) {
                            $DownloadAccess = true;
                            if ($article_access[0]->access_type == 1) {
                                $content_download_type = 'F';
                            } else {
                                $content_download_type = 'FO';
                            }
                        }

                        //check issue level content access
                        if (!$DownloadAccess && ($is_epub == 0)) {
                            $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i");
                            if ($article_access[0]->total_count > 0) {
                                $DownloadAccess = true;
                                if ($article_access[0]->access_type == 1) {
                                    $content_download_type = 'F';
                                } else {
                                    $content_download_type = 'FO';
                                }
                            }
                        }

                        //check volume level content access
                        if (!$DownloadAccess && ($is_epub == 0)) {
                            $article_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $volume_id, "v");
                            if ($article_access[0]->total_count > 0) {
                                $DownloadAccess = true;
                                if ($article_access[0]->access_type == 1) {
                                    $content_download_type = 'F';
                                } else {
                                    $content_download_type = 'FO';
                                }
                }
            }
                        if($user_id)
                        {
                            $access_data = UserAccess::CheckUserAccess($user_id);
                        
                            //----------user access id set here
                            foreach($access_data as $row_access_data)
                            {
                                if($row_access_data->access_type_on == "journal_volume" )
                                {
                                    $journal_volume_access = true;
                                    $access_base_type = $row_access_data->access_base_type;
                                    $user_access_id = $row_access_data->user_access_id;
                                }

                               if($row_access_data->access_type_on == "issue" )
                                {
                                    $journal_issue_access = true;
                                    $access_base_type = $row_access_data->access_base_type;
                                    $user_access_id = $row_access_data->user_access_id;
                                }

                               if($row_access_data->access_type_on == "article" )
                                {
                                    $journal_article_access = true;
                                    $access_base_type = $row_access_data->access_base_type;
                                    $user_access_id = $row_access_data->user_access_id;
                                }
                }
            }
            if (!$DownloadAccess) {
                        // Check User Access Volume Level
                        $param['volume_id']  = $article->volume_id;
                        $param['ip_address'] = \Request::ip();
                        $access_on = '';

                if ($journal_volume_access) {
                            $access_on = "volume";
                        }
                       
                if ($is_epub == 0 && $journal_issue_access) {
                            $param['issue_id']  = $article->issue_id;
                            $access_on = "issue";
                        }

                       if($is_epub == 0 && $journal_article_access)
                        {
                            $param['article_id']  = $article->article_id;
                            $access_on = "article";
                        }

                         if($access_base_type == 1)
                         {
                            $user_access = UserAccess::GetAllContentUserAccess($param, array($access_on => true));

                            if (!empty($user_access[0]))
                            {
                                $param['user_access_id']=$user_access[0]->user_access_id;
                                $user_access_info = UserAccess::GetUserAccess($param); 

                                $DownloadAccess              = $user_access[0]->volume_id;
                                $user_access_id              = $user_access[0]->user_access_id;
                                $content_download_type       = $user_access[0]->content_download_type;
                                $restricted_user_access_key  = $user_access[0]->restricted_user_access_key;

                           // Session::flash('message', "Success");


                            }
                        } 
                    }
                }
                    if(!$DownloadAccess)  {

                    print("<center><div style='text-align: left;position: absolute;top: 10vh;right: 0;bottom: 10vh;background-color: #f3f3f3;border: 1px solid #cdcdcd;height: fit-content;width: 50%;left: 0;margin: 0 auto;padding: 15px;box-shadow: 0 4px 6px #cbcbcb;border-radius: 15px;'>Dear Researcher,<br><br> 
                    If the download has not already occurred then you may be outside the premises of your institution, to which this access is locked.<br><br> 
                    You can still access and download this content remotely, via OpenAthens , Shibboleth or EZ Proxy, which are all common models of remote access.<br><br> 
                    Please request your institution to provide us with your Institutions' Open Athens/ Shibboleth/ EZ Proxy, entity ID/ Scope<br><br> 
                    And we will set up the remote access for you.<br><br> 
                    Alternatively, you can ask your institution to provide you VPN access.<br><br> 
                    <b>Note: If your institution has not set up or is not compliant with Open Athens/ Shibboleth or EZProxy, please let us know and we will provide you with an alternative download option.</b><br>Email to contact: <a href='mailto:faizan@benthamscience.net' >faizan@benthamscience.net</a></div></center>");
                    die;
                    }                
                    
        if ($DownloadAccess) {
                    $article_gap = Article::ArticleDownloadGap($user_id, $article_id, $SecondsGap);

                    if ($article_gap->rcd > 0) {

                        $last_session_userid = $request->session()->getId() . "-" . microtime(true);
                        session(['last_session_userid' => $last_session_userid]);
                        DB::select("update download_count_articles set timestamp=" . time() . ", session_id='" . session()->get('last_session_userid') . "' where id='" . $article_gap->id . "'");

                    print("<center><div style='text-align: left;position: absolute;top: 10vh;right: 0;bottom: 10vh;background-color: #f3f3f3;border: 1px solid #cdcdcd;height: fit-content;width: 50%;left: 0;margin: 0 auto;padding: 15px;box-shadow: 0 4px 6px #cbcbcb;border-radius: 15px;'>Cannot download, try again after $SecondsGap seconds</div></center>");
                    die;
                    }

                    //Session::flash('message', "Success");
            if ($user_id > 0 && isset($article->article_id)) {

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

                        $download_file_type = 1;
                        $investigation_type = 2;

                        $add_download_count = array(
                            'user_id'               => $user_id,
                            'journal_id'            => $article->journal_id,
                            'volume_id'             => $article->volume_id,
                            'issue_id'              => $article->issue_id,
                            'article_id'            => $article->article_id,
                            'timestamp'             => time(),
                            'ip_address'            => $request->ip(),
                            'content_download_type' => $content_download_type,
                            'is_agree'              => 1,
                            'download_file_type'    => $download_file_type,
                            //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                            'session_id'            => session()->get('last_session_userid'),
                        );

                       $last_download_count = Article::AddArticleDownload($add_download_count);

                        $add_download_count['investigation_type']=$investigation_type;
                    
                        $add_download_count['ip_address']=ip2long(\Request::ip());

                        $last_inv_id = $this->AddAccessInvestigation($request,$add_download_count);
                    }

                        $file_path          = config('constants.admin.root_path') . $article->file_path . $article->file_name;
                       // dd($file_path);
                        return $file_path;                        
                }
    }
	
    public function ValidateAPIHost($host)
    {
  
        $count = DB::select("select count(*) as total from api_hosts where host='$host' and status='A'");      
      if($count>0){
        return true;
      }else{
        return false; 
      }
    }

    public function getRelatedArticles()
    {
        header('Access-Control-Allow-Origin: *'); 
      $search_keyword="Cancer";
      $pagesize=20;
      $column=2;
      $host='';
      //print_r($_REQUEST); die;
      if($_REQUEST){
        $search_keyword=$_REQUEST['keywords'];
        $pagesize=$_REQUEST['size'];
        $column=$_REQUEST['column'];
        $host=urldecode($_REQUEST['host']);
      }
      if($pagesize>20){
        $pagesize=20;
      }
      
      //$keyword = str_replace(","," ",$search_keyword);//.' '.$article_title;
      if($search_keyword!=""){
        $search_keyword = preg_replace( "/\r|\n/", " ", $search_keyword );
        $keyword = addslashes(strtolower(urlencode($search_keyword)));//.' '.$article_title;
      }
      if(!$this->ValidateAPIHost($host)){
            print('<h4>The operation failed for some reason!</h4>');
            die;
      }
      
      //$url = "https://www.eurekaselect.com/api/service_search/$keyword?type=article&sdate=2013-01-01&edate=".date('Y-m-d')."&pagesize=$pagesize&page=0";
	  $url = "https://www.eurekaselect.com/api/services_search/$keyword";
      //print($url); die;
	  $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		//return the transfer as a string
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// $output contains the output string
		$output = curl_exec($ch);
		// close curl resource to free up system resources
		curl_close($ch);
      
      $relatedoutput="";
      $json=json_decode($output);
      
      $tot_record = $json->tot_record;
      $article = $json->article;
      $tot_article = count($article);
     
      
      $num_pages = intval($tot_record/$pagesize);
      if($tot_record%$pagesize) $num_pages++;
      
      $num_rows = $tot_record;
      $table = "<table><th></th>";
      //print("Total=".$tot_article);
      for($i=0;$i<count($article);$i++) {
        
        
        
              
            $artobj = $article[$i];       
             
            $page = "https://".$_SERVER['HTTP_HOST']."/node/".$artobj->article_nid.'/?tracking-code=3';
            $issn=0;
			if(isset($artobj->journal_issn)){
            $issn = $artobj->journal_issn;
			}
            $volume = $artobj->volume;
            $issue = $artobj->issue;
            $open_url = "https://www.eurekaselect.com/openurl/content.php";
            $journal_url = $open_url."?genre=journal&issn=".$issn;
            $issue_url = $open_url."?genre=article&issn=".$issn."&volume=".$volume."&issue=".$issue;
            $journal_name = $artobj->journal_title;
            $first_page = $artobj->first_page;
            $last_page = $artobj->last_page;
            $pages = $first_page.'-'.$last_page;
            $author = $artobj->author;
            $article_title = $artobj->article_title;
			$article_nid = $artobj->article_nid;
            
            $jsonobj[$i]['article_title'] = $article_title;
            $jsonobj[$i]['journal_title'] = $journal_name;
            $jsonobj[$i]['article_nid'] = $article_nid;
       
          
            
        $griddata = '<a href="'.$page.'" target="_blank">'.$article_title.'</a><br>
                    <span class="bsp-journal">'.$journal_name.'</span>';
        
        $nodeContent[] =  array(
                    $griddata,
                  );              
      }
      $tableattrb = array(
              "width" => '100%',
             ); 
        
      if($tot_article>0){       
        $relatedoutput .= '<div class="bsp-related"><div class="related-title"><h4>Related Article(s)</h4></div>';
        if($nodeContent!=''){
          /*if($column==1){
            $relatedoutput .= theme('table', $tableHeader, $nodeContent, $tableattrb);          
          }else{
            $relatedoutput .= theme('item_list', $nodeContent);         
          }*/
		  foreach($nodeContent as $k=>$rr){
			  
			$table .= "<tr><td>".$rr[0]."</td></tr>";     
          }
		}
      }
      
      //print(json_encode($jsonobj)); die;
        
      
        print $relatedoutput . '</div>';
    }
    /*****************************************************************************************************************************
     *
     *                           MULTIPLE LANGUAGE ARTICLE CONTROLLER
     *
     *******************************************************************************************************************************/
    /*
    *   Author          : Enayat
    *   Date            : 03-02-2022
    *   Description     : This function will add/update mutiple language(title,abstract etc) against article.
    *   @Param           : article_id, request obj
    */
    public function submitMultiLanuage($request, $article_id)
    {
        // dd($request->all());
        $validator              = Validator::make(
            $request->all(),
            [
                'language'          => 'required',
                'article_title'        => 'required',
                'article_node_id'        => 'required'
            ]
        );
        if ($validator->fails()) {
            return array(false, $validator);
        } else {

            $language_id = $request->language;
            $is_added = MultiLangArticle::where(['article_id' => $article_id, 'language_id' => $language_id])->first();



            try {
                DB::beginTransaction();
                $action = '';
                if ($is_added) {
                    $action = config('constants.log_action_types.update');
                    $data = [
                        'language_id' => $request->language,
                        'article_id' => $article_id,
                        'title' => $request->article_title,
                        'abstract' => $request->abstract,
                        'updated' => time(),
                        'updated_by' => Auth::user()->id,
                    ];
                    $response = MultiLangArticle::where(['article_id' => $article_id, 'language_id' => $language_id])->update($data);
                } else {
                    $action = config('constants.log_action_types.insert');
                    $data = [
                        'language_id' => $request->language,
                        'article_id' => $article_id,
                        'title' => $request->article_title,
                        'abstract' => $request->abstract,
                        'created' => time(),
                        'created_by' => Auth::user()->id,
                        'updated' => time(),
                        'updated_by' => Auth::user()->id,
                    ];
                    $response = MultiLangArticle::create($data);
                }
                $keywords_input = $request->get("multi_keywords");
                //-------------------Insert into Keywords table---------------
                if ($keywords_input != "") {
                    MultiLanguageKeywords::where(['article_id' => $article_id, 'language_id' => $language_id])->delete();
                    MultiLanguageKeywords::create(['article_id' => $article_id, 'language_id' => $language_id, 'keyword' => $keywords_input]);
                } else {
                    MultiLanguageKeywords::where(['article_id' => $article_id, 'language_id' => $language_id])->delete();
                }

                $log     = array_merge(['keywords' => $keywords_input], $data);
                // add into logg
                $add_log = array(
                    'content_id'      => $article_id,
                    'content_type_id' => config('constants.log_content_types.Article'),
                    'action'          => $action,
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return Redirect::to('admin/articles');
            }
        }


        return array(true, $article_id);
    }

    /*
    *   Author      : Enayat
    *   Date        : 07-03-2022
    *   Description : Will Delete Multiple Lang against article
    */
    function destroyArticleLanguage(Request $request, $language_id)
    {
        try {

            $article_language = MultiLangArticle::where('id', $language_id)->first();
            $log_data = $article_language->toArray();

            DB::beginTransaction();

            $add_log = array(
                'content_id'      => $language_id,
                'content_type_id' => config('constants.log_content_types.Article'),
                'action'          => config('constants.log_action_types.delete'),
                'log_data'        => json_encode($log_data),
                'created_dated'   => time(),
                'created_by'      => Auth::user()->id,
                'ip'              => ip2long($request->ip()),
            );
            $log = Log::AddLog($add_log);

            MultiLangArticle::where('id', $language_id)->delete();
            DB::commit();
        } catch (Exception $e) {

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return redirect()->back();
        }

        return redirect()->back()->with('success', 'Article language delete successfully.');
    }

    // AJAX
    public function getMultLangAuthors(Request $request)
    {
        $method = $request->method;
        if ($method == "POSTDATA") {

            try {

                DB::beginTransaction();

                $add_article['language_id']       = $request->get('language_id');
                $add_article['first_name']       = $request->get('first_name');
                $add_article['last_name']        = $request->get('last_name');
                $add_article['initials']         = $request->get('initials');
                $add_article['country']          = $request->get('country');
                $add_article['email']            = $request->get('email');
                $add_article['orcid']            = $request->get('orcid');
                $add_article['h_index']          = $request->get('h_index') ? $request->get('h_index') : 0;
                $add_article['sequence']         = $request->get('sequence');
                $add_article['is_principle']     = ($request->get('principle')) ? $request->get('principle') :  0;
                $add_article['iseditorcoeditor'] = $request->get('author_type');
                $add_article['article_id']       = $request->get('article_id');
                $add_article['id']        = MultiLangAuthor::insertGetId($add_article);

                $add_log = array(
                    'content_id'      => $add_article['id'],
                    'content_type_id' => config('constants.log_content_types.Multi_Lang_Authors'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($add_article),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }

            return response()->json(array('insert' => $add_article), 200);
        } elseif ($method == 'UPDATE_MULTIAUTHOR') {
            try {
                DB::beginTransaction();
                $id = $request->get('id');
                $old_authors = MultiLangAuthor::where('id', $id)->first()->toArray();

                // update record.

                $update_author['language_id']       = $request->get('language_id');
                $update_author['first_name']       = $request->get('first_name');
                $update_author['last_name']        = $request->get('last_name');
                $update_author['initials']         = $request->get('initials');
                $update_author['country']          = $request->get('country');
                $update_author['email']            = $request->get('email');
                $update_author['orcid']            = $request->get('orcid');
                $update_author['h_index']          = $request->get('h_index') ? $request->get('h_index') : 0;
                $update_author['sequence']         = $request->get('sequence');
                $update_author['is_principle']     = ($request->get('principle')) ? $request->get('principle') :  0;
                $update_author['iseditorcoeditor'] = $request->get('author_type');



                $add_log = array(
                    'content_id'      => $id,
                    'content_type_id' => config('constants.log_content_types.Multi_Lang_Authors'),
                    'action'          => config('constants.log_action_types.delete'),
                    'log_data'        => json_encode($old_authors),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                MultiLangAuthor::where('id', $id)->update($update_author);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }
            return response()->json(array('response' => true), 200);
        } elseif ($method == 'DELETE_AUTHORS') {
            try {
                DB::beginTransaction();
                $id = $request->get('id');
                $deleted_authors = MultiLangAuthor::where('id', $id)->first()->toArray();


                $add_log = array(
                    'content_id'      => $id,
                    'content_type_id' => config('constants.log_content_types.Multi_Lang_Authors'),
                    'action'          => config('constants.log_action_types.delete'),
                    'log_data'        => json_encode($deleted_authors),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);
                MultiLangAuthor::where('id', $id)->delete();

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }
            return response()->json(array('response' => true), 200);
        } else {

            $article_id = $request->get('article_id');
            if (!empty($article_id)) {
                $selected_author = MultiLangAuthor::where(['article_id' => $article_id])->get();
                return response()->json(array('multilanguage_authors' => $selected_author), 200);
            }
        }
    }

    /*
    *   MULTI-LANGUAGE AUTHOR AFFILIATIONS
    */
    public function getMultLangAuthorsAffiliation(Request $request)
    {
        $author_id = $request->get('author_id');
        $method = $request->get('method');

        if ($method == 'Add_Affiliation') {
            // insertion
            try {

                DB::beginTransaction();

                $add_affiliation['author_id']   = $request->get('author_id');
                $add_affiliation['institution'] = $request->get('institution');
                $add_affiliation['department']  = $request->get('department');
                $add_affiliation['address']     = $request->get('address');
                $add_affiliation['country']     = $request->get('country');
                $add_affiliation['city']        = $request->get('city');
                $add_affiliation['postal_code'] = $request->get('postal_code');
                $add_affiliation['phone']       = $request->get('phone');
                $add_affiliation['fax']         = $request->get('fax');
                $add_affiliation['web_view']    = addslashes(str_replace('"', "'", $request->get('web_view')));
                $add_affiliation['aff_id']      = MultiLangAuthorAffiliation::insertGetId($add_affiliation);

                $add_log = array(
                    'content_id'      => $add_affiliation['aff_id'],
                    'content_type_id' => config('constants.log_content_types.MutiLangAuthor_Affi'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($add_affiliation),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }

            return response()->json(array('insert' => $add_affiliation), 200);
        } elseif ($method == 'Update_Affiliation') {
            try {
                // try transaction start here for data integrity
                DB::beginTransaction();
                $aff_id =  $request->get('aff_id');

                $old_affiliation_data = MultiLangAuthorAffiliation::where('aff_id', $aff_id)->get()->toArray();

                $update_affiliation['institution'] = $request->get('institution');
                $update_affiliation['department']  = $request->get('department');
                $update_affiliation['address']     = $request->get('address');
                $update_affiliation['country']     = $request->get('country');
                $update_affiliation['city']        = $request->get('city');
                $update_affiliation['postal_code'] = $request->get('postal_code');
                $update_affiliation['phone']       = $request->get('phone');
                $update_affiliation['fax']         = $request->get('fax');
                $update_affiliation['web_view']    = addslashes(str_replace('"', "'", $request->get('web_view')));

                MultiLangAuthorAffiliation::where('aff_id', $aff_id)->update($update_affiliation);

                $add_log = array(
                    'content_id'      => $aff_id,
                    'content_type_id' => config('constants.log_content_types.MutiLangAuthor_Affi'),
                    'action'          => config('constants.log_action_types.update'),
                    'log_data'        => json_encode($old_affiliation_data),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }

            return response()->json(array('update' => $update_affiliation), 200);
        } elseif ($method == 'Delete_Affiliation') {
            try {
                DB::beginTransaction();
                $aff_id = $request->get('aff_id');
                $deleted_author_affi = MultiLangAuthorAffiliation::where('aff_id', $aff_id)->first()->toArray();


                $add_log = array(
                    'content_id'      => $aff_id,
                    'content_type_id' => config('constants.log_content_types.MutiLangAuthor_Affi'),
                    'action'          => config('constants.log_action_types.delete'),
                    'log_data'        => json_encode($deleted_author_affi),
                    'created_dated'   => time(),
                    'created_by'      => Auth::user()->id,
                    'ip'              => ip2long($request->ip()),
                );
                $log = Log::AddLog($add_log);
                MultiLangAuthorAffiliation::where('aff_id', $aff_id)->delete();

                DB::commit();
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }
            return response()->json(array('response' => true), 200);
        } else {
            if (!empty($author_id)) {
                $selected_affiliation = MultiLangAuthorAffiliation::where(['author_id' => $author_id])->get()->toArray();
                return response()->json(array('selected_affiliation' => $selected_affiliation), 200);
            }
        }
    }
}
