<?php

namespace App\Http\Controllers;

use App\Http\Controllers\PaypalExpress;
use App\Models\Article;
use App\Models\BundleOffer;
use App\Models\Orders;
use App\Models\Country;
use App\Models\Author;
use App\Models\Manuscript;
use App\Models\UserAccess\UserAccess;
use App\Models\UserAccess\UserAccessOrganization;
use App\Rules\Captcha;
use App\User;

use Auth;
use File;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Mpdf\Mpdf;
use View;

class HomeController extends BenthamController
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (session()->has('referral_base_access')) {
            return Redirect::to('/');
        }
        $used_token            = array();
        $available_token       = array();
        $SearchToken           = array();
        $access_user_data      = array();
        $bundle_order          = array();
        $rental_order          = array();
        $used_token_array      = array();
        $available_token_array = array();
        $user_consortia_counter = array();
        $registeredips          = array();
        $subscribed_content     = array();
        $view_submissions       = array();
        $member_admin           = array();
        $accessdata             = array();
        $used_token_count      = 0;
        $available_token_count = 0;
        $total_submissions = 0;
        $total_content = 0;
        $total_openaccess = 0;
        $institute_content = array();
        $openaccess_article = array();

        if ($request->ajx_search == true) {
            $param['bundle_offer_order_id'] = $request->get('bundle_offer_order_id');
            $bundle_content                 = BundleOffer::GetBundleOfferOrderContent($param);
            if (count($bundle_content) > 0) {
                return response()->json($bundle_content, 200);
            } else {
                return response()->json(false, 200);
            }
        }

        if (!Auth::check()) {
            return redirect("/");
        }
        $user = User::getUserInfo();
        $pages  = '';
        $orders = '';
        //  if agent login then redirect to its dashboard
        if(!empty($user->agent_access_type)){
            return redirect('/crm/dashboard');
            exit();
        }


        foreach ($user->role as $roles) {
            if ($roles->slug != "user") {
                if ($request->pages != "editprofile") {
                    return redirect('/admin/dashboard');
                }
            }
        }
        $pages = $request->pages;

        // Token Report
        if (Auth::check()) {
            //$user_base_access_data  = $request->session()->get('access_user_data');
            $user_base_access_data = UserAccess::where('user_id', $user->id)->where('user_access_status', 1)->get();

            $token_type = array(444, 555, 666);
            if (!empty($user_base_access_data)) {
                foreach ($user_base_access_data as $k => $v) {
                    if ($v->user_id == $user->id) {
                        if (in_array($v->access_type_id, $token_type)) {
                            $access_user_data        = $user_base_access_data[$k];
                            $access_type_id          = $access_user_data->access_type_id;
                            $param['user_access_id'] = $access_user_data->user_access_id;
                            $param['access_on']      = $access_user_data->access_type_on;
                            if ($param['access_on'] == 'journal_volume' || $param['access_on'] == 'issue' || $param['access_on'] == 'article') {
                                $join['journal']      = true;
                                $join['volume']       = true;
                                $join['issue']        = true;
                                $join['article']      = true;

                                if ($user->id == 394991) {
                                    $join['ebook_volume'] = true;
                                    $join['chapter']      = true;
                                } else {
                                $join['ebook_volume'] = false;
                                $join['chapter']      = false;
                            }
                            }

                            if ($param['access_on'] == 'ebook_volume') {
                                $join['journal']      = false;
                                $join['volume']       = false;
                                $join['issue']        = false;
                                $join['article']      = false;
                                $join['ebook_volume'] = true;
                                $join['chapter']      = false;
                            }

                            if ($param['access_on'] == 'chapter') {
                                $join['journal']      = false;
                                $join['volume']       = false;
                                $join['issue']        = false;
                                $join['article']      = false;
                                $join['ebook_volume'] = true;
                                $join['chapter']      = true;
                            }

                            $used_token[] = UserAccess::GetAccessUsedTokenList($param, $join);
                            
                            if ($access_type_id == 555) {
                                $param['download_count'] = 0;
                            }

                            $available_token[] = UserAccess::GetAccessTokenList($param);
                        }
                    }
                }
            }
        }
        if (!empty($access_user_data)) {
            $access_type_id          = $access_user_data->access_type_id;
            $param['user_access_id'] = $access_user_data->user_access_id;
            $param['access_on']      = $access_user_data->access_type_on;

            if (!empty($used_token)) {
                for ($k = 0; $k < count($used_token); $k++) {
                    $used_token_array = $used_token[$k]->merge($used_token_array);
                }
            }
            if (!empty($available_token)) {

                for ($k = 0; $k < count($available_token); $k++) {
                    $available_token_array = $available_token[$k]->merge($available_token_array);
                }
            }

            // dd($available_token_array);

            // All Tokens (Available and Used)
            $used_token      = $used_token_array;
            $available_token = $available_token_array;

            $used_token_count = $used_token->count();

            if (!empty($available_token_array)) {
                $av_count = 0;
                foreach ($available_token_array as $av_val) {
                    $av_count = $av_count + $av_val->download_count;
                }
            }
            // dd($av_count);

            //$available_token_count = $av_count - $used_token_count;

            $available_token_count = $user_base_access_data[0]->restricted_download_limit - $used_token_count;

            if ($access_type_id == 555) {
                $param['download_count'] = 0;
            }
            //$available_token = UserAccess::GetAccessTokenList($param);
            //$available_token = $available_token_array;

            if ($request->search == 'SearchToken') {
                return $this->SearchToken($request, $access_user_data);
            }
        }

        if ($pages == 'exporttokenlist') {
            return $this->ExportTokenList($request, $used_token, $available_token);
        }

        if ($pages == 'invoice') {
            $request->customer_email = $user->email;
            $request->order_status   = 'completed';
            $orders                  = Orders::GetOrderList($request, 100);
        }
        if ($pages == 'exportinvoice') {
            $details = $this->GetOrderDetails($request);

            /* $email_template='email_template.testing';
            $view_data['temp']='Arshad';
            $to='arshad@xolva.com';
            $from='admin@xolva.com';
            $subject='Testing Email';
            SendSmtpMail($email_template,$view_data, $to, $from, $subject);*/

            $mpdf = new Mpdf(['mode' => 'utf-8', 'format' => 'A4', 'margin_left' => '5', 'margin_right' => '5']);

            $html = View::make('admin.orders.template.invoice')
                ->with('order', $details['order'])
                ->with('user', $details['user'])
                ->with('payments', $details['payments'])
                ->with('balance', $details['balance'])
                ->with('products', $details['products'])
                ->with('comments', $details['comments'])
                ->with('admin_comments', $details['admin_comments'])
                ->with('order_logs', $details['order_logs'])
                ->with('ord_status', $details['ord_status']);
            $mpdf->WriteHTML($html, 2);
            $mpdf->Output($details['order']->order_id . '-order.pdf', 'D');
            exit();
        }
        $countries = $this->countries;

        //dd($user->user_id);
        //---------------------Bundle Order------------------------
        $sparam['user_id']             = $user->id;
        $sparam['order_status']        = 'C';
        $sparam['bundle_order_status'] = 'C';
        $sparam['bundle_offer_expiry'] = time();
        $sparam['paginate']            = true;
        $bundle_order                  = "";
        $bundle_content                = "";

        $bundle_order = BundleOffer::GetBundleOfferOrderDetail($sparam);

        if (count($bundle_order) > 0) {
            $a = 0;
            foreach ($bundle_order as $bo) {
                $bundle_count                       = "";
                $bundle['bundle_offer_order_id']    = $bo->bundle_offer_order_id;
                $bundle_count                       = BundleOffer::GetBundleOfferContentCount($bundle);
                $bundle_order->items()[$a]->article = $bundle_count[0]->article;
                $bundle_order->items()[$a]->chapter = $bundle_count[0]->chapter;
                $bundle_order->items()[$a]->ebook   = $bundle_count[0]->ebook;

                $a++;
            }
        }
        //-----------------------Bundle Order-------------------------
        $sparam['paginate'] = true;
        $rental_order       = Article::GetArticleRentalDetail($sparam);
        if (!empty($user->counter_report_year)) {
            $year_arr = explode(',', $user->counter_report_year);
            foreach ($year_arr as $yy) {
                $counteruseryears[$yy] = $yy;
            }
        } else {
            $counteruseryears = array(date('Y') => date('Y'));
        }

        // -----------------------Consortia User----------------//
        $cparam['agent_id'] = session()->get('user_id');
        $cparam['paginate'] = true;
        $cparam['user_access_status'] = 1;

        if ($pages == "usageconsortiareport" || $pages == "registeredips" || $pages == "view_submissions") {
            $cparam['groupby'] = true;
        }

        $user_consortia_counter = User::getUserConsoriaById($cparam);

        if($user_consortia_counter->count() == 0){
            $user = User::where('id', $cparam['agent_id'])->first();

            if(!empty($user->institution_associations) || !empty($user->societies_associations)){
            return redirect()->route('member');
            }
        }

        $member_admin = User::GetMemberAdmin($cparam['agent_id']);

        if ($pages == "usagereport" && isset($request->id)) {
            $user = User::where('id', $request->id)->first();
        }

        $consortia_admin = array("impadmin", "rfbr-admin", "csucadmin", "ankosadmin", "CSICAdmin" , "croatia-admin");
        
        if ($pages == "usagereport" && in_array($user->name, $consortia_admin)) {
            return redirect()->route('home');
        }   
              
        if ($pages == "registeredips" && isset($request->id)) {
            $user = User::where('id', $request->id)->first();
            $cparam['user_id'] = $user->id;
            $accessdata = UserAccess::GetUserAccessInfo($cparam);
            if(isset($accessdata)){
                if ($accessdata->access_base_type == 1) {
                    if ($request->has('submit_it')) {
                       $cparam['ip_address'] = $request->search_ip;
                    } 
                   
                    $cparam['access_type_on'] = $accessdata->access_type_on;
                    $cparam['access_type_id'] = $accessdata->access_type_id;
                    $registeredips = UserAccess::getUserRegisteredIps($cparam);
                   // dd($registeredips);
                }
            }
        }
        if ($pages == "susbscribed_content" && isset($request->id)) {
            $cparam['user_access_id'] = $request->id;
            $cparam['user_access_status'] = 1;
            $accessdata = UserAccess::GetUserAccessInfo($cparam);
            if (isset($accessdata)) {
                $access_check = false; //Dummy variable

                $user = User::GetUserOrganization($accessdata->user_id);

                if($accessdata->content_data==1 && $accessdata->user_access_status==1){
                    $v_param['access_type_id'] = $accessdata->access_type_id;
                    $v_param['access_on']      = $accessdata->access_type_on;
                    $v_param['user_id']        = $accessdata->user_id;
                    $v_param['limit']          = 20;
                    $v_param['group_by']       = 'journal_id';


                    $ajoin['user_access_info'] = true; // Default True
                    $ajoin['user'] = true; // Default True
                    $ajoin['year'] = true; // Default True

                    if ($accessdata->access_type_on == 'journal_volume') {
                        $ajoin['journal'] = $ajoin['volume'] = $ajoin['year'] = true;
                        $access_check = true;
					}
                    if ($accessdata->access_type_on == 'ebook_volume') {
                        $ajoin['ebook_volume'] = $ajoin['year'] = true;
                        $v_param['group_by']       = 'ebook_volume';
                        $access_check = true;
                    }
                    if ($accessdata->access_type_on == 'disease') {
                        $ajoin['disease'] = true;
                        $v_param['access_type_id'] = 777; // Corporate Disease
                        $access_check = true;
					}


/*					We are not checking here below access (if requred then uncommit and test)
					if ($accessdata->access_type_on == 'issue')
					{
						$ajoin['journal'] = $ajoin['volume'] = $ajoin['year'] = $ajoin['issue'] = true;
					}
					if ($accessdata->access_type_on == 'article')
					{
						$ajoin['journal'] = $ajoin['volume'] = $ajoin['year'] = $ajoin['issue'] = $ajoin['article'] = true;
					}
					if ($accessdata->access_type_on == 'chapter')
					{
                        $ajoin['ebook_volume'] = $ajoin['chapter'] = true;
                        $v_param['group_by']       = 'chapter_id';
					}
*/
                    if ($access_check) {
                        $subscribed_content =  UserAccess::GetUserSubscribedContent($v_param, $ajoin);
                    }
                }
            }
        }

        if ($pages == "view_submissions" && isset($request->id)) {
            $user = User::GetUserOrganization($request->id);
            $cparam['user_id'] = $user->id;
            $accessdata = UserAccess::GetUserAccessInfo($cparam);

            if (isset($user->institution_id)) {
                    $jms_api_Url = 'https://bentham.manuscriptpoint.com/JmsWebServices/GetSubmissionByInstitution/'.$user->institution_id;
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $jms_api_Url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    $output = curl_exec($ch);

                    if (curl_errno($ch)) {
                        $error_msg = curl_error($ch);
                    }
                    curl_close($ch);

                    $view_submissions = json_decode($output);
                    $param['institution_id'] = $user->institution_id;
                    $institute = User::GetInstitutes($param)[0];

                    $cparam['name']     = $institute->name;
                    $cparam['city']     = $institute->city;
                    $cparam['country']  = $institute->country;

                    $institute_content = Article::GetInstituteContent($cparam);
                // dd($institute_content);

                $a = 0;
                $b = 0;
                if ($institute_content->count() > 0) {
                    foreach ($institute_content as $value) {
                         $article = Article::GetConsortiaFreeOpenAccessArticles($value->journal_id, 2, $value->article_id);

                        if (!empty($article)) {
							$openaccess_article[] = $article;
                            if (count($openaccess_article) > 0) {
                                foreach ($openaccess_article 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;
									}
								}
								
									$openaccess_article[$b]->authors = $AuthorNames;
									$b++;
							}
                        }

                        $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;
						}
        
                        $institute_content[$a]->authors = $AuthorNames;
                        $a++;
                    }
                }
            }
            if (is_array($view_submissions) && count($view_submissions) > 0) {
                    $total_submissions = count($view_submissions);
            } else {
                    $view_submissions = '';
                }
        }

        $total_content = isset($institute_content) ? count($institute_content) : 0;
        $total_openaccess = isset($openaccess_article) ? count($openaccess_article) : 0;

        $data =  array();

        $template = 'home';

        return view('home', with([
            'user' => $user,
            'member_admin'                   => $member_admin,
            'countries'                      => $countries,
            'pages'                          => $pages,
            'orders'                         => $orders,
            'used_token'                     => $used_token,
            'used_token_count'               => $used_token_count,
            'available_token'                => $available_token,
            'available_token_count'          => $available_token_count,
            'SearchToken'                    => $SearchToken,
            'access_user_data'               => $access_user_data,
            'bundle_order'                   => $bundle_order,
            'bundle_content'                 => $bundle_content,
            'user_consortia_counter'         => $user_consortia_counter,
            'rental_order'                   => $rental_order,
            'counteruseryears'               => $counteruseryears,
            'registeredips'                  => $registeredips,
            'subscribed_content'             => $subscribed_content,
            'view_submissions'               => $view_submissions,
            'institute_content'              => $institute_content,
            'openaccess_article'             => $openaccess_article,
            'request'                        => $request,
            'total_submissions'              => $total_submissions,
            'total_content'                  => $total_content,
            'total_openaccess'               => $total_openaccess,
            'accessdata'                     => $accessdata
        ]));
    }

    public function GetOrderDetails($request)
    {
        $balance      = 0;
        $paid_amounts = 0;
        $order        = Orders::GetOrder($request->id);
        $user         = User::getUserById($order->uid);
        $products     = Orders::GetOrderProducts($request->id);
        $payments     = Orders::GetOrderPaymentReceipts($request->id);
        if ($payments) {
            foreach ($payments as $paid) {
                $paid_amounts = $paid_amounts + $paid->amount;
            }
            $balance = $order->order_total - $paid_amounts;
        }
        $comments       = Orders::GetOrderComments($request->id);
        $admin_comments = Orders::GetOrderAdminComments($request->id);
        $order_logs     = Orders::GetOrderLogs($request->id);
        $ord_status     = Orders::GetOrderStatus();

        return with([
            'order' => $order,
            'user'               => $user,
            'payments'           => $payments,
            'balance'            => $balance,
            'products'           => $products,
            'comments'           => $comments,
            'admin_comments'     => $admin_comments,
            'order_logs'         => $order_logs,
            'ord_status'         => $ord_status
        ]);
    }

    public function UpdateProfile(User $user, Request $request)
    {
        if ($request->password == null) {
            $validator = Validator::make(
                $request->all(),
                [
                    'display_name' => 'required',
                    'first_name'   => 'required',
                    'last_name'    => 'required',
                ]
            );
        } else {
            $validator = Validator::make(
                $request->all(),
                [
                    'display_name'     => 'required',
                    'first_name'       => 'required',
                    'last_name'        => 'required',
                    'password'         => 'required_with:password_confirm|same:password_confirm|min:6',
                    'password_confirm' => 'min:6',
                ]
            );
        }

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

                $user_id                    = decrypt($request->utm);
                $update_obj['display_name'] = $request->display_name;
                $update_obj['first_name']   = $request->first_name;
                $update_obj['last_name']    = $request->last_name;
                $update_obj['dob']          = $request->dob;
                $update_obj['bio']          = $request->bio;
                $update_obj['gender']       = $request->gender;
                $update_obj['country']      = $request->country;
                $update_obj['state']        = $request->state;
                $update_obj['city']         = $request->city;
                $update_obj['address']      = $request->address;
                $update_obj['postal']       = $request->postal;
                $update_obj['updated_at']   = time();

                $user  = User::getUserById($user_id);

                if ($user->change_password == 1) {
                    if (!empty($request->password)) {
                        $password               = Hash::make($request->password);
                        $update_obj['password'] = $password;
                    }
                }

                // is new image uploaded?
                if ($file = $request->file('pic_file')) {
                    $extension = $file->extension() ?: 'png';
                    //$destinationPath = public_path() . '/uploads/users/';
                    $destinationPath = 'uploads/users/';
                    $safeName        = str_random(10) . '.' . $extension;
                    $file->move($destinationPath, $safeName);
                    //delete old pic if exists
                    if (File::exists($destinationPath . $user->pic)) {
                        File::delete($destinationPath . $user->pic);
                    }
                    //save new file path into db
                    $update_obj['pic'] = $safeName;
                }
                           
                if ($request->openathensrealmName && $request->openathensderivedEduPersonScope) {
                    $oaupdate_obj['display_name']                       = $request->display_name;
                    
                    $oaupdate_obj['openathensOrganisationId']           = $request->openathensOrganisationId;
                    $oaupdate_obj['openathensrealmName']                = $request->openathensrealmName;
                    $oaupdate_obj['openathensderivedEduPersonScope']    = $request->openathensderivedEduPersonScope;
                    User::where('id', $user_id)->update($oaupdate_obj);

                    return redirect('/crm/dashboard?_token=' . $request->_token . '&by_country=' . $request->by_country . '&by_customer=' . $request->by_customer)->with('success', "User was successfully updated.");
                } else {
                User::where('id', $user_id)->update($update_obj);
                //save record
                }
                // Was the user updated?
                if ($update_obj) {
                    // Redirect to the user pages
                    return redirect('home')->with('success', "User was successfully updated.");
                }

                // Prepare the error message
                $error = "There was an issue updating the user. Please try again.";
            } catch (UserNotFoundException $e) {
                // Prepare the error message
                $error = "User does not exist.";

                // Redirect to the user management page
                return redirect('home#profileedit')->withInput()->with('error', $error);
            }

            // Redirect to the user page
            return redirect('home#profileedit')->withInput()->with('error', $error);
        }
    }

    public function AdminDashboard(Request $request)
    {
        //dd($request->route()->getPrefix());
        return view('admin.dashboard');
    }

    public function ShowUserLogin($value = '')
    {
        return view('login');
    }

    public function ShowAdminLogin()
    {
        if (Auth::user()) {
            return redirect('/admin/dashboard');
        }
        return view('admin.login');
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    //Get content id, read pdf param, access type id, content type (article/chapter)
    public function Terms(Request $request)
    {
        return view('terms.termandcondition', with(['content_id' => $request->content_id, 'param' => $request->param, 'content' => $request->content, 'file_type' => $request->file_type]));
    }

    public function TermsTrial(Request $request)
    {
        return view('terms.termandcondition_trial', with(['access_type' => $request->access_type, 'content_id' => $request->content_id, 'param' => $request->param, 'content' => $request->content, 'file_type' => $request->file_type]));
    }

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

            if ($validator->fails()) {
                $detail['name']          = '';
                $detail['email']         = '';
                $detail['site_comment']  = '';
                $detail['other_comment'] = '';
                return view('feedback', with(['detail' => $detail]))->withErrors($validator);
            } else {

                $detail = array();
                //$to = "feedback@benthamscience.org";

                if (!strpos($request->site_comment, 'https://') && !strpos($request->other_comment, 'https://') && !strpos($request->site_comment, 'http://') && !strpos($request->other_comment, 'http://')) {
                        $to      = 'armash@xolva.com';
                $cc      = env('email_xolva_2') . ',' . env('email_support_2');
                $from    = $request->email;
                $subject = "Eurekaselect: Feedback - (".$request->ip().")";
				
                $detail['name']          = $request->name;
                $detail['email']         = $request->email;
                $detail['site_comment']  = $request->site_comment;
                $detail['other_comment'] = $request->other_comment;
                $detail['ip']            = $request->ip();
				
                SendSmtpMail('email_template.feedback', $detail, $to, $from, $subject, $request->name, $cc);
                    } 

                $message = true;
                return view('feedback', with(['detail' => $detail, 'message' => $message]));
            }
        } else if ($request->param) {  //dd($request);
           $param = (object) unserialize($request->param);

           $article = Author::GetArticleByAuthor($param->journal_id, $param->article_id, $param->author_id);

            return view('feedback-laterofthanks', with(['article' => $article]));
        } else if ($request->submit_lot) {
            $validator = Validator::make(
                $request->all(),
                [
                    'experience'        => 'required|in:1,2,3,0',
                    'services'          => 'required|in:1,2,0',
                    'captcha'           => 'required|captcha'
                ],
                ['captcha.captcha'   => 'Invalid captcha code.']
            );

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

                $data = array();
                $data['journal_id']   = $request->journal_id;
                $data['author_id']    = $request->author_id;
                $data['article_id']   = $request->article_id;
                $data['experience']   = $request->experience;
                $data['services']     = $request->services;
                $data['improvement']  = $request->improvement;
                $data['sub_datetime'] = time();
                $data['sub_ip']       = ip2long($request->ip());

                $feedback = Author::GetAuthorFeedBack($data);

                if ($feedback->count() > 0) {
                    Session::flash('error', " You have already post your feedback");
                    return back();
                }

                $id = Author::AddAuthorFeedBack($data);

                if ($id) {
                    $param = array();
                    $param['id'] = $id;
                    $feedback = Author::GetAuthorFeedBack($param)[0];
                    //$to = "feedback@benthamscience.org";

                    if (!strpos($request->improvement, 'https://') && !strpos($request->improvement, 'https://')) {
                        $to      = 'azhar@benthamscience.net';
                        $cc      = env('email_xolva_2') . ',' . env('email_support_2');
                        $from    = $feedback->email;
                        $subject = "Eurekaselect: Author Feedback - (".$request->ip().")";
                        $detail['journal']          = $feedback->journal_title;
                        $detail['article_tile']     = $feedback->article_title;
                        $detail['name']             = $feedback->author;
                        $detail['email']            = $feedback->email;
                        $detail['experience']       = $feedback->experience;
                        $detail['services']         = $feedback->services;
                        $detail['improvement']      = $feedback->improvement;
                        $detail['ip']               = $request->ip();

                        SendSmtpMail('email_template.feedback', $detail, $to, $from, $subject, $request->name, $cc);
                    }

                    $message = true;
                    return view('feedback-laterofthanks', with(['detail' => $detail, 'message' => $message]));
                }
            }
        } else {
            $detail['name']          = '';
            $detail['email']         = '';
            $detail['site_comment']  = '';
            $detail['other_comment'] = '';
        }
        return view('feedback', with(['detail' => $detail]));
    }

    public function CrossMark()
    {
        return view('crossmark');
    }

    public function SearchToken($request, $access_user_data)
    {

        $user_name = $request->user_name;
        $user_id   = session()->get('user_id');

        $user_access_id    = $access_user_data->user_access_id;
        $access_type_id    = $access_user_data->access_type_id;
        $access_type       = $access_user_data->access_type_on;
        $token_access_data = array();

        if (!empty($user_name) && !empty($user_id)) {
            $param['user_id']           = $user_id;
            $param['user_name']         = $user_name;
            $param['user_access_id']    = $user_access_id;
            $param['access_on']         = $access_type;
            $join['token_access_usage'] = true;
            $usage_token_list           = UserAccess::GetAccessTokenList($param, $join);
            $available_flag             = 0;
            $token_flag                 = 0;
            $token_access_data          = array();

            if ($usage_token_list->count() > 0) {
                $access_user_data = $request->session()->get('access_user_data');
                $token_type       = array(444, 555, 666);

                foreach ($access_user_data as $aud) {

                    if ($aud->access_type_id == '444' || $aud->access_type_id == '555') {
                        $token_access_data = $aud;
                        $token_flag        = 1;
                    }
                }
                if (!empty($token_access_data)) {
                    if ($token_access_data->restricted_download_limit > count($usage_token_list)) {
                        foreach ($usage_token_list as $available_token) {
                            if ($available_token->user_name === $user_name && $available_token->download_content_id == 0 && $token_flag == 1) {
                                $available_flag = 1;
                            }
                        }
                    }
                }
                if ($available_flag == 1) {
                    return array($available_token->user_name, 'Available');
                } else {
                    return array($user_name, 'Not Available');
                }
            } else {
                return array($user_name, 'Incorrect Username');
            }
        }
    }

    public function ExportTokenList($request, $used_token, $available_token)
    {
        $tr_data = '';
        if (!empty($used_token)) {
            $tableHeader = "<table width='1000' align='center' border='1'>
                <tr><td><b>'Used Token Report'</b></td></tr>";
            $tableHeader .= "<tr align='center'>";
            $tableHeader .= "<td align='center' bgcolor='#CCCCCC'><b>Journal Title</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Print ISSN</b></td>
                <td bgcolor='#CCCCCC'><b>Online ISSN</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Year</b></td>
                                <td bgcolor='#CCCCCC'><b>DOI</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Article Title</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Volume No</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Issue No</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Pages</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Content Access Key</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Downloaded From IP</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Download Date</b></td>";
            $tableHeader .= "<td bgcolor='#CCCCCC'><b>Access Assign Date</b></td></tr>";

            foreach ($used_token as $token) {

                $tr_data .= "<tr><td>" . $token->journal_title . "</td>
                                  <td>" . $token->journal_issn . "</td>
                                  <td>" . $token->journal_eissn . "</td>
                                  <td>" . $token->year . "</td>
                                  <td>" . $token->article_doi . "</td>
                                  <td>" . $token->article_title . "</td>
                                  <td>" . $token->volume_name . "</td>
                                  <td>" . $token->issue_title . "</td>
                                  <td>" . $token->first_page . ' to ' . $token->last_page . "</td>
                                  <td>" . $token->user_name . "</td>
                                  <td >" . long2ip($token->download_ip) . "</td>
                                  <td>'" . strftime("%d-%m-%Y", $token->download_time) . "</td>
                                  <td>" . strftime("%d-%m-%Y", $token->system_time) . "</td>";
                $tr_data .= "</tr>";
            }

            $table = $tableHeader;
            //$table.='<br>';
            $table .= $tr_data . "</table>";

            header("Content-type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=token_report.xls");
            print $table;
            exit;
        } else {
            return back();
        }
    }

    public function RenderImage($param)
    {

        $imagepath = decrypt($param);
		//dd($imagepath);
        readfile($imagepath);

        die;
    }

    public function Webinars(Request $request)
    {

        $country      = Country::GetCountryList();
        if ($request->submit_webinars) {
            $validator = Validator::make(
                $request->all(),
                [
                    'salutation'    => 'required',
                    'first_name'    => 'required',
                    'last_name'     => 'required',
                    'webinar_title' => 'required',
                    'webinar_id'    => 'required',
                    'email'         => 'required|string|email|max:255',

                ]
            );

            if ($validator->fails()) {
                $detail['name']          = '';
                $detail['email']         = '';
                $detail['site_comment']  = '';
                $detail['other_comment'] = '';
                return view('webinars', with(['detail' => $detail,'country' => $country]))->withErrors($validator);
            } else {

                $paypal['id']             = $request->webinar_id;
                $paypal['name']           = 'Academic branding: Improving your visibility, network, and career opportunities';
                $paypal['paypalEnv']      = env('paypalEnv');
                $paypal['paypalURL']      = env('paypalURL');
                $paypal['business']       = env('email_business', '');
                $paypal['price']          = 25;
                $paypal['currency_code']  = 'USD';
                $paypal['paypalClientID'] = env('paypalClientID');
                

                $salutation    = $request->salutation;
                $first_name    = $request->first_name;
                $last_name     = $request->last_name;
                $email         = $request->email;
                $city          = $request->city;
                $country       = $request->country;
                $phone_number  = $request->phone_number;
                $institute_org = $request->institute_org;
                $webinar_title = $request->webinar_title;
                $webinar_id    = $request->webinar_id;
                $webinar_info  = array(
                    'salutation' => $salutation,
                    'first_name'                        => $first_name,
                    'last_name'                         => $last_name,
                    'email'                             => $email,
                    'city'                              => $city,
                    'country'                           => $country,
                    'phone_number'                      => $phone_number,
                    'institute_org'                     => $institute_org,
                    'webinar_title'                     => $webinar_title,
                    'webinar_id'                        => $webinar_id
                );

                session(['webinar_info' => $webinar_info]);

                return view('webinars', with(['country' => $country,'paypal' => $paypal, 'webinar_info' => $webinar_info]));
            }
        }
        return view('webinars');
    }

    public function WebinarPaypalResponse(Request $request)
    {

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

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

        // If the payment is valid and approved
        if ($paymentCheck && $paymentCheck->state == 'approved') {
            // Get the transaction data
            $id = $paymentCheck->id;
            $state = $paymentCheck->state;
            $payerFirstName = $paymentCheck->payer->payer_info->first_name;
            $payerLastName = $paymentCheck->payer->payer_info->last_name;
            $payerName = $payerFirstName.' '.$payerLastName;
            $payerEmail = $paymentCheck->payer->payer_info->email;
            $payerID = $paymentCheck->payer->payer_info->payer_id;
            $payerCountryCode = $paymentCheck->payer->payer_info->country_code;
            $webinar_info['paidAmount'] = $paidAmount = $paymentCheck->transactions[0]->amount->details->subtotal;
            $currency = $paymentCheck->transactions[0]->amount->currency;
            
            //print_r($paymentCheck); die;
            // Get product details
            $productData['price'] = 25;
        
            // If payment price is valid
            if($productData['price'] >= $paidAmount){

                // Paypal Payment Done Successfully
                //$to      = 'nomanakbar@benthamscience.net';
                $to      = 'arshad@xolva.com';
                $cc      = "aisha@benthamscience.net";
                $bcc     = "bentham.eureka@gmail.com";
                $subject = "Webinar: Paypal Payment";
                $from    = $payerEmail;
                $replyto = "marketing@benthamscience.net";

                SendSmtpMail('email_template.webinar', $webinar_info, $to, $from, $subject, $request->name, $cc);

                Session::flash('success', 'Thank you for your payment!');
            }
        }
        Session::flash('error', 'Somthing wrong with this page. Please try again!');
        return Redirect::to('admin/articles');
    }

    public function MemberManuscript(Request $request)
    {
        $param                  = array();
        $awaiting_manuscript    = array();
        $approved_manuscript    = array();
        $rejected_manuscript    = array();
        $archived_manuscript    = array();
        $pending_invoice        = array();
        $paid_invoice           = array();
        $manuscript_data        = array();
        $authors_list           = array();
        $institute_manuscript   = array();
        $society_manuscript     = array();
        $open_access_user       = array();
        $openaccess_article     = array();
        $member_publish_manuscript  = array();
        $pages  = '';
        $total_awaiting_manuscript = '';
        $total_approved_manuscript = '';
        $total_rejected_manuscript = '';
        $total_pending_invoice     = '';
        $total_paid_invoice        = '';
        $total_publish_manuscript  = '';

        $param['institution_associations'] = $institution_associations = Auth()->user()->institution_associations;
        $param['societies_associations'] = $societies_associations = Auth()->user()->societies_associations;
        $param['user_id'] = $user_id = Auth()->user()->id;
        $pages = $request->pages;
		
		if(empty($param['institution_associations']) && empty($param['societies_associations'])){
            return redirect()->back();
        }

        if ($pages == "") {
        if (!empty($param['institution_associations'])) {
                $total_awaiting_manuscript = Manuscript::TotalAwaitingManuscript($param);
                $total_approved_manuscript = Manuscript::TotalApprovedManuscript($param);
                $total_rejected_manuscript = Manuscript::TotalRejectedManuscript($param);
                $total_pending_invoice = Manuscript::TotalManuscriptPendingInvoice($param);
                $total_paid_invoice = Manuscript::TotalManuscriptPaidInvoice($param);
                $total_publish_manuscript = Manuscript::TotalPublishedManuscriptofInstitute($param);
        } else {
                $total_awaiting_manuscript = Manuscript::TotalSocietyAwaitingManuscript($param);
                $total_approved_manuscript = Manuscript::TotalSocietyApprovedManuscript($param);
                $total_rejected_manuscript = Manuscript::TotalSocietyRejectedManuscript($param);
                $total_pending_invoice = Manuscript::TotalSocietyManuscriptPendingInvoice($param);
                $total_paid_invoice = Manuscript::TotalSocietyManuscriptPaidInvoice($param);
                $total_publish_manuscript = Manuscript::TotalPublishedManuscriptofSociety($param);
            }
        }

        if ($pages == "awaiting-manuscript") {

            $param['reference_number']  = $request->get('reference_number');
            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
            $awaiting_manuscript = Manuscript::AwaitingManuscript($param);
            } else {
                $awaiting_manuscript = Manuscript::SocietyAwaitingManuscript($param);
            }

            if ($request->id) {
                $manuscript_id = decrypt($request->id);

                $manuscript_data = Manuscript::GetManuscriptbyID($manuscript_id);
                $param['manuscript_file_id'] = $manuscript_data->manuscript_file_id;

                if (!empty($param['institution_associations'])) {
                    $param['grid_id'] = $grid_id = $this->GetAuthorAffiliationInstitute($manuscript_id, $institution_associations);

                    $param['vip'] = Manuscript::GetVIPInstitutebygridID($grid_id);

                    $authors_list = Manuscript::GetAuthorbyManuscriptID($manuscript_id, $grid_id);
                } else {
                    $param['grid_id'] = $grid_id = $this->GetAuthorSociety($manuscript_id, $societies_associations);

                    $param['vip'] = Manuscript::GetVipSocietybyGridID($grid_id);

                    $authors_list = Manuscript::GetSocietyAuthorbyManuscriptID($manuscript_id, $grid_id);
                }
                if ($param['vip'] != '' && $param['vip']->approval_required == 1) {
                $param['btn_show']  = true;
                }
                $pages = "detail-manuscript";
            }
        }

        if ($pages == "approved-manuscript") {

            $param['reference_number']  = $request->get('reference_number');
            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
            $approved_manuscript = Manuscript::ApprovedManuscript($param);
            } else {
                $approved_manuscript = Manuscript::SocietyApprovedManuscript($param);
            }

            if ($request->id) {
                $manuscript_id = decrypt($request->id);

                $manuscript_data = Manuscript::GetManuscriptbyID($manuscript_id);

                if (!empty($param['institution_associations'])) {
                    $param['grid_id'] = $grid_id = $this->GetAuthorAffiliationInstitute($manuscript_id, $institution_associations);

                    $param['vip'] = Manuscript::GetVIPInstitutebygridID($grid_id);

                    $authors_list = Manuscript::GetAuthorbyManuscriptID($manuscript_id, $grid_id);
                } else {
                    $param['grid_id'] = $grid_id = $this->GetAuthorSociety($manuscript_id, $societies_associations);

                    $param['vip'] = Manuscript::GetVipSocietybyGridID($grid_id);

                    $authors_list = Manuscript::GetSocietyAuthorbyManuscriptID($manuscript_id, $grid_id);
                }
                $pages = "detail-manuscript";
            }
        }

        if ($pages == "rejected-manuscript") {

            $param['reference_number']  = $request->get('reference_number');
            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
            $rejected_manuscript = Manuscript::RejectedManuscript($param);
            } else {
                $rejected_manuscript = Manuscript::SocietyRejectedManuscript($param);
            }

            if ($request->id) {
                $manuscript_id = decrypt($request->id);

                $manuscript_data = Manuscript::GetManuscriptbyID($manuscript_id);

                if (!empty($param['institution_associations'])) {
                    $param['grid_id'] = $grid_id = $this->GetAuthorAffiliationInstitute($manuscript_id, $institution_associations);

                    $param['vip'] = Manuscript::GetVIPInstitutebygridID($grid_id);

                    $authors_list = Manuscript::GetAuthorbyManuscriptID($manuscript_id, $grid_id);
                } else {
                    $param['grid_id'] = $grid_id = $this->GetAuthorSociety($manuscript_id, $societies_associations);

                    $param['vip'] = Manuscript::GetVipSocietybyGridID($grid_id);

                    $authors_list = Manuscript::GetSocietyAuthorbyManuscriptID($manuscript_id, $grid_id);
                }
                $pages = "detail-manuscript";
            }
        }

        if ($pages == "archived-manuscript") {

            $param['reference_number']  = $request->get('reference_number');
            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
                $archived_manuscript = Manuscript::ArchivedManuscript($param);
            } else {
                $archived_manuscript = Manuscript::SocietyArchivedManuscript($param);
            }

            if ($request->id) {
                $manuscript_id = decrypt($request->id);

                $manuscript_data = Manuscript::GetManuscriptbyID($manuscript_id);

                if (!empty($param['institution_associations'])) {
                    $param['grid_id'] = $grid_id = $this->GetAuthorAffiliationInstitute($manuscript_id, $institution_associations);

                    $authors_list = Manuscript::GetAuthorbyManuscriptID($manuscript_id, $grid_id);
                } else {
                    $param['grid_id'] = $grid_id = $this->GetAuthorSociety($manuscript_id, $societies_associations);

                    $authors_list = Manuscript::GetSocietyAuthorbyManuscriptID($manuscript_id, $grid_id);
                }
                $pages = "detail-manuscript";
            }
        }

        if ($pages == "pending-invoice") {

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

            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
                $pending_invoice = Manuscript::GetManuscriptPendingInvoice($param);
            } else {
                $pending_invoice = Manuscript::GetSocietyManuscriptPendingInvoice($param);
            }
        }

        if ($pages == "paid-invoice") {

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

            $param['pagesize']  = 10;

            if (!empty($param['institution_associations'])) {
                $paid_invoice = Manuscript::GetManuscriptPaidInvoice($param);
            } else {
                $paid_invoice = Manuscript::GetSocietyManuscriptPaidInvoice($param);
            }
        }

        if ($pages == "published-articles") {
            if (!empty($param['institution_associations'])) {
                $institution_association = explode(",", $institution_associations);
                $member_publish_manuscript = Manuscript::PublishedManuscriptofEachInstitute($institution_association);
            } else {
                $societies_association = explode(",", $societies_associations);
                $member_publish_manuscript = Manuscript::PublishedManuscriptofEachSociety($societies_association);
            }
        }

        if ($pages == "add-manuscript") {

            $statusId = $request->get('statusId');
            $manuscriptId = $request->get('manuscriptId');

            $manuscript_data = Manuscript::GetManuscriptbyID($manuscriptId);

            if (!empty($param['institution_associations'])) {
            $member_institute = $this->GetAuthorAffiliationInstitute($manuscriptId, $institution_associations);
            $data = array(
                'manuscript_id'                 => $manuscriptId,
                'journal_id'                    => $manuscript_data->journal_id,
                'institution_id'                => $member_institute,
                'eurekaselect_user_id'          => $user_id,
                'manuscript_status'             => $statusId,
                'created_on'                    => time(),
                'ip_address'                    => ip2long($request->ip()),
            );
            } else {
                $member_society = $this->GetAuthorSociety($manuscriptId, $societies_associations);
                $data = array(
                    'manuscript_id'                 => $manuscriptId,
                    'journal_id'                    => $manuscript_data->journal_id,
                    'society_id'                    => $member_society,
                    'eurekaselect_user_id'          => $user_id,
                    'manuscript_status'             => $statusId,
                    'created_on'                    => time(),
                    'ip_address'                    => ip2long($request->ip()),
                );
            }

            $add_manuscript = Manuscript::AddManuscript($data);

            if ($statusId == 1) {
                return redirect('/member/awaiting-manuscript')->with('success', 'Manuscript was approved!');
            } else {
                return redirect('/member/awaiting-manuscript')->with('success', 'Manuscript was rejected!');
            }
        }

        if ($pages == "member-institute-report" || $pages == "member-society-report") {

            $report_id = $request->id;

            if ($pages == "member-institute-report") {
                if ($report_id == 1) {
                    $export_manuscript = Manuscript::AwaitingManuscript($param);
                    $this->generatecsv($export_manuscript, 'submitted_manuscript');
                }
                if ($report_id == 2) {
                    $export_manuscript = Manuscript::ApprovedManuscript($param);
                    $this->generatecsv($export_manuscript, 'accepted_manuscript');
                }
                if ($report_id == 3) {
                    $export_manuscript = Manuscript::RejectedManuscript($param);
                    $this->generatecsv($export_manuscript, 'rejected_manuscript');
                }
                if ($report_id == 4) {
                    $export_manuscript = Manuscript::GetManuscriptPendingInvoice($param);
                    $this->generatecsv($export_manuscript, 'pending_invoices');
                }
                if ($report_id == 5) {
                    $export_manuscript = Manuscript::GetManuscriptPaidInvoice($param);
                    $this->generatecsv($export_manuscript, 'paid_invoices');;
                }
            } else {
                if ($report_id == 1) {
                    $export_manuscript = Manuscript::SocietyAwaitingManuscript($param);
                    $this->generatecsv($export_manuscript, 'submitted_manuscript');
                }
                if ($report_id == 2) {
                    $export_manuscript = Manuscript::SocietyApprovedManuscript($param);
                    $this->generatecsv($export_manuscript, 'accepted_manuscript');
                }
                if ($report_id == 3) {
                    $export_manuscript = Manuscript::SocietyRejectedManuscript($param);
                    $this->generatecsv($export_manuscript, 'rejected_manuscript');
                }
                if ($report_id == 4) {
                    $export_manuscript = Manuscript::GetSocietyManuscriptPendingInvoice($param);
                    $this->generatecsv($export_manuscript, 'pending_invoices');
                }
                if ($report_id == 5) {
                    $export_manuscript = Manuscript::GetSocietyManuscriptPaidInvoice($param);
                    $this->generatecsv($export_manuscript, 'paid_invoices');;
                }
            }
        }

        if ($pages == "manuscript-list") {

            if ($request->id) {
                $param['institute_id'] = $id = decrypt($request->id);
            }

            $param['reference_number'] = "";
            if ($request->get('search')) {

                $param['reference_number']  = $request->get('reference_number');
                $param['institute_id']  = decrypt($request->get('institute_id'));
            }
            $param['pagesize']  = 10;

            $institute_manuscript = Manuscript::PublishedManuscriptbyInstituteID($param);
        }

        if ($pages == "society-manuscript-list") {

			$param['society_id'] = "";
            if ($request->id) {
            $param['society_id'] = $id = decrypt($request->id);
            }

            $param['reference_number'] = "";
            if ($request->get('search')) {
                $param['reference_number']  = $request->get('reference_number');
                $param['society_id']  = decrypt($request->get('society_id'));
            }
            $param['pagesize']  = 10;
            
            $society_manuscript = Manuscript::PublishedManuscriptbySocietyID($param);
        }

        if ($pages == "detail-manuscript") {

            $manuscript_id = decrypt($request->id);

            $manuscript_data = Manuscript::GetManuscriptbyID($manuscript_id);
            $param['article_data'] = Article::GetArticlebyReferenceNumber($manuscript_data->reference_number);

            if (empty($param['article_data'])) {

                $param['jms_journal'] = Manuscript::GetJMSOpenAccessJournal($manuscript_data->journal_id);
            }

            if (!empty($param['institution_associations'])) {
                $param['grid_id'] = $grid_id = $this->GetAuthorAffiliationInstitute($manuscript_id, $institution_associations);

                $authors_list = Manuscript::GetAuthorbyManuscriptID($manuscript_id, $grid_id);
            } else {
                $param['grid_id'] = $grid_id = $this->GetAuthorSociety($manuscript_id, $societies_associations);

                $authors_list = Manuscript::GetSocietyAuthorbyManuscriptID($manuscript_id, $grid_id);
            }
            $pages = "detail-manuscript";
        }
        if ($pages == "open-access") {

            if (!empty($param['institution_associations'])) {
            $institution_association = explode(",", $institution_associations);

            $open_access_user = Manuscript::GetUserbyInstituteID($institution_association);

            if ($request->id) {

                $user_id = decrypt($request->id);

                $user_list = Manuscript::GetUserbyUserID($user_id)[0];

                $param['organization_name']     = $user_list->display_name;
                $cparam['name']                 = $user_list->name;
                $cparam['city']                 = $user_list->city;
                $cparam['country']              = $user_list->country;

                $institute_content = Article::GetInstituteContent($cparam);

                $a = 0;
                $b = 0;
                if ($institute_content->count() > 0) {
                    foreach ($institute_content as $value) {
                        $article = Article::GetConsortiaFreeOpenAccessArticles($value->journal_id, 2, $value->article_id);

                        if (!empty($article)) {
                            $openaccess_article[] = $article;
                            if (count($openaccess_article) > 0) {
                                foreach ($openaccess_article 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;
                                    }
                                }

                                $openaccess_article[$b]->authors = $AuthorNames;
                                $b++;
                            }
                        }
                        $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;
                        }
                        $institute_content[$a]->authors = $AuthorNames;
                        $a++;
                    }
                }
                    $pages = "open-access-list";
            }
            } else {
                $open_access_user = Manuscript::GetUserbyUserID($user_id);

                if ($request->id) {
                    $user_id = decrypt($request->id);
                    $user_detail = Manuscript::GetUserbyUserID($user_id)[0];

                    $param['organization_name']  = $user_detail->display_name;

                    $society_manuscript_list = Manuscript::ManuscriptListofSociety($user_detail->societies_associations);

                    foreach ($society_manuscript_list as $manuscript_list) {
                        $reference_number_list[] = $manuscript_list->reference_number;
                    }

                    if (!empty($reference_number_list)) {
                        $article = Manuscript::GetArticlebyJMSReferenceNumber($reference_number_list);

                        $b = 0;

                        if ($article->count() > 0) {
                            $openaccess_article = $article;
                            if (count($openaccess_article) > 0) {
                                foreach ($openaccess_article 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;
                                    }
									$openaccess_article[$b]->authors = $AuthorNames;
									$b++;
                                }
                            }
                        }
                    }

                    $pages = "open-access-list";
                }
            }
        }

        // $param['user_theme'] = Manuscript::GetUserCustomTheme($user_id);

        if ($pages == "send-email") {

            $email = Auth()->user()->email;

            $email_template = 'email_template.combine_report';
            $view_data['name'] = Auth()->user()->display_name;
            $to = 'azhar@benthamscince.net';
			//$to = 'arshad@xolva.com';
            $from = $email;
			$cc      = 'faizan@benthamscince.net,nouman@benthamscince.net,accessmanager@benthamscience.net';
            $subject = 'Request for Counter Combine Report ('.Auth()->user()->name.')';
            SendSmtpMail($email_template, $view_data, $to, $from, $subject,$cc);
			Session::flash('success', 'Your request for combine report has been sent to concern department!');
            return response()->json(['url'=>url('/home/usageconsortiareport')]);
        }

        // ---------------------------End Member Institution/Societies---------------------------------

        return view('layouts.members', with([
            'pages'                          => $pages,
            'member_publish_manuscript'      => $member_publish_manuscript,
            'total_publish_manuscript'       => $total_publish_manuscript,
            'param'                          => $param,
            'awaiting_manuscript'            => $awaiting_manuscript,
            'total_awaiting_manuscript'      => $total_awaiting_manuscript,
            'approved_manuscript'            => $approved_manuscript,
            'total_approved_manuscript'      => $total_approved_manuscript,
            'rejected_manuscript'            => $rejected_manuscript,
            'total_rejected_manuscript'      => $total_rejected_manuscript,
            'pending_invoice'                => $pending_invoice,
            'total_pending_invoice'          => $total_pending_invoice,
            'paid_invoice'                   => $paid_invoice,
            'total_paid_invoice'             => $total_paid_invoice,
            'manuscript_data'                => $manuscript_data,
            'authors_list'                   => $authors_list,
            'institute_manuscript'           => $institute_manuscript,
            'society_manuscript'             => $society_manuscript,
            'open_access_user'               => $open_access_user,
            'openaccess_article'             => $openaccess_article,
            'archived_manuscript'            => $archived_manuscript,
        ]));
    }

    public function GetAuthorAffiliationInstitute($manuscriptId, $institution_associations)
    {
        $authors_data = Manuscript::GetAuthorsAffiliationbyMSID($manuscriptId);
        $member_institute = "";
        foreach ($authors_data as $authors) {
            $institution = explode(",", $institution_associations);
            if (in_array($authors->institution_id, $institution)) {
                $member_institute = $authors->institution_id;
            }
        }
        return $member_institute;
    }

    public function GetAuthorSociety($manuscriptId, $societies_associations)
    {
        $society_list = Manuscript::GetSocietiesbyManuscriptID($manuscriptId);
        $member_society = "";
        foreach ($society_list as $society) {
            $societies = explode(",", $societies_associations);
            if (in_array($society->grid_id, $societies)) {
                $member_society = $society->grid_id;
            }
        }
        return $member_society;
    }

    public function generatecsv($export_manuscript, $report)
    {
        if ($report == 'submitted_manuscript' || $report == 'accepted_manuscript' || $report == 'rejected_manuscript') {
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=$report.csv");

            $r = 'Manuscript Title,Reference Number,Submitted Date,Article Type,Institute/Society Name,Principal Author,Email Address,Affiliation';
            $r .= "\n";

            foreach ($export_manuscript as $vals) {
                $r .= '"' . $vals->title . '",';
                $r .= '"' . $vals->reference_number . '",';
                $r .= '"' . gmdate("d-m-Y", $vals->date_submitted) . '",';
                $r .= '"' . $vals->article_type_name . '",';
                $r .= '"' . $vals->name . '",';
                foreach (explode('_', $vals->PrincipalAuthor) as $PrincipalAuthors) {
                    $r .= '"' . $PrincipalAuthors . '",';
                }
                $r .= "\n";
            }
        } elseif ($report == 'pending_invoices' || $report == 'paid_invoices') {
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=$report.csv");

            $r = 'Manuscript Title,Reference Number,Submitted Date,Article Type,Institute/Society Name,Principal Author,Email Address,Affiliation,Invoice Number,Invoice Date,Total Amount,Status';
            $r .= "\n";

            foreach ($export_manuscript as $vals) {
                $r .= '"' . $vals->title . '",';
                $r .= '"' . $vals->reference_number . '",';
                $r .= '"' . gmdate("d-m-Y", $vals->date_submitted) . '",';
                $r .= '"' . $vals->article_type_name . '",';
                $r .= '"' . $vals->name . '",';
                foreach (explode('_', $vals->PrincipalAuthor) as $PrincipalAuthors) {
                    $r .= '"' . $PrincipalAuthors . '",';
                }
                $r .= '"' . $vals->invoice_number . '",';
                $r .= '"' . gmdate("d-m-Y", $vals->invoice_date) . '",';
                $r .= '"$' . $vals->total_amount . '",';
                $r .= '"' . $vals->transaction_status . '",';
                $r .= "\n";
            }
        }
        echo $r;
        die;
    }

    public function readandpublish(Request $request)
    {
        $currentURL = $_SERVER['REQUEST_URI'];

        $data = [];
        $data = array(
            'title'                => $request->title,
            'fname'                => $request->fname,
            'email'                => $request->email,
            'institute_name'       => $request->institute_name,
            'head_of_institution'  => $request->head_of_institution,
            'email_of_institution' => $request->email_of_institution,
            'city'                 => $request->city,
            'country'              => $request->country,
            'comment'              => $request->comment,
            'checkbox'             => $request->checkbox,
        );

        if ($request->title || $request->fname || $request->email || $request->institute_name || $request->head_of_institution || $request->email_of_institution || $request->city || $request->country || $request->comment || $request->checkbox) {
			$to   = 'julykim@benthamscience.net';
            $from = 'support@benthamscience.net';
            $cc   = 'faizan@benthamscience.net,beena@benthamscience.net';
            $bcc  = 0; 

            $subject = "Read and Publish Request";

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

            return back()->with('success', 'Your form has been successfully submitted');
        }

        if ($currentURL == '/read-and-publish') {
            return view('includes.read_and_publish');
        } elseif ($currentURL == '/Elsevier-collaboration') {
            return view('includes.elsevier_collaboration');
        }
    }
}
