<?php

namespace App\Http\Controllers;

use App\Http\Controllers\MigsController;
use App\Models\Article;
use App\Models\Campaign;
use App\Models\Author;
use App\Models\Indexing;
use App\Models\ContentAccess;
use App\Models\Country;
use App\Models\Disease;
use App\Models\Issue;
use App\Models\Journal;
use App\Models\Log;
use App\Models\MarkList;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Subject;
use App\Models\UserAccess\UserAccess;
use App\Models\Volume;
use App\Models\Manuscript;
use App\Rules\Captcha;
use App\User;
use Auth;
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;
use App\Models\MultiLanguage;

class JournalController extends BenthamController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
/*
protected $add_journal = array();
protected $log_journal_disease = array();
protected $log_journal_subject = array();
protected $log_meta = array();
 */
    public function __construct()
    {

        //$this->middleware('Permission:journal')->only('index','show','create','edit','update','destroy');
        //$this->only('destroy');
    }

    public function index(Request $request)
    {

        $editPermission   = false;
        $deletePermission = false;
        $createPermission = false;

        $search  = $request->get('search');
        $journal = Journal::GetJournalList($search);

        if (checkPermission('journal', 'create')) {
            $createPermission = true;
        }
        if (checkPermission('journal', 'edit')) {
            $editPermission = true;
        }
        if (checkPermission('journal', 'delete')) {
            $deletePermission = true;
        }
        return view('admin.journal.journal', with(['journal' => $journal, 'createPermission' => $createPermission, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission]));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //-----------Subject List-------------
        $temp = rtrim(Subject::display_parent(),'_');
        $option = explode('_', $temp);
        $arr = array();
        if ($temp != '') 
        {   
            //disease=1_diabetes=2_
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $arr[0] = 'Please Select';
                    $arr[$id] = $name;
                }
            }
        } else {
            $arr[0] = 'Please Select';
        }

        //---------Indexing List----------
        $temp = rtrim(Indexing::display_parent(), '_');
        $option = explode('_', $temp);
        $indexing_agencies = array();
        if ($temp != '') {
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $indexing_agencies[0] = 'Please Select';
                    $indexing_agencies[$id] = $name;
                }
            }
        } else {
            $indexing_agencies[0] = 'Please Select';
        }

        $disease      = Disease::DiseaseParent();
        $journal_type = Journal::JournalType();
        $publisher    = Journal::Publisher();
        $multilanguage = [];
        $selected_journal = [];
        return view('admin.journal.addjournal', ['multilanguage' => $multilanguage, 'selected_journal' => $selected_journal, 'disease' => $disease, 'journal_type' => $journal_type, 'publisher' => $publisher, 'subject' => $arr, 'indexing' => $indexing_agencies]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

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

        if ($ajax == true) {

            if ($method == 'rental_details') {

                if ($action == 'SELECT') {
                    return $this->ajax_SELECT_Rental_Details($request);
                } else if ($action == 'INSERT') {
                    return $this->ajax_INSERT_Rental_Details($request);
                } else if ($action == 'DELETE') {
                    return $this->ajax_DELETE_Rental_Details($request);
                } else if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE_Rental_Details($request);
                }
            }
        }


        $add_journal         = array();
        $log_journal_disease = array();
        $log_journal_subject = array();
        $log_journal_indexing = array();
        $log_meta            = array();

        //--------------Add Journal Validation------------------
        $validator = Validator::make(
            $request->all(),
            [
            'journal_status'  => 'required',
            'doi' => 'nullable|min:6|max:50|unique:journal,doi',
            'journal_type'    => 'required',
            'IsOpenAccess'    => 'required',
            'title'           => 'required',
            'image_file_name' => 'mimes:jpeg,jpg,bmp,png,gif',
            'flyer_link'      => 'mimes:pdf',
            'subtitle'        => 'required|unique:journal,subtitle',
            'eissn'           => 'required',
            // 'rental_price'    => 'required_if:journal_rental'
        ],
        [
            'eissn.required' => 'The ISSN (Print) field is required.'
            ]
        );

        if ($validator->fails()) {
            return redirect('admin/journals/create')
                ->withErrors($validator)
                ->withInput();
        } else {

            try {
// try transaction start here for data integrity

                DB::beginTransaction();

                //---------------------Inert into node table---------------
                $user     = Auth::user();
                $add_node = array(
                    'type'    => 'journal',
                    'title'   => $request->input('title'),
                    'uid'     => $user->id,
                    'status'  => 1,
                    'created' => time(),
                    'changed' => time(),
                );

                $node_id = Node::Add($add_node);

                //----------------------Upload journal image-------------------------------
                $journal_image_path = config('constants.admin.root_path') . 'JOURNALS/BEN/' . $request->input('subtitle');
                if ($request->hasfile('image_file_name')) {
                    $image_file = $request->file('image_file_name');
                    $file_name  = $image_file->getClientOriginalName();
                    if (!is_dir($journal_image_path)) {
                        mkdir($journal_image_path, 0755, true);
                    }
                    $image_file->move($journal_image_path, $file_name);
                }
                //---------------------Inert into journal table--------
                $add_journal = array(
                    'image_file_name'         => $file_name,
                    'nid'                     => $node_id,
                    'publisher_id'            => $request->input('publisher_id'),
                    'journal_type'            => $request->input('journal_type'),
                    'title'                   => $request->input('title'),
                    'subtitle'                => $request->input('subtitle'),
                    'journal_email'           => $request->input('journal_email'),
                    'formerly_title'          => $request->input('formerly_title'),
                    'issn'                    => $request->input('issn'),
                    'org_impact_factor'       => $request->input('org_impact_factor'),
                    'doi'                     => $request->input('doi'),
                    'eissn'                   => $request->input('eissn'),
                    'signature'               => $request->input('signature'),
                    'description'             => $request->input('description'),
                    'editorial_policy'        => $request->input('editorial_policy'),
                    'guideline_for_reviewers' => $request->input('guideline_for_reviewers'),
                    'ifa'                     => $request->input('ifa'),
                    'aims_and_scope'          => $request->input('aims_and_scope'),
                    'facebook_like_api_code'  => $request->input('facebook_like_api_code'),
                    'jms_link'                => $request->input('jms_link'),
                    'impact_factor'           => $request->input('impact_factor'),
                    'ranking_and_category'    => $request->input('ranking_and_category'),
                    'eic_detail'              => $request->input('eic_detail'),
                    'flyer_link'              => $request->input('flyer_link'),
                    'journal_banner'          => $request->input('journal_banner'),
                    'left_panel'              => $request->input('left_panel'),
                    'right_panel'             => $request->input('right_panel'),
                    'journal_status'          => $request->input('journal_status'),
                    'continues_publication_journal' => $request->input('continues_publication_journal'),
                    'IsOpenAccess'            => $request->input('IsOpenAccess'),
                    'price'                   => $request->input('price'),
                    'epub_price'              => $request->input('epub_price'),
                    'journal_rental'          => $request->input('journal_rental'),
                    'journal_submenus'        => $request->input('journal_submenus'),
                    'social_media_link'       => $request->input('hdnsocial'),
                    'created'                 => time(),
                    'created_by'              => $user->id,
                );

                $journal_id = Journal::Add($add_journal);

                $add_journal['journal_id'] = $journal_id;

                //----------------------Upload Flyer files-------------------------------

                if ($request->hasFile('flyer_link')) {
                    $flyer_link = $request->file('flyer_link');
                    $flyer_Name = $flyer_link->getClientOriginalName();
                    if (!is_dir($journal_image_path)) {
                        mkdir($journal_image_path, 0755, true);
                    }

                    $flyer_link->move($journal_image_path, $flyer_Name);

                    $update_file_name['flyer_link'] = $flyer_Name;
                    Journal::where('journal_id', $journal_id)->update($update_file_name);
                }

                //-------------------Inert into Disease Journal table---------------

                $disease_id = $request->input('disease_id');

                if (!empty($disease_id)) {
                    for ($b = 0; $b < count($disease_id); $b++) {
                        $add_journal_disease[] = array(
                            'disease_id' => $disease_id[$b],
                            'journal_id' => $journal_id
                        );

                        $log_journal_disease['disease'][$b] = $add_journal_disease;
                    }
                    $disease = Disease::AddDiseaseJournal($add_journal_disease);
                }
                //-------------------Inert into Subject Journal table---------------

                $subject_id = $request->input('subject_id');
                if (!empty($subject_id)) {
                    for ($c = 0; $c < count($subject_id); $c++) {
                        $add_journal_subject[] = array(
                            'subject_id' => $subject_id[$c],
                            'journal_id' => $journal_id
                        );

                        $log_journal_subject['subject'][$c] = $add_journal_subject;
                    }
                    $subject = Subject::AddSubjectJournal($add_journal_subject);
                }

                //-------------------Inert into Indexing Journal table---------------

                $index_id = $request->input('index_id');
                if (!empty($index_id)) {
                    for ($d = 0; $d < count($index_id); $d++) {
                        $add_journal_indexing[] = array(
                            'index_id'           => $index_id[$d],
                            'journal_id'         => $journal_id,
                            'created_on'         => time(),
                            'created_by'         => $user->id,
                            'ip'                 => ip2long($request->ip()),
                        );

                        $log_journal_indexing['indexing'][$d] = $add_journal_indexing;
                    }
                    $indexing_list = Indexing::AddIndexingJournal($add_journal_indexing);
                }

                //-------------------Inert into Node Meta table---------------

                $add_node_meta = array(
                    'nid'           => $node_id,
                    'title'         => $request->input('title'),
                    'abstract'      => $request->input('meta_abstract'),
                    'canonical_url' => $request->input('meta_canonical_url'),
                    'copyright'     => $request->input('meta_copyright'),
                    'description'   => $request->input('meta_description'),
                    'keywords'      => $request->input('meta_keywords')
                );

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

                $log_meta['meta'] = $add_node_meta;
                //-----------------------------Insert into log table-----------------------------------

                $log     = array_merge($add_node, $add_journal, $log_journal_disease, $log_journal_subject, $log_journal_indexing, $log_meta,);
                $add_log = array(
                    'content_id'      => $journal_id,
                    'content_type_id' => config('constants.log_content_types.Journal'),
                    '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/journals');
            }
            //-------------------------------------------------------------------------------------
             return Redirect::to('admin/journals/' . $journal_id . '/edit');
            //return redirect()->route('journal.index')->with('success', 'Journal has been added.');
        }
    }

    //-----------------------Journal Rental----------------
    public function ajax_SELECT_Rental_Details($request)
    {

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

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

            DB::beginTransaction();

            $add_rental['journal_id']          = $request->get('journal_id');
            $add_rental['rental_price']         = $request->get('rental_price');
            $add_rental['rental_hours'] = $request->get('rental_hours');

            $add_rental['rental_id'] = $rental_id = Journal::InsertJournalRentalDetail($add_rental);

            $add_log = array(
                'content_id'      => $rental_id,
                'content_type_id' => config('constants.log_content_types.Journal_Rental'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($add_rental),
                '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_rental), 200);
    }

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

            DB::beginTransaction();

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

            $update_rental['journal_id']          = $request->get('journal_id');
            $update_rental['rental_id']           = $request->get('rental_id');
            $update_rental['rental_price']        = $request->get('rental_price');
            $update_rental['rental_hours']        = $request->get('rental_hours');

            $id = Journal::InsertRentalDetail($update_rental);

            $add_log = array(
                'content_id'      => $rental_id,
                'content_type_id' => config('constants.log_content_types.Journal_Rental'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($update_rental),
                '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_rental), 200);
    }

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

            DB::beginTransaction();

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

            $log = (array) Journal::GetJournalRentalDetail($rental_id, 'rental_id');

            $add_log = array(
                'content_id'      => $rental_id,
                'content_type_id' => config('constants.log_content_types.Journal_Rental'),
                '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);

            Journal::RemoveJournalRentalDetail($rental_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);
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        echo "hello";
        // return view('admin.show',compact('journal'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $journaldisease=array();
        $journalsubject=array();
        $journalindexing = array();
        $user = Auth::user()->id;

        $selected_journal = Journal::GetJournalById($id);
        //  print_r($selected_journal); die;
        $selected_meta = Meta::NodeMeta($selected_journal->nid);

        $selected_subject = Subject::SubjectJournal($selected_journal->journal_id, 'journal_id');
        foreach ($selected_subject as $key => $value) {
            $journalsubject[] = $value->subject_id;
        }

        $selected_indexing = Indexing::IndexingJournal($selected_journal->journal_id, 'journal_id');
        foreach ($selected_indexing as $key => $value) {
            $journalindexing[] = $value->index_id;
        }

        $selected_disease = Disease::DiseaseJournal($selected_journal->journal_id, 'journal_id');
        foreach ($selected_disease as $key => $value) {
            $journaldisease[] = $value->disease_id;
        }
        //------Subject List---------
        $temp = rtrim(Subject::display_parent(),'_');
        $option = explode('_', $temp);
        $arr = array();
        if ($temp != '') 
        {   
            //disease=1_diabetes=2_
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $arr[0] = 'Please Select';
                    $arr[$id] = $name;
                }
            }
        } else {
            $arr[0] = 'Please Select';
        }

        //------Indexing List---------
        $temp = rtrim(Indexing::display_parent(), '_');
        $option = explode('_', $temp);
        $indexing_agencies = array();
        if ($temp != '') {
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $indexing_agencies[0] = 'Please Select';
                    $indexing_agencies[$id] = $name;
                }
            }
        } else {
            $indexing_agencies[0] = 'Please Select';
        }

        $disease      = Disease::DiseaseParent();
        $journal_type = Journal::JournalType();
        $publisher    = Journal::Publisher();
        $mulLangdata  = Journal::getLanguageByJournal($selected_journal->journal_id);
        $multilanguage = MultiLanguage::where('isactive',1)->get();
        $param = array();
        $param['journal_id'] = $selected_journal->journal_id;
        $journal_section  = Journal::GetJournalSection($param);
        
        return view('admin.journal.addjournal')->with(['user' => $user, 'subject' => $arr, 'disease' => $disease, 'journal_type' => $journal_type, 'publisher' => $publisher, 'selected_journal' => $selected_journal, 'selected_meta' => $selected_meta, 'journalsubject' => $journalsubject, 'journaldisease' => $journaldisease, 'multilanguage' => $multilanguage, 'mulLangdata' => $mulLangdata, 'journal_section' => $journal_section, 'indexing' => $indexing_agencies, 'journalindexing' => $journalindexing]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $update_journal      = array();
        $log_journal_disease = array();
        $log_journal_subject = array();
        $log_journal_indexing = array();
        $log_meta            = array();

        //-------------- Journal Validation------------------
        $validator = Validator::make($request->all(), [
            'subject_id'     => 'required',
            'doi' => 'nullable|min:6|max:50|unique:journal,doi,'.$id.',journal_id',
            'journal_status' => 'required',
            'journal_type'   => 'required',
            'IsOpenAccess'   => 'required',
            'title'          => 'required',
            'subtitle'       => 'required',
            'eissn'          => 'required',
            'flyer_link'     => 'mimes:pdf',
            // 'rental_price'    => 'required_if:journal_rental,'
        ]);

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

            try {
// try transaction start here for data integrity

                DB::beginTransaction();

                $journal_id  = $request->input('journal_id');
                $journal_nid = $request->input('journal_nid');
                $user        = Auth::user();

                //----------------------Upload journal image-------------------------------
                $journal_obj = Journal::GetJournalById($journal_id);
                $file_name   = $journal_obj->image_file_name;

                $journal_image_path = config('constants.admin.root_path') . 'JOURNALS/BEN/' . $request->input('subtitle');
                if ($request->hasfile('image_file_name')) {
                    //File::delete(base_path() . '/public/assets/images/journals/' . $file_name);
                    $image_file = $request->file('image_file_name');

                    $file_name = $image_file->getClientOriginalName();
                    if (!is_dir($journal_image_path)) {
                        mkdir($journal_image_path, 0755, true);
                    }
                    $image_file->move($journal_image_path, $file_name);
                }
                //---------------------Update journal table--------------------

                $update_journal = array(
                    'journal_id'              => $journal_id,
                    'nid'                     => $journal_nid,
                    'image_file_name'         => $file_name,
                    'publisher_id'            => $request->input('publisher_id'),
                    'journal_type'            => $request->input('journal_type'),
                    'title'                   => $request->input('title'),
                    'journal_email'           => $request->input('journal_email'),
                    'formerly_title'          => $request->input('formerly_title'),
                    'doi'                     => $request->input('doi'),
                    'org_impact_factor'       => $request->input('org_impact_factor'),
                    'issn'                    => $request->input('issn'),
                    'eissn'                   => $request->input('eissn'),
                    'signature'               => $request->input('signature'),
                    'description'             => $request->input('description'),
                    'editorial_policy'        => $request->input('editorial_policy'),
                    'guideline_for_reviewers' => $request->input('guideline_for_reviewers'),
                    'ifa'                     => $request->input('ifa'),
                    'aims_and_scope'          => $request->input('aims_and_scope'),
                    'facebook_like_api_code'  => $request->input('facebook_like_api_code'),
                    'jms_link'                => $request->input('jms_link'),
                    'impact_factor'           => $request->input('impact_factor'),
                    'ranking_and_category'    => $request->input('ranking_and_category'),
                    'eic_detail'              => $request->input('eic_detail'),
                    'journal_banner'          => $request->input('journal_banner'),
                    'left_panel'              => $request->input('left_panel'),
                    'right_panel'             => $request->input('right_panel'),
                    'journal_status'          => $request->input('journal_status'),
                    'IsOpenAccess'            => $request->input('IsOpenAccess'),
                    'continues_publication_journal' => $request->input('continues_publication_journal'),
/*                      'trendmd_id'              => $request->input('trendmd_id'),*/
                    'price'                   => $request->input('price'),
                    'epub_price'              => $request->input('epub_price'),
                    'journal_submenus'        => $request->input('journal_submenus'),
                    'journal_rental'          => $request->input('journal_rental'),
                    'social_media_link'       => $request->input('hdnsocial'),                    
                    'updated_by'              => $user->id,
                );

                if (!empty($request->input('flyer_link'))) {
                    $update_journal = array(
                    'flyer_link' => $request->input('flyer_link')
                    );
                }

                Journal::JournalUpdate($update_journal);

                //----------------------Upload Flyer files-------------------------------

                if ($request->hasFile('flyer_link')) {
                    $flyer_link = $request->file('flyer_link');
                    $flyer_Name = $flyer_link->getClientOriginalName();
                    if (!is_dir($journal_image_path)) {
                        mkdir($journal_image_path, 0755, true);
                    }

                    $flyer_link->move($journal_image_path, $flyer_Name);

                    $update_file_name['flyer_link'] = $flyer_Name;
                    Journal::where('journal_id', $journal_id)->update($update_file_name);
                }
                //-------------------Inert into Disease Journal table---------------

                Disease::DeleteDiseaseJournal($journal_id);

                $disease_id = $request->input('disease_id');
                if (!empty($disease_id)) {
                    for ($b = 0; $b < count($disease_id); $b++) {
                        $add_journal_disease[] = array(
                            'disease_id' => $disease_id[$b],
                            'journal_id' => $journal_id
                        );

                        $log_journal_disease['disease'][$b] = $add_journal_disease;
                    }
                    $disease = Disease::AddDiseaseJournal($add_journal_disease);
                }
                //-------------------Inert into Subject Journal table---------------

                Subject::DeleteSubjectJournal($journal_id);

                $subject_id = $request->input('subject_id');

                for ($c = 0; $c < count($subject_id); $c++) {
                    $add_journal_subject[] = array(
                        'subject_id' => $subject_id[$c], 'journal_id' => $journal_id
                    );

                    $log_journal_subject['subject'][$c] = $add_journal_subject;
                }
                $subject = Subject::AddSubjectJournal($add_journal_subject);

                //-------------------Inert into Indexing Journal table---------------

                Indexing::DeleteIndexingJournal($journal_id);
                $index_id = $request->input('index_id');
                if (!empty($index_id)) {
                    for ($d = 0; $d < count($index_id); $d++) {
                        $add_journal_indexing[] = array(
                            'index_id'           => $index_id[$d],
                            'journal_id'         => $journal_id,
                            'created_on'         => time(),
                            'created_by'         => $user->id,
                            'ip'                 => ip2long($request->ip()),
                        );

                        $log_journal_indexing['indexing'][$d] = $add_journal_indexing;
                    }
                    $indexing_list = Indexing::AddIndexingJournal($add_journal_indexing);
                }
                //-------------------Inert into Node Meta table---------------
                Meta::DeleteMeta($journal_nid);

                $add_node_meta = array(
                    'nid'           => $journal_nid,
                    'title'         => $request->input('title'),
                    'abstract'      => $request->input('meta_abstract'),
                    'canonical_url' => $request->input('meta_canonical_url'),
                    'copyright'     => $request->input('meta_copyright'),
                    'description'   => $request->input('meta_description'),
                    'keywords'      => $request->input('meta_keywords'),
                );

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

                $log_meta['meta'] = $add_node_meta;

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

                $log     = array_merge($update_journal, $log_journal_disease, $log_journal_subject, $log_journal_indexing, $log_meta);
                $add_log = array(
                    'content_id'      => $journal_id,
                    'content_type_id' => config('constants.log_content_types.Journal'),
                    '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::to('admin/journals/' . $journal_id . '/edit');
            }
            //-------------------------------------------------------------------------------------
            return Redirect::to('admin/journals/' . $journal_id . '/edit');
            //return redirect()->route('journal.index')->with('success', 'Journal has been updated.');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id = "", Request $request)
    {

        $journal      = array();
        $subject_list = array();
        $disease_list = array();
        $node         = array();
        $meta         = array();
        $article_list = array();
        $issue_list   = array();
        $volume_list  = array();

        $nid             = $request->input('id');
        $p['journal_id'] = $id;

        $article_list = Article::GetarticleByJournalId($id, 'journal_id');
        $issue_list   = Issue::GetIssueById($p);

        $param_j['journal_id'] = $p['journal_id'];
        $volume_list           = Volume::GetVolumeTitleById($param_j);

        $param_j['journal_id'] = $p['journal_id'];
        $journal               = (array) Journal::GetJournalById($param_j);
        $subject               = Subject::SubjectJournal($id, 'journal_id');
        $disease               = Disease::DiseaseJournal($id, 'journal_id');
        $node                  = (array) Node::GetNode($nid);
        $meta                  = (array) Meta::NodeMeta($nid);

        foreach ($subject as $key => $value) {
            $subject_list['subject'][] = $value->subject_id;
        }

        foreach ($disease as $key => $value) {
            $disease_list['disease'][] = $value->disease_id;
        }
        //print_r($subject_list);die;

        if (isset($article_list[0]) || isset($issue_list[0]) || isset($volume_list[0])) {
            return redirect()->route('journals.index')->with('error', 'Journal Child Table Record Already Exist');
        } else {

            try {
// try transaction start here for data integrity

                DB::beginTransaction();

                Subject::DeleteSubjectJournal($id);
                Disease::DeleteDiseaseJournal($id);
                Node::DeleteNode($nid);
                Meta::DeleteMeta($nid);
                Journal::DeleteJournal($id);

                $log = array_merge($journal, $subject_list, $disease_list, $node, $meta);

                $add_log = array(
                    'content_id'      => $id,
                    'content_type_id' => config('constants.log_content_types.Journal'),
                    '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::to('admin/journals');
            }
            //-------------------------------------------------------------------------------------
            return redirect()->route('journals.index')->with('success', 'Journal delete successfully.');
        }
    }

    /*
    ----------------------------frontend journal listing-----------------------------------
     */
    public function GetJournalList(Request $request)
    {
		//dd($request);
        $alphabet       = "";
        $journal_search = "";
        $year           = "";
        $search_year    = "";

        if (strpos($request->path(), 'browse-by-subscribe') !== false) {
            session(['mysubscribption' => true]);
        }
        if (strpos($request->path(), 'bypublication') !== false) {

            session()->forget('mysubscribption');
        }

        if (isset($request->alphabet)) {
            if (strlen($request->alphabet) == 4) {
                if (is_numeric($request->alphabet)) {
                    $search_year = trim($request->alphabet);
                }
            } else {
                $alphabet = $request->alphabet;
            }
        }
        if (isset($request->btnjournalsearch)) {
            $journal_search = $request->journal_search;   

            if(strpos($journal_search, '10.2174/')!== false){
                
                $article_obj = Article::GetArticleByDOI($journal_search);
                if(!empty($article_obj)){
                    return Redirect::to('article/' . $article_obj->article_id);
                }
            }
        }

        $journal_list = Journal::GetJournalTitle();

        $year = Journal::GetYear();

        if (session()->has('mysubscribption')) {
			
            if (session()->has('ip_base_access') || session()->has('user_base_access')) {
				$user_id = session()->get('user_id');
				$param['user_id'] = $user_id;
			}

			$param['letter'] = $alphabet;
			$param['journal_name'] = $journal_search;
			$param['year'] = $search_year;
			$param['ip_address'] = ip2long($request->ip());
			
            $journal = Journal::SearchSubscriptionList($param);
			
            $searchFormRoute = 'browsebysubscribe';
        } else {
            $journal         = Journal::SearchJournalList($alphabet, $journal_search, $search_year);
            $searchFormRoute = 'bypublication';
        }
        //dd($journal);
        // $volume_list     = Volume::GetVolume($param);

        return view('bypublication', with(['journal' => $journal, 'journal_list' => $journal_list, 'year' => $year, 'alphabet' => $alphabet, 'searchFormRoute' => $searchFormRoute]));
    }

    //----------for journal home page main function which display all tab pages with switch cae----------------------//

    public function GetJournalDetails(Request $request, $journal_id, $page_name = "", $id = "")
    {
		$reviewers=array();
       if(!is_numeric($journal_id))
       {
            if(strlen($journal_id) < 10)
            {
                $journal = Journal::GetJournalByCode($journal_id);
                if(!empty($journal))
                {
                    $journal_id=$journal->journal_id;
                }
                else
                {
                    return redirect('/');
                }
            }
            else if(strlen($journal_id) > 10)
            {
                $journal = Journal::GetJournalByTitle($journal_id);
                if(!empty($journal))
                {
                    $journal_id=$journal->journal_id;
                }
                else
                {
                    return redirect('/');
                }
            }
            else
            {
                    return abort(404);
            }
        }

        $page = isset($request->page) ? $request->page : '';        
        $ajax = $request->get('ajax');

        if ($page_name == 'free-copies-online' || $page_name == 'thematic-issue' || $page_name == 'subscribe' || $page_name == '') 
		{
            $template = 'journal';
        } 
        elseif ($page_name == 'current-issue') 
        {
            $current_issue = $this->GetJournalCurrentIssue($journal_id);
            return Redirect::to('issue/' . $current_issue . '/1');
        } 
        elseif ($page_name == 'about-journal') 
        {
            $template = 'about_journal';
        } 
        elseif ($page_name == 'download_flyer') 
        {
            $file_path = Crypt::decrypt($id);
            if (file_exists($file_path)) 
			{
                return response()->download($file_path);
            } 
			else 
			{
                Session::flash('message', " File does not exist!");
                return back();
            }
        } 
        else 
        {  
			if($page_name == 'reviewers'){
				$jms_journal = Journal::GetJournalById($journal_id);
                $reviewers = Journal::getReviewersByJournalID($jms_journal->jms_jcode);                
            }
            $template = 'journal_menu';
        }

        if ($ajax == true) {
            if ($template == 'journal') {
                return $this->GetVolumesWithAjax($journal_id, $page_name);
            }
            if ($template == 'journal_menu') {
                return $this->GetArticlesWithAjax($journal_id, $page_name, $id);
            }

        } 
        else 
        {
            $journal_search      = Journal::GetJournalTitle();
            $latest_issue       = Issue::getcurrentissue($journal_id);
            $country             = Country::GetCountryList();
            $related_journal     = Subject::RelatedJournalBySubjectId($journal_id);
            $related_ebook       = Subject::RelatedJournaleBookBySubjectId($journal_id);
            $subs_category       = Journal::GetSubsCategory($journal_id);
            $param['journal_id'] = $journal_id;
            $param['status']     = 1;
            $section             = Journal::GetJournalSection($param);
            $section_detail      = array();
            $article_list        = array();
            $continues_publication_journal = array();

            if ($id == 1) {
                $page_name = 'Article Ahead of Print';
            }
            if ($id == 4) {
                $page_name = 'Abstract Ahead of Print';
            }
            $journal         = Journal::GetJournalById($journal_id);
			
            $journal_indexing   = Indexing::GetAllJournalIndexingList($journal_id);

            if($journal->IsOpenAccess==1 && ($id==1 || $id==4) ){
                $page_name = 'Early Views';
            }
            //-- Check journal section and there articles--//
            if($page_name == "section" && isset($id) && $id > 0)
            {
                $page_name = "section-detail";
                $param['js_id'] =  $id;  
                $section_detail  = Journal::GetJournalSection($param)[0];
                $article_list = $this->GetArticlesWithAjax($journal_id, $page_name, $id);
            }

            $JournalSubjects = Subject::GetSubjectByJournalID($journal_id);
            $JournalDiseases = Disease::DiseaseJournal($journal_id, 'journal_id');

            if (!empty($journal->nid)) {
            $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='https://'.$_SERVER['HTTP_HOST'].'/journal/'.$journal->journal_id;
                }
            }

            $count_epub_article = Article::GetTrackList($journal_id, 1, 0)->count();
            $count_epub_abstract = Article::GetTrackList($journal_id, 4, 0)->count();
            if ($page_name == 'editors-choice') {
                $page_name ="editor's choice";
            }

            $publication_journal = Article::GettAllContinuePublicationJournal();
            foreach ($publication_journal as $publication_journals) {
                $continues_publication_journal[] = $publication_journals->subtitle;
            }

            return View::make($template, with(['journal' => $journal, 'latest_issue' => $latest_issue, 'node_meta' => $node_meta, 'param' => $param, 'page_name' => $page_name, 'related_journal' => $related_journal, 'related_ebook' => $related_ebook, 'journal_search' => $journal_search, 'country' => $country, 'journal_id' => $journal_id, 'JournalSubjects' => $JournalSubjects, 'JournalDiseases' => $JournalDiseases, 'subs_category' => $subs_category, 'count_epub_article' => $count_epub_article, 'count_epub_abstract' => $count_epub_abstract, 'section' => $section, 'id' => $id, 'section_detail' => $section_detail, 'article_list' => $article_list, 'page' => $page, 'journal_indexing' => $journal_indexing, 'continues_publication_journal' => $continues_publication_journal,'reviewers'=>$reviewers]));
        }
    }
    //---------------------------for journal home page----------------------------//



    public function GetJournalCompleteDetail($journal_id)
    {

        $volume_list = Volume::GetAllVolumeByJournalID($journal_id);

        $issue_list = Issue::GetAllIssueByJournalID($journal_id);

        $issue_count = count($issue_list);

        return with(['volume_list' => $volume_list, 'issue_list' => $issue_list, 'issue_count' => $issue_count]);
    }

    public function GetVolumesWithAjax($journal_id, $page_name)
    {
        if ($page_name == 'free-copies-online') {
            $volumes = Journal::getFreeOpenAccess_IssuesVolumes($journal_id);
            return response()->json(array('volumes' => $volumes), 200);
        } else if ($page_name == 'thematic-issue') {
            $volumes = Volume::GetIssueExistedVolumeByJournalID($journal_id, 1);
            return response()->json(array('volumes' => $volumes), 200);
        } else {
            // if articles dont exist in issues skip volume
            $volumes = Volume::GetIssueExistedVolumeByJournalID($journal_id);

            if ($volumes) {
				// Check Content Access Volume Level For Volume
				$volumes = $this->CheckContentAccessVolumeLevelForVolume($journal_id,$volumes,$page_name);
				
				// Check User Access Volume Level For (Volume,Issue,Article)
                if (session()->has('ip_base_access') || session()->has('user_base_access')) {
					$volumes = $this->CheckUserAccessVolumeLevelForVolume($journal_id,$volumes,$page_name);
				}
            }

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

    public function GetIssuesWithAjax(Request $request)
    {
        header('Access-Control-Allow-Origin: *');
        $ajax      = $request->get('ajax');
        $action    = $request->get('action');
        $page_name = $request->get('page_name');
		
        if ($ajax == true) {
            if ($action == 'SELECT') {
                if ($page_name == 'free-copies-online') {
                    $volume_id = $request->get('volume_id');
                    $issues    = Journal::getFreeOpenAccess_Issues($volume_id);
                } else if ($page_name == 'thematic-issue') {
                    $volume_id = $request->get('volume_id');
                    $issues    = Issue::getAllIssuesUnderVolumes($volume_id, 1);
                } else {
                    $param['volume_id']   = $volume_id   = $request->get('volume_id');
                    $param['is_uploaded'] = 1;
                    $issues               = Issue::GetIssueById($param);
                    
                    //$volume_obj = Volume::GetVolumeById(array('volume_id' => $volume_id));
					
                    if ($issues) {
                        if (!empty($page_name) && $page_name == 'subscribe') {
							//Content Access Issue Level
							
							$issues = $this->CheckContentAccessIssueLevel($volume_id,$issues,$page_name);
							
							//User Access Issue Level
                            if (session()->has('ip_base_access') || session()->has('user_base_access')) {
								$issues = $this->CheckUserAccessIssueLevel($volume_id,$issues,$page_name);	
							}
                        } else {
							//Content Access Volume Level
							$result = $this->CheckContentAccessVolumeLevelForIssue($volume_id,$issues,$page_name);
							
							$issues = $result[0];
							$oa_vol_lvl = $result[1];
							
                            if ($oa_vol_lvl == false) {
								//Content Access Issue Level
								$issues = $this->CheckContentAccessIssueLevel($volume_id,$issues,$page_name);
								
								//User Access Volume Level -- No need To Check -- 
								
								//User Access Issue Level
                                if (session()->has('ip_base_access') || session()->has('user_base_access')) {
									$issues = $this->CheckUserAccessIssueLevel($volume_id,$issues,$page_name);	
								}
                            }
                        }
                    }
                }

                if ($issues != null) {
                    return response()->json(array('issues' => $issues), 200);
                }
            }
        }
    }

    public function GetArticlesWithAjax($journal_id, $page_name, $id)
    {

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

        if ($page_name == 'current-issue') {
            $issue_id = $this->GetJournalCurrentIssue($journal_id);
            $articles = Article::getAllArticlesByIssueID($issue_id, 5);
        }
        if ($page_name == 'editors-choice') {
            $articles = $this->GetSpecialArticlesList($journal_id, 1);
        } elseif ($page_name == 'open-access-articles') {
            $article_list = $this->GetJournalFreeOpenAccessArticles($journal_id, 2);
            $articles     = $article_list['article_list'];
        } elseif ($page_name == 'highlighted-article') {
            $articles = $this->GetSpecialArticlesList($journal_id, 2);
        } elseif ($page_name == 'most-popular-articles') {
            $articles = $this->GetSpecialArticlesList($journal_id, 3);
        } elseif ($page_name == 'most-cited-articles') {
            $articles = $this->GetMostCitationArticleList($journal_id,$journal->issn);            
        } elseif ($page_name == 'most-download-articles' || $page_name == 'most-accessed-articles') {
            $articles = $this->GetMostDownloadedArticleList($journal->nid);
        } elseif ($page_name == 'track') {                                              
            $article_list    = $this->GetTrackList($journal_id, $id);
            $articles     = $article_list['article_list'];
        } elseif ($page_name == 'section-detail') {
            $articles    = $this->GetJournalSectionArticles($journal_id, $id, 20); 
        } 
        else {
            $articles = Article::getAllArticlesByIssueID($issue_id, 5);
        }
		
		$articles = $this->CheckUserAccessonArticle($articles);

        if ($articles) {
            foreach ($articles as $key => $article) {
               
            $articles[$key]->title = strip_tags(html_entity_decode($article->title));

                $param = encrypt(array('readpdf',$article->article_id,config('constants.admin.token'),$article->content_download_type));

                if (isset($article->type) && $article->type == "111") {
                    $articles[$key]->terms_url = route('termstrial', ['access_type' => $article->type,'content_id' => $article->article_id,'param' => $param]);
                } else {
                    $articles[$key]->terms_url = route('terms', ['content_id' => $article->article_id,'param' => $param]);
                }
                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $articles[$key]->terms_popup = false;
            }
        }
        if ($page_name == 'section-detail') 
        {
            return $articles;
        }
        else
        {
        return response()->json(array('articles' => $articles), 200);
    }

    }

    public function GetJournalCurrentIssue($journal_id)
    {
        $c_issue = Issue::getcurrentissue($journal_id);
        if (!empty($c_issue[0])) {
            $c_issue = $c_issue[0];
            return $c_issue->issue_id;
        }
    }

    public function GetTrackList($journal_id, $track_id)
    {
        $article_list = array();
        $article_list = Article::GetTrackList($journal_id, $track_id, 15);
        //dd($article_list->items()[0]['authors']);
        $a = 0;
        if(!empty($article_list)){
            foreach ($article_list as $key => $article) {
			
            //create encrypt param with article nid
                $article_list[$key]->param      = encrypt($article->nid);
                $article_list[$key]->csrf_token = csrf_token();

            $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');

            $AuthorNames = '';
            if ($article_authors) {
                    $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
            } else {
                    $article_list->items()[$a]->authors = $AuthorNames;
                }
            $a++;
        }
        }
        return with(['article_list' => $article_list]);
    }


    public function GetJournalFreeCopyOnline($journal_id)
    {
        $volume_list = Journal::getFreeOpenAccess_IssuesVolumes($journal_id);

        foreach ($volume_list as $volume) {
            $issue_list[$volume->volume_id] = (array) Journal::getFreeOpenAccess_Issues($volume->volume_id);
        }

        return with(['volume_list' => $volume_list, 'issue_list' => $issue_list]);
    }

    public function GetJournalFreeOpenAccessArticles($journal_id, $access_type)
    {
        $article_list = array();
        $article_list = Journal::GetFreeOpenAccessArticles($journal_id, $access_type);
        //dd($article_list->items()[0]['authors']);
        $a = 0;
        if(!empty($article_list)){
            foreach ($article_list as $key => $article) {

                //create encrypt param with article nid
                $article_list[$key]->param      = encrypt($article->nid);
                $article_list[$key]->csrf_token = csrf_token();
                $article_list[$key]->title      = htmlentities($article->title);
                $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');

                $AuthorNames = '';
                if ($article_authors) {
                    $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
                } else {
                    $article_list->items()[$a]->authors = $AuthorNames;
                }
                $a++;
            }
        }
        return with(['article_list' => $article_list]);
    }

    public function GetSpecialArticlesList($journal_id, $type)
    {
        $article_list = array();
        $article_list = Article::GetSpecialArticles($journal_id, $type, 10);
        // dd($article_list);
        $a = 0;
        if(!empty($article_list)){
            foreach ($article_list as $key => $article) {
                if ($article->is_epub == 0) {
                    $graphical_abstract_small                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/' . $article->issue . '/' . $article->graph_abs_sm_filename;
                    $graphical_abstract_large                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/' . $article->issue . '/' . $article->graph_abs_lg_filename;
                    $article_list[$key]->graphical_abstract_small_image = $graphical_abstract_small;
                    $article_list[$key]->graphical_abstract_large_image = $graphical_abstract_large;
                } elseif ($article->is_epub == 1) {
                    $graphical_abstract_small                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/EPUB/' . $article->issue . '/' . $article->graph_abs_sm_filename;
                    $graphical_abstract_large                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/EPUB/' . $article->issue . '/' . $article->graph_abs_lg_filename;
                    $article_list[$key]->graphical_abstract_small_image = $graphical_abstract_small;
                    $article_list[$key]->graphical_abstract_large_image = $graphical_abstract_large;
                } elseif ($article->is_epub == 2) {
                    $graphical_abstract_small                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/QUICKTRACK/' . $article->issue . '/' . $article->graph_abs_sm_filename;
                    $graphical_abstract_large                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/QUICKTRACK/' . $article->issue . '/' . $article->graph_abs_lg_filename;
                    $article_list[$key]->graphical_abstract_small_image = $graphical_abstract_small;
                    $article_list[$key]->graphical_abstract_large_image = $graphical_abstract_large;
                } elseif ($article->is_epub == 3) {
                    $graphical_abstract_small                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/EXPRESSTRACK/' . $article->issue . '/' . $article->graph_abs_sm_filename;
                    $graphical_abstract_large                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/EXPRESSTRACK/' . $article->issue . '/' . $article->graph_abs_lg_filename;
                    $article_list[$key]->graphical_abstract_small_image = $graphical_abstract_small;
                    $article_list[$key]->graphical_abstract_large_image = $graphical_abstract_large;
                } elseif ($article->is_epub == 5) {
                    $graphical_abstract_small                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/SUPPLEMENTARY/' . $article->issue . '/' . $article->graph_abs_sm_filename;
                    $graphical_abstract_large                           = '/images/graphical-abstract/' . $article->subtitle . '/' . $article->volume_name . '/SUPPLEMENTARY/' . $article->issue . '/' . $article->graph_abs_lg_filename;
                    $article_list[$key]->graphical_abstract_small_image = $graphical_abstract_small;
                    $article_list[$key]->graphical_abstract_large_image = $graphical_abstract_large;
                }

                $article_list[$key]->article_purchase = encrypt($article->nid);
                $article_list[$key]->article_download = encrypt($article->article_id . '||' . 'pdf' . '||' . $article->content_type_access_id);

                //create encrypt param with article nid
                $article_list[$key]->param      = encrypt($article->nid);
                $article_list[$key]->csrf_token = csrf_token();
                $article_array[$a]              = $article;

                $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');
                $AuthorNames     = '';
                if ($article_authors) {
                    $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
                } else {
                    $article_list->items()[$a]->authors = $AuthorNames;
                }

                $a++;
            }
        }
        // $article =  $article_array;
        return $article_list;
    }

    public function GetMostCitationArticleList($journal_id,$issn)
    {
        
        $pubyear = date('Y')-2;
        $queryData = array(
                'query' => 'ISSN("'.trim($issn).'") and PUBYEAR > '.$pubyear,
                'sort' => 'citedby-count',
                'view' => 'standard', 
                'count'=> 15,
                'httpAccept' => 'application/json', //'text/xml',                       
                'APIKey' => '292d0a8d3c5374ad5a929faad7dc7c4b'                      
        );         
/*        $queryData = array(
                'query' => 'ISSN("'.trim($issn).'") and PUBYEAR > 2017',
                'sort' => 'citedby-count',
                'view' => 'standard', 
                'httpAccept' => 'application/json', //'text/xml',                       
                'APIKey' => '292d0a8d3c5374ad5a929faad7dc7c4b'                      
        ); 
*/
        $elsevier_api_Url = 'https://api.elsevier.com/content/search/scopus?'.http_build_query($queryData,'&amp;','&');
        $arr = array();
        $articles=array();
        $citation_articles_doi=array();
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, $elsevier_api_Url);               
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        $output = curl_exec($ch); 
        curl_close($ch); 

        $articles = json_decode($output);
		if(!empty($articles)){
            foreach ($articles as $kkey => $val) {
                $arr = $val->entry;
            }
        

            $articles = (object) $arr;
            foreach($articles as $value){
            //for($i=0;$i<=count($articles); $i++){
                foreach($value as $k=>$v){
                    if($k=='prism:doi')
                    $citation_articles_doi[] = $v;
                    if($k=='citedby-count')
                    $citation_arr[] = $v;
                }
            }
        }
        if(!empty($citation_articles_doi)){
            for($m=0;$m<count($citation_articles_doi); $m++){
                
                DB::table('article')->where('doi', $citation_articles_doi[$m])->update(array('citation'=>$citation_arr[$m]));                    
            }
        }

        //$article_list = Article::GetmostcitationArticles($journal_id, 10);
        
        $article_list = DB::table('article as a')
                        ->selectRaw('a.article_id as article_id, a.publish_on,a.issue_id,a.volume_id,a.journal_id, a.nid,a.pmid,a.publish_on,a.elocator, a.title,a.altmetric_score,a.altmetric_url,a.kudos_url, first_page, last_page, 
                            page_count,abstract,ifnull(is_abstract,"y"), a.is_epub, a.graph_abs_sm_filename as graphical_abstract,
                            a.doi,m.month,y.year,v.volume_name, v.volume_id as volume_id , i.issue_id as issue_id , i.title as issue, at.type_name as article_type_name')
                        ->leftJoin('article_type as at' , 'at.art_type_id', '=', 'a.art_type') 
                        // ->leftjoin('journal_access as j', function($query) {$query->on('a.article_id', 'j.content_type_id')->on('j.content_type', '=', DB::raw("'a'"));})
                        ->leftJoin('issue as i' , 'a.issue_id', '=', 'i.issue_id') 
                        ->leftJoin('volume as  v' , 'v.volume_id', '=', 'a.volume_id') 
                        ->leftJoin('month as m' , 'i.month_id', '=', 'm.id') 
                        ->join('year as y', 'v.year_id', '=', 'y.id')
                        ->whereIn('a.doi',$citation_articles_doi)
                        ->whereRaw('a.is_uploaded = 1 and a.journal_id = '.$journal_id)
                        ->orderByRaw('cast(a.citation+0 as signed) desc')                       
                        ->paginate(50);
                        
            //---if record not found from services so display the article from database table---
            if(count($article_list) == 0)
            {
               $article_list = Journal::GetMostCitedArticles($journal_id,50);

            }

        $a = 0;
        foreach ($article_list as $key => $article) {       
            //create encrypt param with article nid
            $article_list[$key]->param      = encrypt($article->nid);
            $article_list[$key]->csrf_token = csrf_token();

            $article_array[$a] = $article;

            $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');
            $AuthorNames     = '';
            if ($article_authors) {
                $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
            } else {
                $article_list->items()[$a]->authors = $AuthorNames;
            }

            $a++;
        }
        // $article =  $article_array;
        return $article_list;
    }

    public function GetJournalSectionArticles($journal_id, $section_id, $page)
    {  
        $article_list = Article::getAllArticlesByIssueID(0,$page, $journal_id, $section_id);

        $a = 0;
        foreach ($article_list as $key => $article) {

            //create encrypt param with article nid
            $article_list[$key]->param      = encrypt($article->nid);
            $article_list[$key]->csrf_token = csrf_token();

            $article_array[$a] = $article;

            $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');
            $AuthorNames     = '';
            if ($article_authors) {
                $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
            } else {
                $article_list->items()[$a]->authors = $AuthorNames;
            }

            $a++;
        }

        // $article =  $article_array;
        return $article_list;
    }

    public function GetMostDownloadedArticleList($journal_nid)
    {
        $article_list = array();
        $article_list = Journal::getMostDownloadedArticles($journal_nid);

        $a = 0;
        if(!empty($article_list)){
            foreach ($article_list as $key => $article) {

                //create encrypt param with article nid
                $article_list[$key]->param      = encrypt($article->nid);
                $article_list[$key]->csrf_token = csrf_token();

                $article_array[$a] = $article;

                $article_authors = Author::GetAuthorsByContentId($article->article_id, 'article_id');
                $AuthorNames     = '';
                if ($article_authors) {
                    $article_list->items()[$a]->authors = $this->GetAuthorsFormat($article_authors);
                } else {
                    $article_list->items()[$a]->authors = $AuthorNames;
                }

                $a++;
            }
        }
        // $article =  $article_array;
        return $article_list;
    }

    public function GetThematicIssues($journal_id)
    {
        $issue_list  = Issue::getAllIssuesUnderVolumes($journal_id, 1);
        $issue_count = count($issue_list);

        return with(['issue_list' => $issue_list, 'issue_count' => $issue_count]);
    }

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

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

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

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



    //-------------Become_EBM_Review-----------------//
    public function Become_EBM_Review(Request $request)
    {
        try {
// try transaction start here for data integrity

                DB::beginTransaction();

                $this->validate($request, [
                    'cv.*' => 'mimes:jpeg,jpeg,png,doc,docx,pdf',
                    'email' => 'required|email|max:255',
                'captcha' => 'required|captcha'
                ], ['captcha.captcha' => 'Invalid captcha code.']);

            if($request->reg_type == "bcomexecutiveguesteditor")
            {
                $ebm_rev_data = array(
                    'reg_type'                      => $request->input('reg_type'),
                    'journal_id'                    => $request->input('journal_id'),
                    'first_name'                    => $request->input('first_name'),
                    'last_name'                     => $request->input('last_name'),
                    'country'                       => $request->input('country'),
                    'city'                          => $request->input('city'),
                    'email'                         => $request->input('email'),
                    'expertise'                     => $request->input('expertise'),
                    'comments'                      => $request->input('comments'),
                    'title_thematic_issue_proposal' => $request->input('title_thematic_issue_proposal'),
                    'proposal_summary'              => $request->input('proposal_summary'),
                    'ip_address'                    => ip2long($request->ip()),
                    'updated_on'                    => time(),
                );
            }
            else
            {
                $ebm_rev_data = array(
                    'reg_type'           => $request->input('reg_type'),
                    'journal_id'         => $request->input('journal_id'),
                    'first_name'         => $request->input('first_name'),
                    'last_name'          => $request->input('last_name'),
                    'country'            => $request->input('country'),
                    'city'               => $request->input('city'),
                    'email'              => $request->input('email'),
                    'expertise'          => $request->input('expertise'),
                    'comments'           => $request->input('comments'),
                    'ip_address'         => ip2long($request->ip()),
                    'updated_on'         => time(),
                );
            }

                $ebm_rev_id = Journal::Add_EBM_Review($ebm_rev_data);

                    if (isset(Auth::user()->id)) {
                        $login_id = Auth::user()->id;
                    } else {
                        $login_id = 0;
                    }
                
                $add_log = array(
                    'content_id'      => $ebm_rev_data['journal_id'],
                    'content_type_id' => config('constants.log_content_types.Become_EBM_Review'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($ebm_rev_data),
                    'created_dated'   => time(),
                    'created_by'      => $login_id,
                    'ip'              => ip2long($request->ip()),
                );
                //$log = Log::AddLog($add_log);

                DB::commit();
                if ($ebm_rev_id > 0) {
                    $journal = Journal::GetJournalById($request->input('journal_id'));
                    $ebm_rev_data['journal_title'] = $journal->title;

                if ($ebm_rev_data['reg_type'] == 'bcomexecutiveguesteditor') 
                {
                    $to = "nuzhat@benthamscience.net";
                } 
                else 
                {
                        $to = "noureenazhar@benthamscience.net";    
                    }
                    
                    if($ebm_rev_data['reg_type']=='eabm'){      
                        $reg_type_text = "Become an EABM";
                }
                elseif ($ebm_rev_data['reg_type'] == 'reviewer') {
                        $reg_type_text = "Become a Reviewer";
                }
                elseif ($ebm_rev_data['reg_type'] == 'editorcall') {
                        $reg_type_text = "Call For Editor";
                    }
                elseif ($ebm_rev_data['reg_type'] == 'bcomexecutiveguesteditor') {
                    $reg_type_text = "Become An Executive Guest Editor";
                }
                
                    $from = 'admin@eurekaselect.com';
                    //$cc   = 'azhar@benthamscience.net';
                    $cc      = env('email_admin', 'email_xolva_2','email_support_2');
                    $bcc  = 0;
                    $attachments = $request->file('cv');
                    $ebm_rev_data['reg_type'] = $reg_type_text;
                    
                    $subject = "Eurekaselect: ".$reg_type_text." Registration";

                   SendSmtpMail('email_template.become_ebm_reviewer', $ebm_rev_data, $to, $from, $subject, 'Admin', $cc, $bcc, $attachments);

                return back()->with('success', '<strong>Thank you</strong> We appreciate you taking the time to fill out the '.$reg_type_text.' form.
                        Your submission has been emailed to the concerned department.
                       If your request requires a reply, we will be in contact with you shortly. In the meantime, please continue to browse the site.
                       Use the links above to get to where you want to go!');
            }
        } catch (Exception $e) {

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

    //-------------Proposal (Book/Journal)-----------------//
    public function Proposal(Request $request)
    {  
        try {  
            // try transaction start here for data integrity

            DB::beginTransaction();

            $this->validate($request, [
                'cv.*' => 'mimes:jpeg,jpeg,png,doc,docx,pdf',
                'email' => 'required|email|max:255',
                'captcha' => 'required|captcha'
                ], ['captcha.captcha' => 'Invalid captcha code.']);

            if($request->reg_type == "journalproposal")
            {
                $proposal_data = array(
                    'reg_type'                  => $request->input('reg_type'),
                    'journal_id'                => $request->input('journal_id'),
                    'title_proposed_journal'    => $request->input('title_proposed_journal'),
                    'field_of_experties'        => $request->input('field_of_experties'),
                    'affiliation'               => $request->input('affiliation'),
                    'hindex'                    => $request->input('hindex'),
                    'aims_and_scope'            => $request->input('aims_and_scope'),
                    'comments'                  => $request->input('comments'),
                    'title'                     => $request->input('title'),
                    'first_name'                => $request->input('first_name'),
                    'last_name'                 => $request->input('last_name'),
                    'country_id'                => $request->input('country'),
                    'city'                      => $request->input('city'),
                    'email'                     => $request->input('email'),
                    'ip'                        => ip2long($request->ip()),
                    'updated_on'                => time(),
                );
            }
            else
            {
                $proposal_data = array(
                    'reg_type'              => $request->input('reg_type'),
                    'journal_id'            => $request->input('journal_id'),
                    'title_proposed_book'   => $request->input('title_proposed_book'),
                    'editor_name'           => $request->input('editor_name'),
                    'editor_affiliation'    => $request->input('editor_affiliation'),
                    'list_of_publications'  => $request->input('list_of_publications'),
                    'book_description'      => $request->input('book_description'),
                    'proposal_keywords'     => $request->input('proposal_keywords'),
                    'book_type'             => $request->input('book_type'),
                    'total_chapter'         => $request->input('total_chapter'),
                    'date_for_submission'   => $request->input('date_for_submission'),
                    'comments'              => $request->input('comments'),
                    'title'                 => $request->input('title'),
                    'first_name'            => $request->input('first_name'),
                    'last_name'             => $request->input('last_name'),
                    'user_category'         => $request->input('user_category'),
                    'country_id'            => $request->input('country'),
                    'address'               => $request->input('address'),
                    'city'                  => $request->input('city'),
                    'state'                 => $request->input('state'),
                    'zip_code'              => $request->input('zipcode'),
                    'email'                 => $request->input('email'),
                    'phone'                 => $request->input('phone'),
                    'fax'                   => $request->input('fax'),
                    'ip'                    => ip2long($request->ip()),
                    'updated_on'            => time(),
                );
            }

            $ebm_rev_id = Journal::Add_Journal_eBook_Proposal($proposal_data);

            DB::commit();
            
            if ($ebm_rev_id > 0) 
            {
                $journal = Journal::GetJournalById($request->input('journal_id'));
                $proposal_data['journal_title']    = $journal->title;

                $country                           = Country::GetCountryList($request->country);
                $proposal_data['country']          = $country->iso;
                $proposal_data['country_name']     = $country->printable_name;

                if ($proposal_data['reg_type'] == 'bookproposal') {
                    $to   = 'imrankhan@xolva.com';
                    //$to = "nuzhat@benthamscience.net";
                    $reg_type_text = "eBook Proposal";
                    $template = "ebook_proposal";
                }
                if ($proposal_data['reg_type'] == 'journalproposal') {
                    $to   = 'imrankhan@xolva.com';
                    //$to = "wajeehaahmed@benthamscience.net";
                    $reg_type_text = "Journal Proposal";
                    $template = "journal_proposal";
                }

                $from = 'admin@eurekaselect.com';
                //$cc   = 'azhar@benthamscience.net';
                $cc      = env('email_admin', 'email_xolva_2', 'email_support_2');
                $bcc  = 0;
                if ($request->file('cv')!=null) 
                {  
                    $attachments = $request->file('cv');
                }
                else 
                {
                    
                    $attachments = "";
                }
                
                $proposal_data['reg_type'] = $reg_type_text;

                $subject = "Eurekaselect: " . $reg_type_text . " Submitted";

                //SendSmtpMail('email_template.become_ebm_reviewer', $proposal_data, $to, $from, $subject, 'Admin', $cc, $bcc, $attachments);
                SendSmtpMail('email_template.'.$template, $proposal_data, $to, $from, $subject, 'Admin', $cc, $bcc, $attachments);

                return back()->with('success', '<strong>Thank you</strong> We appreciate you taking the time to fill out the '.$reg_type_text.' form.
                        Your submission has been emailed to the concerned department.
                       If your request requires a reply, we will be in contact with you shortly. In the meantime, please continue to browse the site. 
                       Use the links above to get to where you want to go!');
                }
            } catch (Exception $e) {

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return back();
            }
    }
    //-------------library-recommendation-----------------//
    public function LibraryRecommendation(Request $request)
    {
        //dd($request);
        if ($request->method() == 'POST') {
			
        $test = strtolower($request->input('library_contact'));
		$array = array("html","doctype","http","https","www.w3");
        $match = "";
        foreach ($array as $char) 
        {
          $match = preg_match("/\b".$char."\b/",$test);
          if($match == 1)
          {
            return Redirect::to('/');
          }

        }
			
				try {
	// try transaction start here for data integrity

					DB::beginTransaction();

					$this->validate($request, [
					'captcha' => 'required|captcha'
					], ['captcha.captcha' => 'Invalid captcha code.']);

					$lib_rec_form = array(
						'journal_id'         => $request->input('journal_id'),
						'rec_reason1'        => $request->input('rec_reason1'),
						'rec_reason2'        => $request->input('rec_reason2'),
						'rec_reason3'        => $request->input('rec_reason3'),
						'additional_reasons' => $request->input('additional_reasons'),
						'library_contact'    => $request->input('library_contact'),
						'library_name'       => $request->input('library_name'),
						'institution'        => $request->input('institution'),
						'library_address'    => $request->input('library_address'),
						'library_country'    => $request->input('library_country'),
						'library_email'      => $request->input('library_email'),
						'library_phone'      => $request->input('library_phone'),
						'library_fax'        => $request->input('library_fax'),
						'salutation'         => $request->input('salutation'),
						'first_name'         => $request->input('first_name'),
						'last_name'          => $request->input('last_name'),
						'usercat'            => $request->input('usercat'),
						'address'            => $request->input('address'),
						'city'               => $request->input('city'),
						'country'            => $request->input('country'),
						'state'              => $request->input('state'),
						'zip'                => $request->input('zip'),
						'email'              => $request->input('email'),
						'phone'              => $request->input('phone'),
						'fax'                => $request->input('fax'),
						'updated'            => date("Y-m-d h:i:s", time()),
						'status'             => 'A',
					);

					$lib_rec_id = Journal::AddLibraryRecommendation($lib_rec_form);
					if (isset(Auth::user()->id)) {
						$login_id = Auth::user()->id;
					} else {
						$login_id = 0;
					}

					$add_log = array(
						'content_id'      => $lib_rec_form['journal_id'],
						'content_type_id' => config('constants.log_content_types.Library_Recommendations'),
						'action'          => config('constants.log_action_types.insert'),
						'log_data'        => json_encode($lib_rec_form),
						'created_dated'   => time(),
						'created_by'      => $login_id,
						'ip'              => ip2long($request->ip()),
					);
					//$log = Log::AddLog($add_log);

					DB::commit();
					if ($lib_rec_id > 0) {
						$journal = Journal::GetJournalById($request->input('journal_id'));

						$lib_rec_form['journal_title'] = $journal->title;

						$to   = $request->input('library_email');
						$from = 'admin@eurekaselect.com';
						$cc   = 'armash@xolva.com,zafar@benthamscience.net,'.$request->input('email');
						$bcc  = 'imrankhan@xolva.com';

						$subject = "Library Recommendation for  Journal: " . $journal->title. " - ".$request->ip();

						SendSmtpMail('email_template.library_recommendation', $lib_rec_form, $to, $from, $subject, 'Admin', $cc, $bcc);

						return back()->with('success', 'Thank you for recommending Bentham Journals to your library. We have sent your recommendation at ' . $request->input("library_email") . '
								In the mean while, if you have any further query, you may write us at <a href="mailto:support@benthamscience.net">support@benthamscience.net</a> .');
					}
				} catch (Exception $e) {

					DB::rollback();
					Session::flash('error', 'Somthing wrong with this page. Please try again!');
					return back();
				}
        } else {
            $param['IsOpenAccess'] = "No";
            $journal_search = Journal::GetJournalTitle($param);
            $country        = Country::GetCountryList();
            $journal_id     = 0;
            return View::make('library_recommendation', with(['journal_search' => $journal_search, 'country' => $country, 'journal_id' => $journal_id]));
        }
    }

    //-------------become-institutional-member-----------------//
    public function BecomeInstitutionalMember(Request $request)
    {
        //dd($request);
        if ($request->method() == 'POST') {


            $this->validate(
                $request,
                [
                    'captcha' => 'required|captcha'
                ],
                ['captcha.captcha' => 'Invalid captcha code.']
            );

            $lib_rec_form = array(
                'salutation'        => $request->input('salutation'),
                'full_name'         => $request->input('full_name'),
                'email'             => $request->input('email'),
                'institution'       => $request->input('institution'),
                'web_institution'   => $request->input('web_institution'),
                'name_librarian'    => $request->input('name_librarian'),
                'email_librarian'   => $request->input('email_librarian'),
                'city'              => $request->input('city'),
                'country'           => $request->input('country'),
                'comment'           => $request->input('comment'),
                'institute_check'   => $request->input('institute_check'),
            );

            $to   = $request->input('email_librarian');
            $from = 'admin@eurekaselect.com';
            $cc   = 'armash@xolva.com,' . $request->input('email');
            $bcc  = 0;

            $subject = "Become An Institutional Member";

            SendSmtpMail('email_template.become_institutional_member', $lib_rec_form, $to, $from, $subject, 'Admin', $cc, $bcc);

            return back()->with('success', 'Thank you for recommending Bentham Journals to your library. We have sent your recommendation at ' . $request->input("library_email") . '
                            In the mean while, if you have any further query, you may write us at <a href="mailto:support@benthamscience.net">support@benthamscience.net</a> .');
        } else {
            return view('pages', with(['page_name' => $request->page_name]));
        }
    }

    //-------------read-publish-collaboration-----------------//
    public function ReadPublishCollaboration(Request $request)
    {
        //dd($request);
        if ($request->method() == 'POST') {

            DB::beginTransaction();

            $this->validate(
                $request,
                [
                    'captcha' => 'required|captcha'
                ],
                ['captcha.captcha' => 'Invalid captcha code.']
            );

            $lib_rec_form = array(
                'salutation'        => $request->input('salutation'),
                'full_name'         => $request->input('full_name'),
                'email'             => $request->input('email'),
                'institution'       => $request->input('institution'),
                'web_institution'   => $request->input('web_institution'),
                'email_librarian'   => $request->input('email_librarian'),
                'city'              => $request->input('city'),
                'country'           => $request->input('country'),
                'phone_number_inst' => $request->input('phone_number_inst'),
                'phone_number_pers' => $request->input('phone_number_pers'),
                'comment'           => $request->input('comment'),
                'librarian_check'   => $request->input('librarian_check'),
            );

            $to   = $request->input('email_librarian');
            $from = 'admin@eurekaselect.com';
            $cc   = 'armash@xolva.com,' . $request->input('email');
            $bcc  = 0;

            $subject = "Request for Read and Publish Collaboration";

            SendSmtpMail('email_template.read_publish', $lib_rec_form, $to, $from, $subject, 'Admin', $cc, $bcc);

            return back()->with('success2', 'Thank you for recommending Bentham Journals to your library. We have sent your recommendation at ' . $request->input("library_email") . '
                            In the mean while, if you have any further query, you may write us at <a href="mailto:support@benthamscience.net">support@benthamscience.net</a> .');
        } else {
            return view('pages', with(['page_name' => $request->page_name]));
        }
    }

    //-------------Trial-Request-----------------//
    public function TrialRequest(Request $request)
    {   //Trial-Request with Society
        if (isset($request->society) && isset($request->id)) {

            if ($request->method() == 'POST') {
                try {
                // try transaction start here for data integrity

                    DB::beginTransaction();

                    $this->validate($request, [
						'zip'                 => 'nullable|numeric',
                        'captcha' => 'required|captcha'
                        ], ['captcha.captcha' => 'Invalid captcha code.']);

                    $society_request = array(
                        'society_id'            => $request->id,
                        'member_name'           => $request->input('member_name'),
                        'member_affiliation'    => $request->input('member_affiliation'),
                        'member_designation'    => $request->input('member_designation'),
                        'member_email'          => $request->input('member_email'),
                        'member_phone'          => $request->input('member_phone'),
                        'member_institute'      => $request->input('member_institute'),
                        'member_country'        => $request->input('member_country'),
                        'institution_name'      => $request->input('institution_name'),
                        'institution_ips'       => $request->input('institution_ips'),
                        'institution_address'   => $request->input('institution_address'),
                        'institution_email'     => $request->input('institution_email'),
                        'institution_phone'     => $request->input('institution_phone'),
                        'contact_name'          => $request->input('contact_name'),
                        'contact_email'         => $request->input('contact_email'),
                        'contact_phone'         => $request->input('contact_phone'),
                        'updated'               => date("Y-m-d h:i:s", time()),
                        'status'                => 'A',
                        'ip'                    => ip2long($request->ip()),
                    );
                    $society_member_id = Journal::AddTrialSocietyRequest($society_request);
                    if (isset(Auth::user()->id)) {
                        $login_id = Auth::user()->id;
                    } else {
                        $login_id = 0;
                    }

                    $add_log = array(
                        'content_id'      => $society_member_id,
                        'content_type_id' => config('constants.log_content_types.Society_Requests'),
                        'action'          => config('constants.log_action_types.insert'),
                        'log_data'        => json_encode($society_request),
                        'created_dated'   => time(),
                        'created_by'      => $login_id,
                        'ip'              => ip2long($request->ip()),
                    );
                    //$log = Log::AddLog($add_log);

                    DB::commit();
                    if ($society_member_id > 0) {
                        $society = Journal::GetSocietyById($request->id);
                        $society_request['society_name'] = $society->society_name;

                        $to   = 'zafar@benthamsceince.net';
                        $from = 'support@benthamscience.net';
                        $cc   = 'azhar@benthamscience.net';
                        $bcc  = 'faizan@benthamscience.net,armash@xolva.com';

                        $subject = "Registration for ".$society->society_name;

                        SendSmtpMail('email_template.society_requests', $society_request, $to, $from, $subject, 'Admin', $cc, $bcc);

                        return back()->with('success', '<b>Thank You</b> for submitting Society Member Registration form to Bentham Science Publisher.     
                    Our support department will contact you shortly. In the mean while, if you have any further query, you may write us at <a href="mailto:faizan@benthamscience.net">faizan@benthamscience.net</a>');
                    }
                } catch (Exception $e) {

                    DB::rollback();
                    Session::flash('error', 'Somthing wrong with this page. Please try again!');
                    return back();
                }
            } else {
                $society = Journal::GetSocietyById($request->id);
                $country        = Country::GetCountryList();

                return View::make('trial_requests', with(['society' => $society, 'country' => $society]));
            }
        }
        else  //Trial-Request without Society
        {  
            if ($request->method() == 'POST') {

                try {
                // try transaction start here for data integrity

                    DB::beginTransaction();

                    $this->validate($request, [
						'zip'                 => 'nullable|numeric',
                        'captcha' => 'required|captcha'
                        ], ['captcha.captcha' => 'Invalid captcha code.']);

                    $trial_request = array(
                        'journal_id'            => $request->input('journal_id'),
                        'institutional_contact' => $request->input('institutional_contact'),
                        'institution_name'      => $request->input('institution_name'),
                        'institution_ips'       => $request->input('institution_ips'),
                        'institution_address'   => $request->input('institution_address'),
                        'institution_country'   => $request->input('institution_country'),
                        'institution_email'     => $request->input('institution_email'),
                        'institution_phone'     => $request->input('institution_phone'),
                        'institution_fax'       => $request->input('institution_fax'),
                        'salutation'            => $request->input('salutation'),
                        'first_name'            => $request->input('first_name'),
                        'last_name'             => $request->input('last_name'),
                        'usercat'               => $request->input('usercat'),
                        'address'               => $request->input('address'),
                        'city'                  => $request->input('city'),
                        'country'               => $request->input('country'),
                        'state'                 => $request->input('state'),
                        'zip'                   => $request->input('zip'),
                        'email'                 => $request->input('email'),
                        'phone'                 => $request->input('phone'),
                        'fax'                   => $request->input('fax'),
                        'updated'               => date("Y-m-d h:i:s", time()),
                        'status'                => 'A',
                        'ip'                    => ip2long($request->ip()),
                    );
                    $trial_request_id = Journal::AddTrialRequest($trial_request);
                    if (isset(Auth::user()->id)) {
                        $login_id = Auth::user()->id;
                    } else {
                        $login_id = 0;
                    }

                    $add_log = array(
                        'content_id'      => $trial_request['journal_id'],
                        'content_type_id' => config('constants.log_content_types.Trial_Requests'),
                        'action'          => config('constants.log_action_types.insert'),
                        'log_data'        => json_encode($trial_request),
                        'created_dated'   => time(),
                        'created_by'      => $login_id,
                        'ip'              => ip2long($request->ip()),
                    );
                    //$log = Log::AddLog($add_log);

                    DB::commit();
                    if ($trial_request_id > 0) {
                        $journal = Journal::GetJournalById($request->input('journal_id'));

                        $trial_request['journal_title'] = $journal->title;

                        $to   = 'zafar@benthamsceince.net';
                        $from = 'support@benthamscience.net';
                        $cc   = 'azhar@benthamscience.net';
                        $bcc  = 'faizan@benthamscience.net,armash@xolva.com';
                        //$bcc='imrankhan@xolva.com';

                        $subject = "Trial Request for Journal: " . $journal->title;

                        SendSmtpMail('email_template.trial_requests', $trial_request, $to, $from, $subject, 'Admin', $cc, $bcc);

                        return back()->with('success', 'Thank you for submitting trial request to Bentham Science Publisher.
                        Our support department will contact you shortly. In the mean while, if you have any further query, you may write us at <a href="mailto:support@benthamscience.net">support@benthamscience.net</a> .');
                    }
                } catch (Exception $e) {

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

                $param['IsOpenAccess'] = "No";
                $journal_search = Journal::GetJournalTitle($param);
                $country        = Country::GetCountryList();
                $journal_id     = 0;

                return View::make('trial_requests', with(['journal_search' => $journal_search, 'country' => $country, 'journal_id' => $journal_id]));
            }
        }
    }


    public function DeleteJournalFile(Request $request, $journal_id, $file_type)
    {
        $user = Auth::user();
        //-----------------------------Insert into log table-----------------------------------
        $journal = Journal::GetJournalById($journal_id);
        $log     = (array) $journal;
        $add_log = array(
            'content_id'      => $journal_id,
            'content_type_id' => config('constants.log_content_types.Journal'),
            '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 == "image_file_name") {
           $filename=config('constants.admin.root_path').'JOURNALS/BEN/'.$journal->subtitle.'/'.$journal->image_file_name;

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

            Journal::where('journal_id', $journal_id)->update($update_journal);
            }
        }

        return redirect()->back();
    }
	
	// public function CheckUserAccessVolumeLevel($volume_obj,$issues,$put_key,$pull_key)
	// {
		// //user Access Volume Level
		// /*---------------User Access code :: added by arshad-------------------------*/

		// if (session()->has('ip_base_access') || session()->has('user_base_access')) 
		// {
			// $ua_session = session()->get('access_user_data');
			
			// $sparam['volume_name']  = $volume_obj[0]->volume_name;
			// $sparam['journal_id']   = $volume_obj[0]->journal_id;
			
			// foreach($ua_session as $ua_k => $ua_v) // check if User Access On Volume
			// {
				// if($ua_v->content_data == 1)
				// {
					// $sparam['session_data'] = $ua_session[$ua_k];
					// $sparam['check_access_on'] = '';
					// $access_type_on = explode(",",$ua_v->access_type_on);
					
					// if (in_array("v", $access_type_on)) 
					// {
						// $sparam['check_access_on'] = 'v';
					// }

					// $download_access_data    = UserAccess::getUserAccessData($sparam);
					// $volume_user_access_data = $download_access_data['access_data'];
					
					// if (!empty($volume_user_access_data)) 
					// {
						// if (session()->has('mysubscribption')) 
						// {
							// foreach ($issues as $key => $issue) 
							// {
								// $put_key[$key] = $key;
							// }
						// }
					// }
				// }
			// }
		// }
		// return $put_key;
		// /*----------------------------------------------------------------------------*/
	// }
	
	public function CheckContentAccessIssueLevel($volume_id,$issues,$page_name='')
	{
		
		$p = array('condition'=>true,'content_type'=>'i','volume_id' => $volume_id);
		$issue_open_access = ContentAccess::GetContentAccessIssueList($p);
		
		$oa_issues = array();
		
        foreach ($issues as $key => $issue) {
			$oa_issue[$key] = $issues[$key];
			$oa_issue[$key]->access_base_text = "";
			$oa_issue[$key]->open_access = false;
			
            if (!empty($issue_open_access)) {
                foreach ($issue_open_access as $issue_access) {
                    if ($issue->issue_id == $issue_access->issue_id) {
						$oa_issue[$key]->open_access = true;
                        if ($issue_access->content_type_access_id == 1) {
                           // $oa_issue[$key]->access_base_text = "promotion: free to download";
                            $oa_issue[$key]->access_base_text = "";
						}
                        if ($issue_access->content_type_access_id == 2) {
							$oa_issue[$key]->access_base_text = "open access plus";
						}
					}
				}
			}
			
            if (!empty($page_name) && $page_name == 'subscribe') {
                if ($oa_issue[$key]->open_access == false) {
					$oa_issues[] = $oa_issue[$key];
				}
            } else {
				$oa_issues[] = $oa_issue[$key];
			}
			unset($oa_issue);
		}
		
		return $oa_issues;
	}
	
	public function CheckUserAccessIssueLevel($volume_id,$issues,$page_name='')
	{
		$oa_issues = array();
		
		$param['volume_id'] = $volume_id;
		$param['user_id'] = session()->get('user_id');
		$param['ip_address'] = \Request::ip();
		$join['volume'] = true;
		$join['issue'] = true;
		$join['article'] = true;
		$uci = UserAccess::GetAllContentUserAccess($param,$join);
		
        foreach ($issues as $key => $issue) {
			$oa_issue[$key] = $issues[$key];
			$oa_issue[$key]->user_access = false;
			
            if ($issue->open_access == false) {
                foreach ($uci as $uci_k => $uci_v) {
					
                    if ($uci_v->access_level == 'volume') {
						$oa_issue[$key]->user_access = true;
					}
				
                    if ($uci_v->issue_id == $issue->issue_id) {
						$oa_issue[$key]->user_access = true;
                        if ($uci_v->access_level == 'issue') {
							$oa_issue[$key]->access_base_text = $uci_v->access_base_text;
						}
					}
				}
			}
			
            if (!empty($page_name) && $page_name == 'subscribe') {
                if ($oa_issue[$key]->user_access == true) {
					$oa_issues[] = $oa_issue[$key];
				}
            } else {
				$oa_issues[] = $oa_issue[$key];
			}
			
			unset($oa_issue);
			
			/*----------------------------------------------------------------------------*/
		}
		
		return $oa_issues;
	}
	
	public function CheckContentAccessVolumeLevelForVolume($journal_id,$volumes,$page_name='')
	{
		
		// Get Volume Level Content Access
		$param['journal_id']   = $journal_id;
		$param['condition']    = true;
		$param['content_type'] = 'v';
		$volume_open_access    = ContentAccess::GetContentAccessVolumeList($param);
		
		$oav_volumes = array();
		
        foreach ($volumes as $key => $volume) {
			$oav_vol[$key] = $volumes[$key];
			$oav_vol[$key]->access_base_text = '';
			$oav_vol[$key]->open_access = false;
			
            if (!empty($volume_open_access)) {
                foreach ($volume_open_access as $volume_access) {
                    if ($volume->volume_id == $volume_access->volume_id) {
                        if ($volume_access->content_type_access_id == 1) {
                           // $oav_vol[$key]->access_base_text = "promotion: free to download";
                            $oav_vol[$key]->access_base_text = "";
						}
                        if ($volume_access->content_type_access_id == 2) {
							$oav_vol[$key]->access_base_text = "open access plus";
						}
					}
				}
			}	
			
            if (!empty($page_name) && $page_name == 'subscribe') {
                if (empty($oav_vol[$key]->access_base_text)) {
					$oav_volumes[] = $oav_vol[$key];
				}
            } else {
				$oav_volumes[] = $oav_vol[$key];
			}
			
			unset($oav_vol);
		}
		
		return $oav_volumes;
	}
	
	public function CheckUserAccessVolumeLevelForVolume($journal_id,$volumes,$page_name='')
	{
		
		$param['journal_id'] = $journal_id;
		$param['user_id'] = session()->get('user_id');
		$param['ip_address'] = \Request::ip();
		$join['volume'] = true;
		$join['issue'] = true;
		$join['article'] = true;
		$ucv = UserAccess::GetAllContentUserAccess($param,$join);
		
		$ucv_volumes = array();
			
        foreach ($volumes as $vol_k => $vol_v) {
			$ucv_vol[$vol_k] = $volumes[$vol_k];
			$ucv_vol[$vol_k]->user_access = false;
			
			// Check if Volume Already has Content Access then Donot Include User Access
            if ($vol_v->open_access == false && $vol_v->access_base_text == '') {
				$ucv_vol[$vol_k]->access_base_text = '';
				$ucv_vol[$vol_k]->DownloadAccess        = false;
				$ucv_vol[$vol_k]->free                  = false;        
				$ucv_vol[$vol_k]->tracksAccessByVolume  = false;
				$ucv_vol[$vol_k]->access_data           = '';
				
                if (!empty($ucv)) {
                    foreach ($ucv as $ucv_k => $ucv_v) {
                        if ($vol_v->volume_id == $ucv_v->volume_id) {
                            if ($ucv_v->access_level == 'volume') {
								$ucv_vol[$vol_k]->access_base_text = $ucv_v->access_base_text;
							}
							
							$ucv_vol[$vol_k]->terms_popup = $ucv_v->terms_popup;
							$ucv_vol[$vol_k]->content_download_type = $ucv_v->content_download_type;
							$ucv_vol[$vol_k]->restricted_user_access_key = $ucv_v->restricted_user_access_key;
							$ucv_vol[$vol_k]->restricted_user_access_type = $ucv_v->restricted_user_access_type;
							$ucv_vol[$vol_k]->tracksAccessByVolume = $ucv_v->tracksAccessByVolume;
							$ucv_vol[$vol_k]->DownloadAccess = true;
							$ucv_vol[$vol_k]->free = false;
							$ucv_vol[$vol_k]->type = $ucv_v->type;
						}
					}
				}
			}
			
            if (!empty($page_name) && $page_name == 'subscribe') {
                if (isset($ucv_vol[$vol_k]->type)) {
					// include only User Access Volumes
					$ucv_volumes[] = $ucv_vol[$vol_k];	
				}
            } else {
				$ucv_volumes[] = $ucv_vol[$vol_k];
			}
			
			unset($ucv_vol);
		}
			
		return $ucv_volumes;	

		/*----------------------------------------------------------------------------*/
	}
	
	public function CheckContentAccessVolumeLevelForIssue($volume_id,$issues,$page_name='')
	{
		$volume_open_access = ContentAccess::CheckVolumeContentAccess(array('content_type_id' => $volume_id));
		
		$oa_issues = array();
		
        foreach ($issues as $key => $issue) {
			$oa_issue[$key] = $issues[$key];
			$oa_issue[$key]->access_base_text = '';
			$oa_issue[$key]->open_access = false;
			
            if (!empty($volume_open_access)) {
				$oa_issue[$key]->open_access = true;
			}
			
            if (!empty($page_name) && $page_name == 'subscribe') {
                if (empty($oa_issue[$key]->access_base_text)) {
					$oa_issues[] = $oa_issue[$key];
				}
            } else {
				$oa_issues[] = $oa_issue[$key];
			}
			
			unset($oa_issue);
		}
		
        if (!empty($volume_open_access)) {
			return array($oa_issues,true);	
        } else {
			return array($oa_issues,false);	
		}
	}
	
	public function CheckUserAccessonArticle($articles)
    {

        $DownloadAccess              = false;
        $article_before_level        = false;
        $download_access_data        = '';
        $terms_popup                 = true;
        $restricted_user_access_key  = '';
        $restricted_user_access_type = '';
        $content_download_type       = '';
        $download_access             = 0;
        $checkIfMarked               ='';   
        $access_base_text 			 = '';
        $art_type_array = array("Editorial", "Preface", "Acknowledgement","Biography","Corrigendum","Erratum","Obituary","Retraction Notice","Withdrawal Notice");

        $subscribe = \Request::get('subscribe');
        $bundle_content =array();
       
        if (!empty($articles[0])) {
            $journal_id = $articles[0]->journal_id;
            $volume_id = $articles[0]->volume_id;
            $volume_name = $articles[0]->volume_name;
            $issue_id  = $articles[0]->issue_id;
			$article_id  = $articles[0]->article_id;
			
			 //----------------Content Access--------------

				//Check free or open access on article
				//---------------------------------------------------
            foreach ($articles as $k => $v) {
					$article_ids[] = $v->article_id;
				}


				$article_lvl_access = ContentAccess::GetContentAccessById(array('article_ids'=>$article_ids,'condition'=>true));
				
            foreach ($articles as $key => $article) {
					
                    $open_access_before=array();
					$oa_articles[$key] = $articles[$key];
					
                    $oa_articles[$key]->view_option = 0;
					$oa_articles[$key]->open_access = false;
					$oa_articles[$key]->download_access = false;
					$oa_articles[$key]->content_download_type = '';
					$oa_articles[$key]->file_type = '';
					$oa_articles[$key]->user_access_id = '';
					$oa_articles[$key]->access_base_text      = '';
					$oa_articles[$key]->terms_popup          = '';
					$oa_articles[$key]->restricted_user_access_key      = '';
					$oa_articles[$key]->restricted_user_access_type      = '';
					
                if ($article->volume_id != "") {
                    $volume_lvl_access = ContentAccess::GetContentAccessById(array('volume_id'=>$article->volume_id,'condition'=>true));

                    if (!empty($volume_lvl_access)) {
                            $open_access_before = $volume_lvl_access[0];
					}
                    }

                if (empty($open_access_before)) {
                    if ($article->issue_id != "" && $article->issue_id != 0) {
                        $issue_lvl_access = ContentAccess::GetContentAccessById(array('issue_id'=>$article->issue_id,'condition'=>true));

                        if (!empty($issue_lvl_access)) {
						$open_access_before = $issue_lvl_access[0];
                            }
					}
                    }        
//print_r($open_access_before);
                if (!empty($open_access_before)) {
						$oa_articles[$key]->open_access      = true;
						$oa_articles[$key]->download_access      = 1;
						$oa_articles[$key]->content_download_type = 'F';
                    if ($open_access_before->content_type_access_id  == 1) {
                            $oa_articles[$key]->terms_popup          = true;
                            $oa_articles[$key]->content_download_type = 'F';
                            if(!in_array($article->article_type_name,$art_type_array)){
                               // $oa_articles[$key]->access_base_text      = "promotion: free to download";
                                $oa_articles[$key]->access_base_text      = "";
                            }else{            
                                //$oa_articles[$key]->access_base_text = 'free to download';
                                $oa_articles[$key]->access_base_text = '';
    						}
                    } elseif ($open_access_before->content_type_access_id  == 2) {
                            $oa_articles[$key]->terms_popup          = false;
                            $oa_articles[$key]->content_download_type = 'FO';
                            $oa_articles[$key]->access_base_text = '';
                            //$oa_articles[$key]->access_base_text = 'open access plus';
						}
                } elseif (!empty($article_lvl_access)) {
                    foreach ($article_lvl_access as $a_k => $a_v) {
                        if ($a_v->content_type_id == $article->article_id) {
								$oa_articles[$key]->open_access      = true;
								$oa_articles[$key]->download_access      = 1;
								$oa_articles[$key]->content_download_type = 'F';
								
                            if ($a_v->content_type_access_id  == 1) {
                                    $oa_articles[$key]->terms_popup          = true;
                                    $oa_articles[$key]->content_download_type = 'F';
									
                                    if(!in_array($article->article_type_name,$art_type_array)){
                                    //$oa_articles[$key]->access_base_text      = "promotion: free to download";
                                    $oa_articles[$key]->access_base_text      = "";
                                    }else{            
                                        //$oa_articles[$key]->access_base_text = 'free to download';
                                        $oa_articles[$key]->access_base_text = '';
                                    }
                            } elseif ($a_v->content_type_access_id  == 2) {
                                    $oa_articles[$key]->terms_popup          = false;
                                    $oa_articles[$key]->content_download_type = 'FO';
									//$oa_articles[$key]->access_base_text = 'open access plus';
                                    $oa_articles[$key]->access_base_text = '';
								}
							}
						}
					}
				}
				
				//-------------------------------------------------------------------
				
				// Check User Access Article Level 

				$a_param['issue_id'] = $issue_id;
				$a_param['user_id'] = session()->get('user_id');
				$a_param['ip_address'] = \Request::ip();
				
				$ua_article_lvl = UserAccess::GetAllContentUserAccess($a_param,array('article'=>true));
				
				$ua_article_list = array();
				
            foreach ($oa_articles as $ao_k => $ao_v) {
					$user_access_before=0;
					$ua_article[$ao_k] = $oa_articles[$ao_k];
					$ua_article[$ao_k]->user_access = false;
					
                if ($ao_v->open_access == false) {
						$ua_article[$ao_k]->download_access = 0;
						$ua_article[$ao_k]->access_base_text = '';
						$ua_article[$ao_k]->DownloadAccess        = false;
						$ua_article[$ao_k]->free                  = false;        
						$ua_article[$ao_k]->tracksAccessByVolume  = false;
						$ua_article[$ao_k]->access_data           = '';
						$ua_article[$ao_k]->restricted_user_access_key = '';
						
                        $v_param['volume_id'] = $ao_v->volume_id;
                        $v_param['user_id'] = session()->get('user_id');
                        $v_param['ip_address'] = \Request::ip();

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

                        $p_issue['issue_id'] = $ao_v->issue_id;
                        $p_issue['user_id'] = session()->get('user_id');
                        $p_issue['ip_address'] = \Request::ip();
                        
                    if (empty($user_access_before)) {

                            $ua_issue_lvl = UserAccess::GetAllContentUserAccess($p_issue,array('issue'=>true));
                            
                        if (!empty($ua_issue_lvl[0])) {
							$user_access_before = $ua_issue_lvl[0];
                            }
						}
						
                    if (!empty($user_access_before)) {
                            $param['user_access_id']=$user_access_before->user_access_id;
                            $user_access_info = UserAccess::GetUserAccess($param);  

                            $ua_article[$ao_k]->view_option = $user_access_info->view_option;
							$ua_article[$ao_k]->user_access = true;
							$ua_article[$ao_k]->user_access_id = $user_access_before->user_access_id;
							$ua_article[$ao_k]->terms_popup = $user_access_before->terms_popup;
							$ua_article[$ao_k]->access_base_text = $user_access_before->access_base_text;
							$ua_article[$ao_k]->content_download_type = $user_access_before->content_download_type;
							$ua_article[$ao_k]->restricted_user_access_key = $user_access_before->restricted_user_access_key;
							$ua_article[$ao_k]->restricted_user_access_type = $user_access_before->restricted_user_access_type;
							$ua_article[$ao_k]->tracksAccessByVolume = $user_access_before->tracksAccessByVolume;
							$ua_article[$ao_k]->DownloadAccess = true;
							$ua_article[$ao_k]->download_access = 1;
							$ua_article[$ao_k]->free = false;
							$ua_article[$ao_k]->type = $user_access_before->type;
						}
						
						if(!empty($ua_article_lvl)) // check User Access Article level
						{
                        foreach ($ua_article_lvl as $ua_k => $ua_v) {
                            if ($ua_v->article_id == $ao_v->article_id) {
									
                                    $param['user_access_id']=$ua_v->user_access_id;
                                    $user_access_info = UserAccess::GetUserAccess($param);   

                                    $ua_article[$ao_k]->view_option = $user_access_info->view_option;

									$ua_article[$ao_k]->user_access = true;
									$ua_article[$ao_k]->user_access_id = $ua_v->user_access_id;
									$ua_article[$ao_k]->terms_popup = $ua_v->terms_popup;
									$ua_article[$ao_k]->access_base_text = $ua_v->access_base_text;
									$ua_article[$ao_k]->content_download_type = $ua_v->content_download_type;
									$ua_article[$ao_k]->restricted_user_access_key = $ua_v->restricted_user_access_key;
									$ua_article[$ao_k]->restricted_user_access_type = $ua_v->restricted_user_access_type;
									$ua_article[$ao_k]->tracksAccessByVolume = $ua_v->tracksAccessByVolume;
									$ua_article[$ao_k]->DownloadAccess = true;
									$ua_article[$ao_k]->download_access = 1;
									$ua_article[$ao_k]->free = false;
									$ua_article[$ao_k]->type = $ua_v->type;
                            }
                        }
                    }
                }

                if (!empty($subscribe) && $subscribe == 'subscribe') {
                    if (isset($ua_article[$ao_k]->type)) {
							// include only User Access Articles
							$ua_article_list[] = $ua_article[$ao_k];
						}
                } else {
						$ua_article_list[] = $ua_article[$ao_k];
					}
					
					unset($ua_article);
				}
				
		
            foreach ($articles as $alk => $alv) {
					unset($articles[$alk]);
					
                if (!empty($ua_article_list[$alk])) {
						$articles[$alk] = $ua_article_list[$alk];
					}
                    if($articles[$alk]->is_epub==4){
                        $articles[$alk]->access_base_text = '';                                  
                    }
					
					$articles[$alk]->sparam = Crypt::encrypt($alv->article_id . '||' . 'pdf' . '||' . $alv->content_download_type . '||' . $alv->restricted_user_access_key . '||' . $alv->user_access_id);
				}


            /*----------------------------------------------------------------------------*/

            foreach ($articles as $key => $article) {

            $aparam=encrypt(array('readpdf',$article->article_id,config('constants.admin.token'),$article->content_download_type));

           $articles[$key]->route = route('article', ['article_id' => $article->article_id,'param' => $aparam]);
            //create encrypt param with article nid
            $articles[$key]->param            = encrypt($article->nid);
            $articles[$key]->csrf_token       = csrf_token();

                if (session()->has('user_id')) {
                    $checkIfMarked = MarkList::checkIfMarked(1, $article->nid, session()->get('user_id'));
                    if (!empty($checkIfMarked)) {
                        $checkIfMarked = true;
                    }
                    //check if user has perpetual access (if artcile purchased by login user)

                    if($articles[$key]->download_access==0){     
                        if (ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $article->article_id, 'article')[0]->total > 0) {
                            //$DownloadAccess        = true;
                            $articles[$key]->view_option           = 0;
                            $articles[$key]->user_access           = true;
                            $articles[$key]->access_base_text      = "Subscribe";                        
                            $articles[$key]->content_download_type = 'P';
                            $articles[$key]->terms_popup           = true;
                            $articles[$key]->DownloadAccess        = true;
                            $articles[$key]->download_access       = 1;
                        }
                    }

                    if ($articles[$key]->download_access==0) {
                        $articles[$key]->user_access_id = 0;
                    }
                }
                $articles[$key]->checkIfMarked = $checkIfMarked;
            }

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

                if (!empty($bundle_content) && $bundle_content->article > 0) {
                    foreach ($articles as $k => $v) {
                            $articles[$k]->view_option           = 0;
                            $articles[$k]->bundle_offer_order_id  = $bundle_content->bundle_offer_order_id;
                            $articles[$k]->article  = $bundle_content->article;
                            $articles[$k]->content_download_type  = $bundle_content->content_download_type;
                            $var = isset($var) ? $var : "default";
                        if ($bundle_content->article == 1) {
                              $v->restricted_user_access_key = !empty($v->restricted_user_access_key) ? $v->restricted_user_access_key : "0";
                              $v->user_access_id = !empty($v->user_access_id) ? $v->user_access_id : "0";
                              $articles[$k]->sparam = Crypt::encrypt($v->article_id . '||' . 'pdf' . '||' . $bundle_content->content_download_type . '||' . $v->restricted_user_access_key . '||' . $v->user_access_id);
                            }
                        }
                    }
                }
        
				
            /*----------------------------------------------------------------------------*/
		     // dd($articles);
			return $articles;
		}
    }
	
    public function SubscriptionRedirect($journal_code)
    {
        $journal=Journal::GetJournalByCode($journal_code);
        return redirect()->route('subscription_request', ['journal_id' => $journal->journal_id]);
    }

    public function SubscriptionRequest(Request $request, $journal_id)
    {
        $ajax = $request->get('ajax');
        $subs_category = $request->get('subs_category');
        
        if ($ajax == true) {
            if (isset($request->promo_code)) {
                return $this->validate_promo_code($request);
            } else {
            $category = Journal::GetSubsCategoryByID($subs_category);
            return response()->json($category, 200);
        }
        }

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

            if ($validator->fails()) {
                return $this->SubscriptionRequestForm($request, $journal_id, $validator);
            } else {
                return $this->SubscriptionRequestPreview($request, $journal_id);
            }
        } elseif (isset($request->subscription_purchase_form) && $request->subscription_purchase_form == "Proceed to Checkout") {
            return $this->SubscriptionRequestSubmit($request, $journal_id);
        } else {
            return $this->SubscriptionRequestForm($request, $journal_id);
        }
    }

    public function validate_promo_code(Request $request)
    {  
        $promo_code      = $request->get('promo_code');
        $journal_id      = $request->journal_id;

        if ($journal_id > 0 && !empty($promo_code)) {
            $promo_details = Campaign::GetPromoCodeDetails($promo_code);

            if ($promo_details != null) {
                // -- Check If Promo Code is Active
                if ($promo_details->status == 'Active') {
                    $date_now = date('Y-m-d H:i:s');
                    // -- Check If Promo Code Date wise
                    if ($date_now >= $promo_details->start_date && $date_now <= $promo_details->end_date) {
                        // --- validate promo code journal / Country / ip wise
                        $result = Campaign::ValidateJournalPromoCode($journal_id, $promo_details,$request->ip());

                        if ($result == true) {

                            session(['promo_discount' => $promo_details->discount]);
                            $msg = array(true, 'Promo Code Validate Successfully');
                        } else {
                            Session::forget('promo_discount');
                            $msg = array(false, 'Promo Code Validate Error');
                        }
                    } else {
                        Session::forget('promo_discount');
                        $msg = array(false, 'Promo Code Date Expired');
                    }
                } else {
                    Session::forget('promo_discount');
                    $msg = array(false, 'Promo Code is not Active');
                }
            } else {
                Session::forget('promo_discount');
                $msg = array(false, 'promo code is incorrect');
            }
        } else {
            Session::forget('promo_discount');
            $msg = array(false, 'please enter promo code');
        }

        return response()->json($msg, 200);
    }
    public function SubscriptionRequestForm($request, $journal_id, $validator = null)
    {
            $journal_search      = Journal::GetJournalTitle();
            $subs_category       = Journal::GetSubsCategory($journal_id);
            $latest_issue        = Issue::getcurrentissue($journal_id);
            $country             = Country::GetCountryList();
            $related_journal     = Subject::RelatedJournalBySubjectId($journal_id);
            $related_ebook       = Subject::RelatedJournaleBookBySubjectId($journal_id);
            $JournalSubjects     = Subject::GetSubjectByJournalID($journal_id);
            $JournalDiseases     = Disease::DiseaseJournal($journal_id, 'journal_id');
            $journal             = Journal::GetJournalById($journal_id);
            $param['journal_id'] = $journal_id;
            $page_name = 'subscribe_journal_form';
            $user    = Auth::user();

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

            $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='https://'.$_SERVER['HTTP_HOST'].'/journal/'.$journal->journal_id;
            }

            if (isset(Auth::user()->id)) {
                $session_detail         = $request->session()->get('session_detail');
                $detail['first_name']   = isset($user->first_name) ? $user->first_name : '';
                $detail['last_name']    = isset($user->last_name) ? $user->last_name : '';
                $detail['user_category']      = isset($user->user_category) ? $user->user_category : '';
                $detail['address']      = isset($user->address) ? $user->address : '';
                $detail['city']         = isset($user->city) ? $user->city : '';
                $detail['country']      = isset($user->country) ? $user->country : '';
                $detail['state']        = isset($user->state) ? $user->state : '';
                $detail['zip']          = isset($user->zip) ? $user->postal : '';
                $detail['email']        = isset($user->email) ? $user->email : '';
                $detail['phone']        = isset($user->phone) ? $user->phone : '';
                $detail['fax']          = isset($user->fax) ? $user->fax : '';
            } elseif ($request->session()->has('session_detail')) {

                $session_detail         = $request->session()->get('session_detail');
                $detail['first_name']   = isset($session_detail['first_name']) ? $session_detail['first_name'] : '';
                $detail['last_name']    = isset($session_detail['last_name']) ? $session_detail['last_name'] : '';
                $detail['user_category']      = isset($session_detail['user_category']) ? $session_detail['user_category'] : '';
                $detail['address']      = isset($session_detail['address']) ? $session_detail['address'] : '';
                $detail['city']         = isset($session_detail['city']) ? $session_detail['city'] : '';
                $detail['country']      = isset($session_detail['country']) ? $session_detail['country'] : '';
                $detail['state']        = isset($session_detail['state']) ? $session_detail['state'] : '';
                $detail['zip']          = isset($session_detail['zip']) ? $session_detail['zip'] : '';
                $detail['email']        = isset($session_detail['email']) ? $session_detail['email'] : '';
                $detail['phone']        = isset($session_detail['phone']) ? $session_detail['phone'] : '';
                $detail['fax']          = isset($session_detail['fax']) ? $session_detail['fax'] : '';
            } else {
                $detail['first_name']          = '';
                $detail['last_name']                 = '';
                $detail['user_category']             = '';
                $detail['address']              = '';
                $detail['city'] = '';
                $detail['country']               = '';
                $detail['state']                = '';
                $detail['zip']                = '';
                $detail['email']                = '';
                $detail['phone']                = '';
                $detail['fax']                = '';
            }

            if (!empty($validator) && $validator->fails()) {
            return view('journal_menu', with([
                'journal' => $journal,
                    'journal'           => $journal,
                    'latest_issue'      => $latest_issue,
                    'node_meta'         => $node_meta,
                    'param'             => $param,
                    'page_name'         => $page_name,
                    'related_journal'   => $related_journal,
                    'related_ebook'     => $related_ebook,
                    'journal_search'    => $journal_search,
                    'country'           => $country,
                    'journal_id'        => $journal_id,
                    'JournalSubjects'   => $JournalSubjects,
                    'JournalDiseases'   => $JournalDiseases,
                    'detail'            => $detail,
                    'count_epub_article' => $count_epub_article, 
                    'count_epub_abstract' => $count_epub_abstract,
                'subs_category'     => $subs_category
            ]))->withErrors($validator);
            } else {
            return view('journal_menu', with([
                'journal' => $journal,
                    'journal'           => $journal,
                    'latest_issue'      => $latest_issue,
                    'node_meta'         => $node_meta,
                    'param'             => $param,
                    'page_name'         => $page_name,
                    'related_journal'   => $related_journal,
                    'related_ebook'     => $related_ebook,
                    'journal_search'    => $journal_search,
                    'country'           => $country,
                    'journal_id'        => $journal_id,
                    'JournalSubjects'   => $JournalSubjects,
                    'JournalDiseases'   => $JournalDiseases,
                    'detail'            => $detail,
                    'count_epub_article' => $count_epub_article, 
                    'count_epub_abstract' => $count_epub_abstract,
                'subs_category'     => $subs_category
            ]));
            }
    }

    public function SubscriptionRequestPreview(Request $request, $journal_id)
    { 
        $detail = array();

        $promo_code = $this->validate_promo_code($request);
        if ($promo_code->original[0]) {
            $promodiscount = session()->get('promo_discount');
        } else {
            $promodiscount = false;
            Session::forget('promo_discount');
        }

            $detail['promo_code']   = isset($request->promo_code) ? $request->promo_code : '';
            $detail['subs_category']    = isset($request->subs_category) ? $request->subs_category : '';
            $detail['subs_type']        = isset($request->subs_type) ? $request->subs_type : '';
            $detail['price']            = isset($request->price) ? $request->price : '';
            $detail['volume']           = isset($request->volume) ? $request->volume : '';
            $detail['frequency']        = isset($request->frequency) ? $request->frequency : '';
            $detail['year']             = isset($request->year) ? $request->year : '';
            $detail['salutation']       = isset($request->salutation) ? $request->salutation : '';
            $detail['first_name']       = isset($request->first_name) ? $request->first_name : '';
            $detail['last_name']        = isset($request->last_name) ? $request->last_name : '';
            $detail['user_category']    = isset($request->user_category) ? $request->user_category : '';
            $detail['address']          = isset($request->address) ? $request->address : '';
            $detail['city']             = isset($request->city) ? $request->city : '';
            $detail['state']            = isset($request->state) ? $request->state : '';
            $detail['zip']              = isset($request->zip) ? $request->zip : '';
            $detail['email']            = isset($request->email) ? $request->email : '';
            $detail['phone']            = isset($request->phone) ? $request->phone : '';
            $detail['fax']              = isset($request->fax) ? $request->fax : '';
            $country                    = Country::GetCountryList("", $request->country);
            $detail['country']          = $country->iso;
            $detail['country_name']     = $country->printable_name;
            $detail['subs_category_name']   = $detail['subs_type']." - Volume ".$detail['volume'].", ".$detail['frequency']." Issue (".$detail['year'].")";

            $journal_search      = Journal::GetJournalTitle();
            $latest_issue        = Issue::getcurrentissue($journal_id);
            $country             = Country::GetCountryList();
            $related_journal     = Subject::RelatedJournalBySubjectId($journal_id);
            $related_ebook       = Subject::RelatedJournaleBookBySubjectId($journal_id);
            $JournalSubjects     = Subject::GetSubjectByJournalID($journal_id);
            $JournalDiseases     = Disease::DiseaseJournal($journal_id, 'journal_id');
            $journal             = Journal::GetJournalById($journal_id);
            $param['journal_id'] = $journal_id;
            $page_name = 'subscribe_journal_form_preview';

            $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='https://'.$_SERVER['HTTP_HOST'].'/journal/'.$journal->journal_id;
            }

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


        return view('journal_menu', with([
            'journal' => $journal,
                    'journal'           => $journal,
                    'latest_issue'      => $latest_issue,
                    'node_meta'         => $node_meta,
                    'param'             => $param,
                    'page_name'         => $page_name,
                    'related_journal'   => $related_journal,
                    'related_ebook'     => $related_ebook,
                    'journal_search'    => $journal_search,
                    'country'           => $country,
                    'journal_id'        => $journal_id,
                    'JournalSubjects'   => $JournalSubjects,
                    'JournalDiseases'   => $JournalDiseases,
                    'detail'            => $detail,
                    'count_epub_article' => $count_epub_article, 
                    'count_epub_abstract' => $count_epub_abstract,
            'promodiscount'     => $promodiscount
        ]));
    }

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

            //-------------------Insert into Table---------------
            $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;

            $subscribe = Journal::GetSubsCategoryByID($request->subs_category);

            if ($promodiscount) {
                $item_price     = round(($promodiscount / 100) * ($subscribe->price));
                $price = round($subscribe->price - $item_price);
            } else {
                $price = $subscribe->price;
            }

            $add_details['subs_id']          = $request->subs_category;
            $add_details['title']            = $request->salutation;
            $add_details['first_name']       = $request->first_name;
            $add_details['last_name']        = $request->last_name;
            $add_details['user_category']    = $request->user_category;
            $add_details['address']          = $request->address;
            $add_details['city']             = $request->city;
            $add_details['country']          = $request->country;
            $add_details['state']            = $request->state;
            $add_details['zip']              = $request->zip;
            $add_details['email']            = $request->email;
            $add_details['phone']            = $request->phone;
            $add_details['fax']              = $request->fax;
            $add_details['promo_code']       = $request->promo_code;
            $add_details['origional_price']  = $subscribe->price;
            $add_details['discount']         = ($promodiscount > 0 ? $promodiscount : '');
            $add_details['amount']           = $price;
            $add_details['created_on']       = time();
            $add_details['last_modified']    = time();
            $add_details['ip']               = ip2long($request->ip());
            $add_details['status']    = 'I';

            $subscrition_order_id = Journal::AddSubscriptionOrder($add_details);

/*            $add_log = array(
                'content_id'      => $subscrition_order_id,
                'content_type_id' => config('constants.log_content_types.Subscription_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 Temparay)---------------------------------------
        $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = "SJ_" . $subscrition_order_id;
        $migs['amount']             = $price;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/subscription-request-migs-response/". $migs['order_id'];   
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/subscription-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-------------------------------
    }
//-----------------------------------MIGS Payment Response---------------------------------------
    public function SubscriptionRequestMigsResponse(Request $request)
    { 
        $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;

        $subscrition_order_id = substr($request->subscrition_order_id, 3, strlen($request->subscrition_order_id));

        $param['subscrition_order_id'] = $subscrition_order_id;
        $subscrition           = Journal::GetSubscritionOrderDetail($param);
        $subscrition           = $subscrition[0];

        $detail['order_id']         = $subscrition_order_id;  
        $detail['journal']          = $subscrition->journal_title;
        $detail['subs_category']    = $subscrition->subs_id;
        $detail['subs_type']        = $subscrition->type;
        $detail['price']            = $subscrition->price;
        $detail['discount']         = ($promodiscount > 0 ? $promodiscount : '');
        $detail['amount']           = $subscrition->amount;
        $detail['volume']           = $subscrition->volume_name;
        $detail['frequency']        = $subscrition->frequency;
        $detail['year']             = $subscrition->year;
        $detail['salutation']       = $subscrition->title;
        $detail['first_name']       = $subscrition->first_name;
        $detail['last_name']        = $subscrition->last_name;
        $detail['user_category']    = $subscrition->user_category;
        $detail['address']          = $subscrition->address;
        $detail['city']             = $subscrition->city;
        $detail['state']            = $subscrition->state;
        $detail['zip']              = $subscrition->zip;
        $detail['email']            = $subscrition->email;
        $detail['phone']            = $subscrition->phone;
        $detail['fax']              = $subscrition->fax;
        $detail['promo_code']       = $subscrition->promo_code;

        $detail['country']          = $subscrition->country;
        $country                = Country::GetCountryList("", $detail['country']);
        $detail['country_name']     = $country->printable_name;
        $detail['subs_category_name']   = $detail['subs_type']." - Volume ".$detail['volume'].", ".$detail['frequency']." Issue (".$detail['year'].")";
        $journal_id                 = $subscrition->journal_id;

        $journal_search      = Journal::GetJournalTitle();
        $latest_issue        = Issue::getcurrentissue($journal_id);
        $country             = Country::GetCountryList();
        $related_journal     = Subject::RelatedJournalBySubjectId($journal_id);
        $related_ebook       = Subject::RelatedJournaleBookBySubjectId($journal_id);
        $JournalSubjects     = Subject::GetSubjectByJournalID($journal_id);
        $JournalDiseases     = Disease::DiseaseJournal($journal_id, 'journal_id');
        $journal             = Journal::GetJournalById($journal_id);
        $param['journal_id'] = $journal_id;
        $page_name = 'subscribe_journal_form_preview';
        $count_epub_article = Article::GetTrackList($journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($journal_id, 4, 0)->count();

        $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='https://'.$_SERVER['HTTP_HOST'].'/journal/'.$journal->journal_id;
        }

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

        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($request->subscrition_order_id);

        $payment_gateway['order_id'] = $request->subscrition_order_id;
        $payment_gateway['response'] = json_encode($apiResponse);
        $payment_gateway['domain'] = env('APP_NAME');
        Log::AddPaymentGatewayResponse($payment_gateway);        

        if ($apiResponse->result == "SUCCESS" && $apiResponse->transaction[0]->result != "FAILURE") {
              $txnResponseCode = html_entity_decode($apiResponse->transaction[0]->response->acquirerCode, ENT_QUOTES, 'UTF-8');

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

                $detail['status'] = "Sucessfully Completed";

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_support_2');
                $bcc      = env('email_xolva') . ',' . env('email_xolva_2');
                $subject = "Personal Subscription Request # " . $subscrition_order_id . "";

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

                $migs_transaction                  = 'Success';
                $update_subscrition['response_code']    = $txnResponseCode;
                $update_subscrition['response_message'] = $plain_message;
                $update_subscrition['transaction_no']   = $transactionNo;
                $update_subscrition['status']     = $status;
                $update_subscrition['last_modified']    = time();

                Journal::UpdateSubscritionOrder($subscrition_order_id, $update_subscrition);
                Session::forget('promo_discount');
        

                return view('journal_menu', with([
                    'journal' => $journal,
                'journal'           => $journal,
                'latest_issue'      => $latest_issue,
                'node_meta'         => $node_meta,
                'param'             => $param,
                'page_name'         => $page_name,
                'related_journal'   => $related_journal,
                'related_ebook'     => $related_ebook,
                'journal_search'    => $journal_search,
                'country'           => $country,
                'journal_id'        => $journal_id,
                'JournalSubjects'   => $JournalSubjects,
                'JournalDiseases'   => $JournalDiseases,
                'detail'            => $detail,
                'promodiscount'    => $promodiscount,
                'count_epub_article' => $count_epub_article, 
                'count_epub_abstract' => $count_epub_abstract,
                    'migs_transaction' => $migs_transaction
                ]));
            }
        } else {
                $detail['status'] = "Transaction Failed with MiGS";

                // MiGs Payment Fail

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_support_2');
                $bcc      = env('email_xolva') . ',' . env('email_xolva_2');
                $subject = "Personal Subscription Request # " . $subscrition_order_id . "";

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

            $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;

            $migs_transaction = 'Cancel';
            $update_subscrition['status'] = 'N';
            Journal::UpdateSubscritionOrder($subscrition_order_id, $update_subscrition);

            $paypal['paypalEnv']      = env('paypalEnv');
            $paypal['paypalURL']      = env('paypalURL');
            $paypal['business']       = env('email_business', '');
            $paypal['invoice']        = 'SJ:' . $subscrition_order_id;
            $paypal['item_name']      = 'Order# SUBSCRIPTION JOURNAL' . $subscrition_order_id;
            $paypal['amount']         = $subscrition->amount;
            $paypal['currency_code']  = 'USD';
            $paypal['paypalClientID'] = env('paypalClientID');
            $paypal['return']         = url("/subscription-request-paypal-response/");

            return view('journal_menu', with([
                'journal' => $journal,
                'journal'           => $journal,
                'latest_issue'      => $latest_issue,
                'node_meta'         => $node_meta,
                'param'             => $param,
                'page_name'         => $page_name,
                'related_journal'   => $related_journal,
                'related_ebook'     => $related_ebook,
                'journal_search'    => $journal_search,
                'country'           => $country,
                'journal_id'        => $journal_id,
                'JournalSubjects'   => $JournalSubjects,
                'JournalDiseases'   => $JournalDiseases,
                'detail'            => $detail,
                'promodiscount'    => $promodiscount,    
                'paypal'            => $paypal,
                'count_epub_article' => $count_epub_article, 
                'count_epub_abstract' => $count_epub_abstract,
                'migs_transaction' => $migs_transaction
            ]));
        }
    }

    public function SubscriptionRequestPaypalResponse(Request $request)
    {
        try {
// try transaction start here for data integrity
            $promodiscount = session()->has('promo_discount') ? session()->get('promo_discount') : false;

            $paypal = array();

            DB::beginTransaction();

            $param['subscrition_order_id'] = $subscrition_order_id = substr($request->invoice, 3, strlen($request->invoice));
            $subscrition           = Journal::GetSubscritionOrderDetail($param);
            $subscrition           = $subscrition[0];

            $detail['order_id']         = $subscrition_order_id;  
            $detail['journal']          = $subscrition->journal_title;
            $detail['subs_category']    = $subscrition->subs_id;
            $detail['subs_type']        = $subscrition->type;
            $detail['price']            = $subscrition->price;
            $detail['discount']         = ($promodiscount > 0 ? $promodiscount : '');
            $detail['amount']           = $subscrition->amount;
            $detail['volume']           = $subscrition->volume_name;
            $detail['frequency']        = $subscrition->frequency;
            $detail['year']             = $subscrition->year;
            $detail['salutation']       = $subscrition->title;
            $detail['first_name']       = $subscrition->first_name;
            $detail['last_name']        = $subscrition->last_name;
            $detail['user_category']    = $subscrition->user_category;
            $detail['address']          = $subscrition->address;
            $detail['city']             = $subscrition->city;
            $detail['state']            = $subscrition->state;
            $detail['zip']              = $subscrition->zip;
            $detail['email']            = $subscrition->email;
            $detail['phone']            = $subscrition->phone;
            $detail['fax']              = $subscrition->fax;
            $detail['promo_code']       = $subscrition->promo_code;
            $detail['country']          = $subscrition->country;
            $country                = Country::GetCountryList("", $detail['country']);
            $detail['country_name']     = $country->printable_name;
            $detail['subs_category_name']   = $detail['subs_type']." - Volume ".$detail['volume'].", ".$detail['frequency']." Issue (".$detail['year'].")";
            $journal_id                 = $subscrition->journal_id;

            if ($subscrition->status == 'C') {
                return Redirect::to('journal/' . $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);

            $payment_gateway['order_id'] = $request->invoice;
            $payment_gateway['response'] = json_encode($paymentCheck);
            $payment_gateway['domain'] = env('APP_NAME');
            Log::AddPaymentGatewayResponse($payment_gateway);        

            // If the payment is valid and approved
            if ($paymentCheck && $paymentCheck->state == 'approved') {

                $detail['status'] = "Sucessfully Completed";

                // Paypal Payment Done Successfully

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_support_2');
                $bcc      = env('email_xolva') . ',' . env('email_xolva_2');
                $subject = "Personal Subscription Request # " . $subscrition_order_id . "";

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

                $paypal_transaction             = 'Success';
                $update_subscrition['transaction_no'] = $paymentCheck->transactions[0]->related_resources[0]->sale->id;
                $update_subscrition['response_message']  =  $paymentCheck->state;
                $update_subscrition['response_code'] = 0;
                $update_subscrition['status']  = "C";
            } else {

                $detail['status'] = "Transaction Failed with Paypal";

                // Paypal Payment Fail

                $to      = $detail['email'];
                $from    = env('email_admin', '');
                $cc      = env('email_support_2');
                $bcc      = env('email_xolva') . ',' . env('email_xolva_2');
                $subject = "Personal Subscription Request # " . $subscrition_order_id . "";

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

                $update_subscrition['response_code'] = "C";
                $update_subscrition['status']  = "N";

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

            Journal::UpdateSubscritionOrder($subscrition_order_id, $update_subscrition);

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

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

            $journal_search      = Journal::GetJournalTitle();
            $subs_category       = Journal::GetSubsCategory($journal_id);
            $latest_issue        = Issue::getcurrentissue($journal_id);
            $country             = Country::GetCountryList();
            $related_journal     = Subject::RelatedJournalBySubjectId($journal_id);
            $related_ebook       = Subject::RelatedJournaleBookBySubjectId($journal_id);
            $JournalSubjects     = Subject::GetSubjectByJournalID($journal_id);
            $JournalDiseases     = Disease::DiseaseJournal($journal_id, 'journal_id');
            $journal             = Journal::GetJournalById($journal_id);
            $param['journal_id'] = $journal_id;
            $page_name = 'subscribe_journal_form_preview';
            $user    = Auth::user();

            $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='https://'.$_SERVER['HTTP_HOST'].'/journal/'.$journal->journal_id;
            }
                Session::forget('promo_discount');

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

        return view('journal_menu', with([
            'journal' => $journal,
                    'journal'           => $journal,
                    'latest_issue'      => $latest_issue,
                    'node_meta'         => $node_meta,
                    'param'             => $param,
                    'page_name'         => $page_name,
                    'related_journal'   => $related_journal,
                    'related_ebook'     => $related_ebook,
                    'journal_search'    => $journal_search,
                    'country'           => $country,
                    'journal_id'        => $journal_id,
                    'JournalSubjects'   => $JournalSubjects,
                    'JournalDiseases'   => $JournalDiseases,
                    'detail'            => $detail,
                    'promodiscount'    => $promodiscount,    
                    'paypal'            => $paypal, 
                    'paypal_transaction' => $paypal_transaction,
                    'count_epub_article' => $count_epub_article, 
                    'count_epub_abstract' => $count_epub_abstract,
            'subs_category'     => $subs_category
        ]));
    } 


    public function FreeOnlineSamples(Request $request)
    {

        $journal         = Journal::getContinuedJournalList();          

        return view('freeonlinesample', with(['journallist' => $journal]));
    }

    public function journalSubscriptionsRate(Request $request)
    {

        $journal         = Journal::GetJournalSubscriptionRate($request->rateyear);

        return view('journal_subscriptions_rates', with(['journallist' => $journal,'rateyear'=>$request->rateyear]));

    }    

    /*
    *   Author      : Enayat
    *   Date        : 07-03-2022
    *   Description : This function will manage multi lang journal request (add, edit,delete,update) 
    */ 
    public function manageMultilang(Request $request)
    {
        if($request->form_action == 'submit'){
            $this->addMultiLang($request);
        }elseif($request->form_action == 'update'){
            $this->updateMultiLanguage($request);
        }else if($request->form_action == 'delete'){
            $result = DB::table('multilanguage_journal')->where('id',$request->multi_language_id)->delete();
            echo json_encode(['msd'=> 'Language Title deleted.']);


        }


    }
    public function addMultiLang($request)
    {
        $data = array(
            'language_id' => $request->language_id,
            'journal_id' => $request->journal_id,
            'title' => $request->multi_lang_title,
            'created_by'=> Auth::user()->id,
            'updated_by'=> Auth::user()->id,
            'created'=>time(),
            'updated'=>time()
        );
        $result = DB::table('multilanguage_journal')->insert($data);
       echo json_encode(['msd'=> 'Language Title Added.']);
    }
    public function updateMultiLanguage($request)
    {
        $data = array(
            'language_id' => $request->language_id,
            'title' => $request->multi_lang_title,
            'updated_by'=> Auth::user()->id,
            'updated'=>time()
        );
        $result = DB::table('multilanguage_journal')->where('id',$request->multi_language_id)->update($data);
        echo json_encode(['msd'=> 'Language Title updated.']);
    }

    public function FreeOnlineSubscriptionOffer(Request $request)
    {   
        if ($request->method() == 'POST') 
        {
                $j_array = array();
                $data = array();

                $this->validate($request, [
                    'journal'               => "required|array|min:1|max:3",
                    'journal_id'            => "required",
                    'salutation'            => "required",
                    'first_name'            => "required",
                    'last_name'             => "required",
                    'user_category'         => "required",
                    'address'               => "required",
                    'city'                  => "required",
                    'state'                 => "required",
                    'country'               => "required",
                    'email'                 => "required|email",
                    'captcha'               => 'required|captcha'
                    ], ['captcha.captcha'   => 'Invalid captcha code.']
                );
                
            
                    $data = array(
                    'title_thematic_issue'  => $request->input('title_thematic_issue'),
                    'name_guest_editor'     => $request->input('name_guest_editor'),
                    'salutation'            => $request->input('salutation'),
                    'first_name'            => $request->input('first_name'),
                    'last_name'             => $request->input('last_name'),
                    'user_category'         => $request->input('user_category'),
                    'address'               => $request->input('address'),
                    'city'                  => $request->input('city'),
                    'state'                 => $request->input('state'),
                    'country'               => $request->input('country'),
                    'zip'                   => $request->input('zip'),
                    'email'                 => $request->input('email'),
                    'phone'                 => $request->input('phone'),
                    'fax'                   => $request->input('fax'),
                    'journal_title'         => $request->input('journal_id'),
                    'updated'               => time(),
                    'status'                => 'A',
                    'ip'                    => ip2long($request->ip()),
                    );
                    
                $j_array = $request->input('journal');

                if (!empty($j_array)) 
                {   $a=1;
                    for ($c = 0; $c < count($j_array); $c++) 
                    {
                        $data['journal_choice'.$a] = $j_array[$c];

                        $a++;
                    }
                }

                $request_id = Journal::AddFreeOnlineSubsRequest($data);

                if($request_id > 0)
                {
                    $to   = 'rehana@benthamscience.net';
                    $from = 'support@benthamscience.net';
                    $cc   = 'azhar@benthamscience.net';
                    $bcc  = 'armash@xolva.com';
                    // $to   = 'zafar@benthamsceince.net';
                    // $from = 'support@benthamscience.net';
                    // $cc   = 'azhar@benthamscience.net';
                    // $bcc  = 'faizan@benthamscience.net,armash@xolva.com';

                    $subject = "Editorial Subscription Request - Subscription Office Record";

                    SendSmtpMail('email_template.free_online_subscription_offer', $data, $to, $from, $subject, 'Admin', $cc, $bcc);

                    return back()->with('success', ' Thank you for submitting your Free Online Subscription request, very soon our representative of Editorial/Subscription office will contact you. if you have any further query, you may write us at <a href="mailto:support@benthamscience.net">support@benthamscience.net</a> .');
                }
        } 
        else 
        {
            $journal = Journal::GetAllContinuedJournal();
            $country        = Country::GetCountryList();
            //dd($journal);
            return View::make('form.free-online-subscription-offer', with(['journal' => $journal, 'country' => $country]));
        }
    }

    public function ManageJournalSection(Request $request)
    {   
        if($request->form_action == 'Submit')
        {
            $this->AddJournalSection($request);
        }
        else if($request->form_action == 'Update')
        {
            $this->UpdateJournalSection($request);
        }
        else if($request->form_action == 'Delete'){
            $this->DeleteJournalSection($request);
        }
    }

    public function AddJournalSection($request)
    {
        $data = array(
            'journal_id' => $request->journal_id,
            'js_code' => $request->subtitle,
            'js_title' => trim($request->js_title),
            'js_description' => htmlspecialchars($request->js_description, ENT_QUOTES),
            'js_aims_and_scope' => htmlspecialchars($request->js_aims_and_scope, ENT_QUOTES),
            'js_status' => $request->js_status,
            'js_created_on'=> time(),
            'js_created_by'=> Auth::user()->id,
            'js_updated_on'=>time(),
            'js_updated_by'=>Auth::user()->id
        );
        $section_id = Journal::JournalSectionAdd($data);
       echo json_encode(['msg'=> 'Journal Section Added.']);
    }

    public function UpdateJournalSection($request)
    {
        $data = array(
            'js_id' => $request->js_id,
            'js_title' => trim($request->js_title),
            'js_description' => htmlspecialchars($request->js_description, ENT_QUOTES),
            'js_aims_and_scope' => htmlspecialchars($request->js_aims_and_scope, ENT_QUOTES),
            'js_status' => $request->js_status,
            'js_updated_on'=> Auth::user()->id,
            'js_updated_by'=>time()
        );
        Journal::JournalSectionUpdate($data);
        echo json_encode(['msg'=> 'Journal Section Updated.']);
    }

    public function DeleteJournalSection($request)
    {
        $data = array(
            'js_id' => $request->js_id,
            'js_status' => 0,
            'js_updated_on'=> Auth::user()->id,
            'js_updated_by'=>time()
        );
        Journal::JournalSectionDelete($data);
        echo json_encode(['msg'=> 'Journal Section Deleted.']);
    }

public function SectionEditorForm(Request $request)
    {
        if ($request->input('section_editor')) {
            $this->validate($request, [
                'cv.*' => 'mimes:doc,docx,pdf',
                'email' => 'required|email|max:255',
                'captcha' => 'required|captcha'
            ], ['captcha.captcha' => 'Invalid captcha code.']);

            $section_editor_data = array(
                'reg_type'                      => "section_editor",
                'first_name'                    => $request->input('first_name'),
                'last_name'                     => $request->input('last_name'),
                'country'                       => $request->input('country'),
                'city'                          => $request->input('city'),
                'email'                         => $request->input('email'),
                'expertise'                     => $request->input('expertise'),
                'comments'                      => $request->input('comments'),
                'ip_address'                    => ip2long($request->ip()),
                'updated_on'                    => time(),
            );

            $section_editor_id = Journal::Add_EBM_Review($section_editor_data);

            $to   = 'faizan@benthamscience.net';
            $from = $request->input('email');
            $cc   = 'hermain@benthamscience.net';
            $bcc  = 'bentham.eureka@gmail.com,azhar@xolva.com';
            $attachments = $request->file('cv');

            $subject = "Eurekaselect: Section Editor Registration";

            SendSmtpMail('email_template.become_section_editor', $section_editor_data, $to, $from, $subject, 'Admin', $cc, $bcc, $attachments);


            return back()->with('success', '<strong>Thank you</strong> We appreciate you taking the time to fill out the form. Your submission has been emailed to the concerned department. If your request requires a reply, we will be in contact with you shortly.');
        }

        $country = Country::GetCountryList();
        return view('form.section_editor_form', with(['country' => $country]));
    }

    public function GetCallForPapers(Request $request)
    {
        $alphabet       = "";
        $journal_search = "";
        $year           = "";
        $search_year    = "";
        $jms_article    = "";
        $param['journal_group'] = false;
        $param['paginate'] = true;
        $searchFormRoute = 'callforpapers';
        $reference_number_list = array();
        $article_list = array();
        $journal = array();
        $continues_publication_journal = array();


        if (strpos($request->path(), 'browse-by-subscribe') !== false) {
            session(['mysubscribption' => true]);
        }
        if (strpos($request->path(), 'bypublication') !== false) {

            session()->forget('mysubscribption');
        }

        if (isset($request->alphabet)) {
            if (strlen($request->alphabet) == 4) {
                if (is_numeric($request->alphabet)) {
                    $search_year = trim($request->alphabet);
                }
            } else {
                $alphabet = $request->alphabet;
            }
        }
        if (isset($request->btnjournalsearch)) {
            $journal_search = $request->journal_search;

            if (strpos($journal_search, '10.2174/') !== false) {

                $article_obj = Article::GetArticleByDOI($journal_search);
                if (!empty($article_obj)) {
                    return Redirect::to('article/' . $article_obj->article_id);
                }
            }
        }

        $journal_list = Journal::GetJournalTitle();

        $year = Journal::GetYear();

        if (session()->has('mysubscribption')) {

            if (session()->has('ip_base_access') || session()->has('user_base_access')) {
                $user_id = session()->get('user_id');
                $param['user_id'] = $user_id;
            }

            $param['letter'] = $alphabet;
            $param['journal_name'] = $journal_search;
            $param['year'] = $search_year;
            $param['ip_address'] = ip2long($request->ip());

            $journal = Journal::SearchSubscriptionList($param);

            $searchFormRoute = 'browsebysubscribe';
        } 
        else 
        {

            if(!isset($request->param))
            {
                $param['journal_group'] = true;
                $page_name = "journal-listing";
            }

            if(isset($request->param))
            {   
                if($request->param == "journal")
                {
                    $param['subtitle'] = $request->id;
                    $page_name = "specialissue-list";

                }

                if($request->param == "specialissue")
                {
                    $param['htcode'] = $request->id;
                    $page_name = "specialissue-detail";
                    $searchFormRoute = 'callforpapers-detail';
                    $param['paginate'] = false;

                    $jms_article = Manuscript::SearchHTArticleList($param);

                    if(!empty($jms_article))
                    {
                        foreach ($jms_article as $manuscript_list) 
                        {
                            if(!empty($manuscript_list->reference_number))
                            {
                                $reference_number_list[] = $manuscript_list->reference_number;
                            }
                        }
                        if(!empty($reference_number_list)) 
                        {
                            
                            $article_list = Manuscript::GetArticlebyJMSRefNumber($reference_number_list, 20);

                            if ($article_list->count() > 0) 
                            {
                                $article_list = $this->CheckUserAccessonArticle($article_list);
                                $b = 0;

                                if (count($article_list) > 0) {
                                    foreach ($article_list as $key => $value) {
                                        $AuthorNames     = '';
                                        $article_authors = Author::GetAuthorsByContentId($value->article_id, 'article_id');
                                        if (!empty($article_authors)) {
                                            $AuthorNames = '';
                                            foreach ($article_authors as $author) {
                                                if ($author->is_principle == 1) {
                                                    $AuthorNames .= $author->authors . '*' . ',  ';
                                                } else {
                                                    $AuthorNames .= $author->authors . ',  ';
                                                }
                                            }
                                            $AuthorNames = rtrim($AuthorNames, ', ');
                                        }
                                        $pos = strrpos($AuthorNames, ",");
                                        if ($pos) {
                                            $str         = substr($AuthorNames, 0, $pos);
                                            $str2        = substr($AuthorNames, $pos + 1, strlen($AuthorNames));
                                            $AuthorNames = $str . " and " . $str2;
                                        }
                                    }

                                    $article_list[$b]->authors = $AuthorNames;
                                    $b++;
                                }
                            }
                        }
                    }
                }
            }
            if($request->param == "specialissue")
            {
            $journal_title = Manuscript::GetJournalByHtCode($request->id);
            $journal = Journal::GetJournalByJMSCode($journal_title->journal_code);            

            }
                $jms_journal = Manuscript::SearchJMSJournalList($alphabet, $journal_search, $search_year, $param);
        }

            $publication_journal = Article::GettAllContinuePublicationJournal();
            foreach ($publication_journal as $publication_journals) {
                $continues_publication_journal[] = $publication_journals->subtitle;
            }

        $subject_list = Subject::getAllSubjects();
        $temp = rtrim(Subject::display_parent(), '_');
        $option = explode('_', $temp);
        $arr = array();
        if ($temp != '') {
            //disease=1_diabetes=2_
            foreach ($option as $pair) {
                list($name, $id) = explode('=', $pair);
                if ($id != '') {
                    $arr[0] = 'Please Select';
                    $arr[$id] = $name;
                }
            }
        } else {
            $arr[0] = 'Please Select';
        }


        //dd($article_list);
        // $volume_list     = Volume::GetVolume($param);

        return view($searchFormRoute, with(['journal' => $journal, 'jms_journal' => $jms_journal, 'journal_list' => $journal_list, 'year' => $year, 'alphabet' => $alphabet, 'searchFormRoute' => $searchFormRoute, 'page_name' => $page_name, 'article_list' => $article_list, 'continues_publication_journal' => $continues_publication_journal, 'subject_list' => $arr]));
    }
    
}
