<?php

namespace App\Http\Controllers;

use App\Http\Controllers\MigsController;
use App\Models\Article;
use App\Models\Author;
use App\Models\ContentAccess;
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\UserAccess\UserAccess;
use App\Models\UserAccess\UserAccessIpRange;
use App\Models\UserAccess\UserAccessOrganization;
use App\Models\UserAccess\UserAccessRequest;
use App\Models\Volume;
use App\Models\Indexing;
use App\Rules\Captcha;
use App\User;
use Auth;
use DB;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;

class IssueController extends BenthamController
{

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

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

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

        if ($frm_search != null && $frm_search == true) {

            $issue_list      = Issue::GetIssue($param);
            $p['journal_id'] = $journal_id;
            $volume_search   = Volume::GetVolumeTitleById($p);

        }

        if ($ajx_search != null && $ajx_search == true) {
            if (!empty($journal_id)) {
                $p['journal_id'] = $journal_id;
                $volume_search   = Volume::GetVolumeTitleById($p);
                return response()->json(array('volume_search' => $volume_search), 200);
            }

        }

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

            $issue_list = Issue::GetIssue();
        }

        $journal_search = Journal::GetJournalTitle();
        // $year_search = Journal::GetYear();

        if (checkPermission('issue', 'edit')) {
            $editPermission = true;
        }if (checkPermission('issue', 'delete')) {
            $deletePermission = true;
        }

        return View::make('admin.issue.issue', with(['issue_list' => $issue_list,
            'journal_search'                                          => $journal_search,
            'volume_search'                                           => $volume_search,
            'param'                                                   => $param,
            'editPermission'                                          => $editPermission,
            'deletePermission'                                        => $deletePermission]));
    }

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id, Request $request)
    {

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

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

        }

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

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

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

        }
        $volume_search = '';
        $journal       = Journal::GetJournalTitle();
        return View::make('admin.issue.addissue')->with(['journal' => $journal, 'volume_search' => $volume_search]);

    }

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

        $validator = Validator::make($request->all(), [
            'journal_id'       => 'required',
            'volume_id'        => 'required',
            'type'             => 'required',
            'month_id'         => 'required',
            'title'            => 'required',
            'title'            => 'required',
            'publication_date' => 'required',
            'title'            => 'numeric',
            'publication_date' => 'required',
            'is_uploaded'      => 'required',
        ]);

        $validator->after(function ($validator) use ($request) {

            $p['journal_id'] = $request->get("journal_id");
            $p['volume_id']  = $request->get("volume_id");
            $p['title']      = $request->get("title");
            $issue_exist     = Issue::GetIssueById($p);

            if (!empty($issue_exist[0])) {
                $validator->errors()->add('title', 'Issue name already exist');
            }

        });

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

            return back()->with(['volume_search' => $volume_search])->withInput()->withErrors($validator);
        } else {
            $this->insertIssue($request);
            return Redirect::to('admin/issue');
        }
    }

    public function update(Request $request, $issue_id)
    {

        $validator = Validator::make($request->all(), [
            'journal_id'       => 'required',
            'volume_id'        => 'required',
            'type'             => 'required',
            'month_id'         => 'required',
            'title'            => 'required',
            'title'            => 'required',
            'publication_date' => 'required',
            'title'            => 'numeric',
            'publication_date' => 'required',

            'is_uploaded'      => 'required',
        ]);

        $validator->after(function ($validator) use ($issue_id, $request) {

            $p['journal_id'] = $request->get("journal_id");
            $p['volume_id']  = $request->get("volume_id");
            $p['issue_id']   = $issue_id;
            $p['title']      = $request->get("title");

            $issue_exist = Issue::CheckIssueExist($p);

            if (!empty($issue_exist)) {
                $validator->errors()->add('title', 'Issue name already exist');
            }

        });

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

            return back()->with(['volume_search' => $volume_search])->withInput()->withErrors($validator);
        } else {

            $this->updateIssue($request, $issue_id);
            return Redirect::to('admin/issue');
        }

    }

    public function destroy(Request $request, $issue_id)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

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

            if (empty($article)) {
                $issue = Issue::where('issue_id', $issue_id)->first();

                $delete_issue['issue_id']         = $issue->issue_id;
                $delete_issue['nid']              = $issue->nid;
                $delete_issue['journal_id']       = $issue->journal_id;
                $delete_issue['month_id']         = $issue->month_id;
                $delete_issue['volume_id']        = $issue->volume_id;
                $delete_issue['title']            = $issue->title;
                $delete_issue['type']             = $issue->type;
                $delete_issue['issue_title']      = $issue->issue_title;
                $delete_issue['about_issue']      = $issue->about_issue;
                $delete_issue['price']            = $issue->price;
                $delete_issue['is_uploaded']      = $issue->is_uploaded;
                $delete_issue['is_new']           = $issue->is_new;
                $delete_issue['publication_date'] = $issue->publication_date;
                $delete_issue['old_jour_id']      = $issue->old_jour_id;
                $delete_issue['old_vol_id']       = $issue->old_vol_id;
                $delete_issue['old_issue_id']     = $issue->old_issue_id;
                $delete_issue['old_issue']        = $issue->old_issue;
                $delete_issue['created']          = $issue->created;
                $delete_issue['created_by']       = $issue->created_by;
                $delete_issue['updated_by']       = $issue->updated_by;

                $node                     = Node::where('nid', $issue->nid)->first();
                $delete_node['nid']       = $node->nid;
                $delete_node['type']      = $node->type;
                $delete_node['language']  = $node->language;
                $delete_node['title']     = $node->title;
                $delete_node['uid']       = $node->uid;
                $delete_node['status']    = $node->status;
                $delete_node['created']   = $node->created;
                $delete_node['changed']   = $node->changed;
                $delete_node['comment']   = $node->comment;
                $delete_node['promote']   = $node->promote;
                $delete_node['moderate']  = $node->moderate;
                $delete_node['sticky']    = $node->sticky;
                $delete_node['tnid']      = $node->tnid;
                $delete_node['translate'] = $node->translate;

                $node_meta                         = Meta::where('nid', $issue->nid)->first();				
                $delete_node_meta['node_meta_id']  = $node_meta->node_meta_id;
                $delete_node_meta['nid']           = $node_meta->nid;
                $delete_node_meta['title']         = $node_meta->title;
                $delete_node_meta['abstract']      = $node_meta->abstract;
                $delete_node_meta['canonical_url'] = $node_meta->canonical_url;
                $delete_node_meta['copyright']     = $node_meta->copyright;
                $delete_node_meta['description']   = $node_meta->description;
                $delete_node_meta['keywords']      = $node_meta->keywords;

                //-----------------------------Delete into log table-----------------------------------

                $log_node['node']      = $delete_node;
                $log_issue['issue']    = $delete_issue;
                $log_meta['node_meta'] = $delete_node_meta;

                $log     = array_merge($log_node, $log_issue, $log_meta);
                $user    = Auth::user();
                $add_log = array(
                    'content_id'      => $issue['issue_id'],
                    'content_type_id' => config('constants.log_content_types.Issue'),
                    'action'          => config('constants.log_action_types.delete'),
                    'log_data'        => json_encode($log),
                    'created_dated'   => time(),
                    'created_by'      => $user->id,
                    'ip'              => ip2long($request->ip()),
                );

                $log = Log::AddLog($add_log);
                Issue::where('issue_id', $issue_id)->delete();
                Node::where('nid', $issue->nid)->delete();
                Meta::where('nid', $issue->nid)->delete();
                //-------------------------------------------------------------------------------------
            } else {
                return back()->with(['delete_msg' => 'Article(s) exist in this Issue']);
            }

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

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

    public function edit(Request $request, $id)
    {

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

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

        }

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

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

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

        }

        //$issue  = Issue::GetIssueTitleById($id);
        $p['issue_id'] = $id;
        $issue         = Issue::GetIssueById($p);
        $issue         = $issue[0];

        $param_j['journal_id'] = $journal_id;
        $issue_type            = Issue::GetIssueTitleById($param_j);
        //$volume = Volume::GetVolumeByJournalId($issue->journal_id);
        // $journal = Journal::GetJournalTitle();
        $selected_meta = Meta::NodeMeta($issue->nid);

        for ($i = 2000; $i <= 2019; $i++) {
            $year[$i] = $i;
        }

        $param['journal_id'] = $issue->journal_id;
        $journal             = Journal::GetJournalTitle($param);

        $param['volume_id'] = $issue->volume_id;
        $volume_search      = Volume::GetVolumeTitleById($param);

        return View::make('admin.issue.addissue', with(['issue' => $issue,
            'issue_type'                                            => $issue_type,
            'journal'                                               => $journal,
            'volume_search'                                         => $volume_search,
            'year'                                                  => $year,
            'selected_meta'                                         => $selected_meta]));
    }

    public function updateIssue($request, $issue_id)
    {
        try {
// try transaction start here for data integrity

            DB::beginTransaction();

            $issue = Issue::where('issue_id', $issue_id)->get();
            $issue = $issue[0];

            $user                             = Auth::user();
            $update_issue['month_id']         = $request->get("month_id");
            $update_issue['title']            = $request->get("title");
            $update_issue['type']             = $request->get("type");
            $update_issue['issue_title']      = $request->get("issue_title");
            $update_issue['about_issue']      = $request->get("about_issue");
            $update_issue['price']            = $request->get("price");
            $update_issue['is_uploaded']      = $request->get("is_uploaded");
            $update_issue['publication_date'] = strtotime($request->get("publication_date"));
            $update_issue['updated_by']       = $user->id;
            Issue::where('issue_id', $issue_id)->update($update_issue);
            $update_issue['issue_id'] = $issue_id;
            $update_issue['nid']      = $issue->nid;

            //-------------------Update into Meta table---------------

            Meta::where('nid', $issue->nid)->delete();
            $add_node_meta['nid']           = $issue->nid;
            $add_node_meta['abstract']      = $request->get('meta_abstract');
            $add_node_meta['canonical_url'] = $request->get('meta_canonical_url');
            $add_node_meta['copyright']     = $request->get('meta_copyright');
            $add_node_meta['description']   = $request->get('meta_description');
            $add_node_meta['keywords']      = $request->get('meta_keywords');
            $add_node_meta['node_meta_id']  = Meta::insertGetId($add_node_meta);

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

            $log_volume['issue'] = $update_issue;
            $log_meta['meta']    = $add_node_meta;

            $log     = array_merge($log_volume, $log_meta);
            $add_log = array(
                'content_id'      => $issue_id,
                'content_type_id' => config('constants.log_content_types.Issue'),
                'action'          => config('constants.log_action_types.update'),
                'log_data'        => json_encode($log),
                '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 Redirect::to('admin/issue');
        }

    }

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

            DB::beginTransaction();
            $journal_id = $request->get('journal_id');

            //-------------------Insert into Node table---------------
            $add_node['type']    = 'issue';
            $add_node['title']   = $request->get('title');
            $add_node['created'] = time();
            $add_node['nid']     = Node::insertGetId($add_node);

            //-------------------Insert into Issue table---------------
            $user                     = Auth::user();
            $add_issue['nid']         = $add_node['nid'];
            $add_issue['journal_id']  = $request->get('journal_id');
            $add_issue['month_id']    = $request->get('month_id');
            $add_issue['volume_id']   = $request->get('volume_id');
            $add_issue['title']       = $request->get('title');
            $add_issue['type']        = $request->get('type');
            $add_issue['issue_title'] = $request->get('issue_title');
            $add_issue['about_issue'] = $request->get('about_issue');
            $add_issue['price']       = $request->get('price');
            $add_issue['is_uploaded'] = $request->get('is_uploaded');
            $add_issue['created']     = time();
            $add_issue['created_by']  = $user->id;
            $add_issue['updated_by']  = $user->id;
            $add_issue['issue_id']    = Issue::insertGetId($add_issue);

            //-------------------Insert into Meta table---------------
            $add_node_meta['nid']           = $add_node['nid'];
            $add_node_meta['abstract']      = $request->get('meta_abstract');
            $add_node_meta['canonical_url'] = $request->get('meta_canonical_url');
            $add_node_meta['copyright']     = $request->get('meta_copyright');
            $add_node_meta['description']   = $request->get('meta_description');
            $add_node_meta['keywords']      = $request->get('meta_keywords');
            $add_node_meta['node_meta_id']  = Meta::insertGetId($add_node_meta);

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

            $log_node['node']      = $add_node;
            $log_volume['issue']   = $add_issue;
            $log_meta['node_meta'] = $add_node_meta;

            $log     = array_merge($log_node, $log_volume, $log_meta);
            $add_log = array(
                'content_id'      => $add_issue['issue_id'],
                'content_type_id' => config('constants.log_content_types.Issue'),
                'action'          => config('constants.log_action_types.insert'),
                'log_data'        => json_encode($log),
                '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 Redirect::to('admin/issue');
        }
        // redirect
        Session::flash('message', 'Successfully created issue!');
        return Redirect::to('admin/issue');
    }

    public function PurchaseFullIssue(Request $request, $issue_id)
    {

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

            if ($validator->fails()) {
                return $this->PurchaseFullIssueForm($request, $issue_id, $validator);
            } else {
                return $this->PurchaseFullIssuePreview($request, $issue_id);
            }
        } elseif (isset($request->issue_purchase_form) && $request->issue_purchase_form == 'Submit') {
            return $this->PurchaseFullIssueSubmit($request, $issue_id);
        } else {
            return $this->PurchaseFullIssueForm($request, $issue_id);
        }
    }

    public function PurchaseFullIssueForm($request, $issue_id, $validator = null)
    {
        $issue   = Issue::where('issue_id', $issue_id)->first();
        $volume  = Volume::where('volume_id', $issue->volume_id)->join('year', 'year.id', '=', 'volume.year_id')->first();
        $journal = Journal::where('journal_id', $issue->journal_id)->first();

        if ($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['email']      = isset($session_detail['email']) ? $session_detail['email'] : '';

        } else {
            $detail['first_name'] = '';
            $detail['last_name']  = '';
            $detail['email']      = '';
        }

        $page_name = 'purchase_issue_form';

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

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

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

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

    }

    public function PurchaseFullIssuePreview(Request $request, $issue_id)
    {

        $detail  = array();
        $message = '';
        if ($request->session()->has('session_detail')) {
            $session_detail       = $request->session()->get('session_detail');
            $detail['first_name'] = isset($request->first_name) ? $request->first_name : $session_detail['first_name'];
            $detail['last_name']  = isset($request->last_name) ? $request->last_name : $session_detail['last_name'];
            $detail['email']      = isset($request->email) ? $request->email : $session_detail['email'];
        } else {
            $detail['first_name'] = isset($request->first_name) ? $request->first_name : '';
            $detail['last_name']  = isset($request->last_name) ? $request->last_name : '';
            $detail['email']      = isset($request->email) ? $request->email : '';
        }

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

        $issue   = Issue::where('issue_id', $issue_id)->first();
        $volume  = Volume::where('volume_id', $issue->volume_id)->join('year', 'year.id', '=', 'volume.year_id')->first();
        $journal = Journal::where('journal_id', $issue->journal_id)->first();

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

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

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

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

    }

    public function PurchaseFullIssueSubmit(Request $request, $issue_id)
    {
        //$access_user_data  = $request->session()->get('access_user_data');

        $username = '';
        if ($user = Auth::user()) {
            $user_id = $user->id;
            //$user = User::with('role')->find($user_id);
            $username = $user->name;
        }

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

        $remote_ip = ip2long($request->ip());
        $firstname = $request->first_name;
        $lastname  = $request->last_name;
        $email     = $request->email;

        $journal_name = $journal->title;
        $sell_price   = $issue->price;
        $volume       = $volume->volume_name;
        $issue_title  = $issue->title;
        //$year= $row->year_name;

        //-------------------Insert into Issue Inquiry Order Table---------------
        $add_details['nid']          = $issue->nid;
        $add_details['first_name']   = $firstname;
        $add_details['last_name']    = $lastname;
        $add_details['email']        = $email;
        $add_details['remote_ip']    = $remote_ip;
        $add_details['guest']        = $username;
        $add_details['amount']       = $sell_price;
        $add_details['created_on']   = now();
        $add_details['last_updated'] = now();
        $add_details['status']       = 'P';

        $inquiry_id = Issue::AddContactDetails($add_details);

        $inquiry_order = Issue::GetInquiryOrder($inquiry_id);
        $inquiry_order = $inquiry_order[0];

        $issue = Issue::where('nid', $inquiry_order->nid)->first();

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

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

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


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

    }


    public function PurchaseIssueMigsResponse(Request $request)
    {
        $inquiry_id = substr($request->inquiry_id, 5, strlen($request->inquiry_id));

        $inquiry_order = Issue::GetInquiryOrder($inquiry_id);

        $inquiry_order = $inquiry_order[0];

        $issue   = Issue::where('nid', $inquiry_order->nid)->first();
        $volume  = Volume::where('volume_id', $issue->volume_id)->join('year', 'year.id', '=', 'volume.year_id')->first();
        $journal = Journal::where('journal_id', $issue->journal_id)->first();

        $detail['inquiry_id']    = $inquiry_order->inquiry_id;
        $detail['journal_title'] = $journal->title;
        $detail['volume_name']   = $volume->volume_name;
        $detail['volume_year']   = $volume->year;
        $detail['issue_title']   = $issue->title;
        $detail['issue_price']   = $issue->price;
        $detail['first_name']    = $inquiry_order->first_name;
        $detail['last_name']     = $inquiry_order->last_name;
        $detail['email']         = $inquiry_order->email;


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

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


            $res = $this->CreateNewUserAndAccess($inquiry_order);

            if (isset($res['user_details']['password_text'])) {
                $detail['username']   = $res['user_details']['email'];
                $detail['password']   = $res['user_details']['password_text'];
                $detail['issue_link'] = url("/issue/" . $issue->issue_id);
            }

            $message = 'The transaction Successfully Done';
            $to      = $inquiry_order->email;
            $from    = env('email_admin', '');
            $cc      = env('email_admin');
            $bcc     = env('email_xolva_2') . ',' . env('email_support_2');
            $subject = "Issue Inquiry number # " . $inquiry_id . " (" . $message . ")";

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

                    }
            }
			}
        } 
        else
        {     
            $status  = "X";
            $message = 'The transaction Cancelled';
        }

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

        $inquiry_id = Issue::UpdatePurchaseIssueInquiryOrder($inquiry_id, $update_inquiry);

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

        $page_name = 'purchase_issue_form_preview';

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

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

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

    //---------------------------for journal home page----------------------------//

    public function GetIssueDetails(Request $request, $id, $type = "")
    {

        $issue_type = "";
        $view_issue = 1;
        $art_type_array = array("Editorial", "Preface", "Acknowledgement","Biography","Corrigendum","Erratum","Obituary","Retraction Notice","Withdrawal Notice");
        if ($type == 1) {
            $issue_type = "Current Issue";
            $view_issue = 0;
        }

        $param['issue_id']   = $issue_id   = $id;
        $issue               = Issue::GetIssueTitleById($param);
        $issue               = $issue[0];
        $journal             = Journal::GetJournalById($issue->journal_id);
        $param2['volume_id'] = $issue->volume_id;
        $volume              = Volume::GetVolumeById($param2)->toArray();
        $volume              = $volume[0];
        $volume_data         = Volume::GetVolumeDetail($param2);
        $count_epub_article = Article::GetTrackList($issue->journal_id, 1, 0)->count();
        $count_epub_abstract = Article::GetTrackList($issue->journal_id, 4, 0)->count();
        $main_indexing       = Indexing::GetMainJournalIndexing($issue->journal_id);

        $article_list = Article::getAllArticlesByIssueID($issue->issue_id, 20);
        foreach ($article_list as $key => $article) {
            $article_list[$key]->user_access_id = 0;
        }

        $a                           = 0;
        $DownloadAccess              = false;
        $article_before_level        = false;
        $download_access_data        = '';
        $checkIfMarked               = false;
        $sparam                      = array();
        $terms_popup                 = true;
        $restricted_user_access_key  = '';
        $restricted_user_access_type = '';
        $bundle_content              = "";
        $user_access_id              = 0;
        $continues_publication_journal = array();

        if (!empty($article_list[0])) {
            $journal_id  = $article_list[0]->journal_id;
            $volume_id   = $article_list[0]->volume_id;
            $volume_name = $article_list[0]->volume_name;
            $issue_id    = $article_list[0]->issue_id;
            $article_id  = $article_list[0]->article_id;

            //----------------Content Access--------------

            //Check free or open access on volume
            $journal_lvl_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $volume_id, "v");
            $journal_lvl_access = isset($journal_lvl_access[0]->access_type) ? $journal_lvl_access[0]->access_type : false;
            if ($journal_lvl_access) {
                $DownloadAccess = $journal_lvl_access;
            }

            //Check free or open access on issue
            $issue_lvl_access = ContentAccess::CheckOpenFreeAcccessWithType("journal_access", $issue_id, "i");
            $issue_lvl_access = isset($issue_lvl_access[0]->access_type) ? $issue_lvl_access[0]->access_type : false;
            if ($issue_lvl_access) {
                $DownloadAccess = $issue_lvl_access;
            }

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

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

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

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

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

            }

            //Check free or open access on article
            //---------------------------------------------------
            foreach ($article_list as $k => $v) {
                $article_ids[] = $v->article_id;
            }
           $article_lvl_access = ContentAccess::GetContentAccessById(array('article_ids' => $article_ids, 'condition' => true));

            foreach ($article_list as $key => $article) {
                $oa_articles[$key] = $article_list[$key];

                $oa_articles[$key]->open_access                 = false;
                $oa_articles[$key]->download_access             = false;
                $oa_articles[$key]->content_download_type       = '';
                $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 = '';
                $oa_articles[$key]->view_option           = 0;

                if (!empty($journal_lvl_access)) {
                    $open_access_before = $journal_lvl_access;
                } elseif (!empty($issue_lvl_access)) {
                    $open_access_before = $issue_lvl_access;
                }

                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 == 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      = "";
                        }
                        //$oa_articles[$key]->access_base_text = 'promotion: free to download';
                    } elseif ($open_access_before == 2) {
                        $oa_articles[$key]->terms_popup           = false;
                        $oa_articles[$key]->content_download_type = 'FO';
                        $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      = "";
                                }
                                //$oa_articles[$key]->access_base_text = 'promotion: free to download';
                            } 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';
                            }

                        }
                    }
                }
            }

            //-------------------------------------------------------------------

            // 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) {

                $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 = '';

                    if (!empty($ua_volume_lvl[0])) // check User Access Volume level
                    {
                        $user_access_before = $ua_volume_lvl[0];
                    } elseif (!empty($ua_issue_lvl[0])) // check User Access Issue level
                    {
                        $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($type) && $type=='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 ($article_list as $alk => $alv) {
                unset($article_list[$alk]);

                if (!empty($ua_article_list[$alk])) {
                    $article_list[$alk] = $ua_article_list[$alk];
                }
            }

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

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

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

                    if (!$DownloadAccess) {
                        $article_list[$key]->user_access_id = 0;
                    }

                }
                $article_list[$key]->checkIfMarked = $checkIfMarked;
                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $article_list[$key]->terms_popup = false;
                /*----------------------------------------------------------------------*/
                $AuthorNames     = '';
                $article_authors = Author::GetAuthorsByContentId($article->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[$a]->authors          = $AuthorNames;
                $article_list->items()[$a]->authors = $AuthorNames;
                $a++;
            }

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

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

        //--------------User Bundle Access Check-----------------------
        if (session()->has('user_id')) {
            $bundle_content = BundleOfferController::BundleOfferUserAccess(session()->get('user_id'));
        }
        return view('journal_menu', with(['journal' => $journal,
            'volume_data'                               => $volume_data,
            'latest_issue'                              => $latest_issue,
            'issue'                                     => $issue,
            'issue_type'                                => $issue_type,
            'volume'                                    => $volume,
            'article_list'                              => $article_list,
            'page_name'                                 => $page_name,
            'view_issue'                                => $view_issue,
            'issue_id'                                  => $issue_id,
            'DownloadAccess'                            => $DownloadAccess,
            'node_meta'                                 => $node_meta,
            'bundle_content'                            => $bundle_content,
            'user_access_id'                            => $user_access_id,
            'count_epub_article'                        => $count_epub_article, 
            'count_epub_abstract'                       => $count_epub_abstract,
            'continues_publication_journal'             => $continues_publication_journal,
            'current_year_issue'                        => $current_year_issue,
            'main_indexing'                             => $main_indexing
        ]));
    }

    public function CreateNewUserAndAccess($inquiry_order)
    {
        $issue_nid = $inquiry_order->nid;

        try
        {
// try transaction start here for data integrity

            DB::beginTransaction();

            //if Doesnot exist create new User
            $user_details = (array) $this->add_user_details($inquiry_order);
            $user_id      = $user_details['id'];

            if (!empty($user_id)) {
                // if organization does not exist enter record
                $organization  = $this->add_organization();
                $access_org_id = $organization['access_organization_id'];
            }

            if (!empty($access_org_id)) {
                // if access does no exist enter record
                $user_access = $this->add_user_access($user_id, $access_org_id, $issue_nid);
            }

            DB::commit();

            $res['user_details'] = $user_details;
            $res['organization'] = $organization;
            $res['user_access']  = $user_access;

            return $res;

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

    public function add_organization()
    {
        $param['organization_name'] = 'Bentham Science Publisher';
        $organization               = UserAccessOrganization::where('organization_name', 'Bentham Science Publisher')->first();

        if (empty($organization)) {
            $organization['organization_name']      = 'Bentham Science Publisher';
            $organization['organization_website']   = '';
            $organization['country_id']             = '';
            $organization['organization_status']    = 'A';
            $organization['system_ip']              = null;
            $organization['created_on']             = time();
            $organization['created_by']             = 1;
            $organization['updated_ip']             = null;
            $organization['updated_by']             = 1;
            $organization['updated_on']             = time();
            $organization['access_organization_id'] = $access_org_id = UserAccessOrganization::AddAccessOrganization($organization);
        }

        return $organization;
    }

    public function add_user_details($inquiry_order)
    {
        $user_details = User::GetUserByField('email', $inquiry_order->email);
        //dd($user_details);
        if (empty($user_details)) {
            $pass = Str::random(10);

            $user_details['name']         = $inquiry_order->email;
            $user_details['display_name'] = $inquiry_order->first_name;
            $user_details['email']        = $inquiry_order->email;
            $user_details['password']     = Hash::make($pass);

            $user_details['status']                 = 1;
            $user_details['first_name']             = $inquiry_order->first_name;
            $user_details['last_name']              = $inquiry_order->last_name;
            $user_details['created_at']             = time();
            $user_details['updated_at']             = time();
            $user_details['org_name']               = '';
            $user_details['org_branch']             = '';
            $user_details['user_type']              = 'user';
            $user_details['access_organization_id'] = '';
            $user_details['id']                     = User::insertGetId($user_details);

            $user_details['password_text'] = $pass;
        }

        return $user_details;
    }

    public function add_user_access($user_id, $access_org_id, $issue_nid)
    {
        $param['user_id'] = $user_id;
        $user_access      = UserAccess::GetUserAccess($param);

        if (empty($user_access)) {
            $user_access['access_org_id']    = $access_org_id;
            $user_access['user_id']          = $user_id;
            $user_access['access_type_id']   = 333; // Corporate Access
            $user_access['access_type_on']   = 'issue';
            $user_access['access_base_type'] = 0; // user base
            $user_access['view_option'] = 0; // view_option

            // 1 Year Corporate Access
            $user_access['access_date_from'] = time();
            $user_access['access_date_to']   = strtotime(date('Y-m-d', strtotime('+1 years')));

            $user_access['remarks']            = 'System Generated Access';
            $user_access['content_data']       = 1;
            $user_access['user_access_status'] = 1;
            $user_access['system_ip']          = null;
            $user_access['system_user_id']     = 1;
            $user_access['system_time']        = time();
            $user_access['created_on']         = time();
            $user_access['created_by']         = 1;
            $user_access['user_access_id']     = UserAccessIpRange::insertAccessOnUser($user_access);

        }

        $user_access = (object) $user_access;

        if (!empty($user_access)) {
            $access_request = (array) UserAccessRequest::GetAccessRequestByField('organization_name', 'Bentham Science Publisher');
            if (empty($access_request)) {
                $access_request['access_type']          = 'Corporate';
                $access_request['client_name']          = 'xolva';
                $access_request['organization_name']    = 'Bentham Science Publisher';
                $access_request['organization_type']    = 'Normal';
                $access_request['contact_address']      = 'ITS';
                $access_request['contact_person_email'] = 'admin@eurekselect.com';
                $access_request['comments']             = 'System Generated Access';
                $access_request['request_status']       = 'C';
                $access_request['user_access_id']       = $user_access->user_access_id;
                $access_request['system_ip']            = null;
                $access_request['created_on']           = time();
                $access_request['created_by']           = 1;
                $access_request['updated_ip']           = null;
                $access_request['updated_on']           = time();
                $access_request['updated_by']           = 1;
                $access_request['request_id']           = UserAccessRequest::AddAccessRequest($access_request);
            }

            //Add User Access Request
            $uc_req['request_id']     = $access_request['request_id'];
            $uc_req['user_access_id'] = $user_access->user_access_id;
            $uc_req['action']         = '"C"';
            $uc_req['sys_user_id']    = 1;
            $uc_req['sys_time']       = time();
            $uc_req['sys_ip']         = 'null';

            UserAccess::AddUserAccessWithRequest($uc_req);

        }

        if (!empty($user_access)) {
            $issue                   = issue::where('nid', $issue_nid)->first();
            $param['issue_id']       = $issue->issue_id;
            $param['user_access_id'] = $user_access->user_access_id;
            $param['access_type_id'] = 333; // Corporate Access
            $param['access_on']      = 'issue';
            $content_access          = UserAccess::GetUserAccessOnContent($param);

            if (!empty($content_access[0])) {
                $content_ids = array($content_access[0]->uc_id);
                //Delete User Access on Content
                $p['sys_h_user_id']  = 1;
                $p['sys_h_time']     = time();
                $p['sys_h_ip']       = 'null';
                $p['access_type_id'] = 333;
                $p['access_on']      = 'issue';
                UserAccess::DeleteUserAccessOnContent($content_ids, $p);
            }

            $uc_insert['user_access_id'] = $user_access->user_access_id;
            $uc_insert['journal_id']     = $issue->journal_id;
            $uc_insert['volume_id']      = $issue->volume_id;
            $uc_insert['issue_id']       = $issue->issue_id;
            $uc_insert['user_id']        = $user_id;
            $uc_insert['from_date']      = time();
            $uc_insert['to_date']        = strtotime(date('Y-m-d', strtotime('+1 years')));
            $uc_insert['perpetual']      = 0;
            $uc_insert['type']           = 333;
            $uc_insert['sys_time']       = time();
            $uc_insert['sys_user_id']    = 1;
            $uc_insert['sys_ip']         = null;

            $user_access_insert[] = $uc_insert;

            UserAccess::InsertUserAccessOnContent($user_access_insert, $user_access, $param);

        }

        return $user_access;
    }

    public function CheckUserAccessVolumeLevel($journal_id, $volume_id, $issue_id, $articles)
    {

        $oa_issues = array();

        $param['volume_id']  = $volume_id;
        $param['volume_id']  = $volume_id;
        $param['user_id']    = session()->get('user_id');
        $param['ip_address'] = $request->ip();

        $uci = UserAccess::GetAllContentUserAccess($param);

        foreach ($articles as $key => $article) {
            $oa_issue[$key]              = $articles[$key];
            $oa_issue[$key]->user_access = false;

            if ($article->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 == $article->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($type) && $type=='subscribe'){
            if (session()->has('mysubscribption')) {
                if ($oa_issue[$key]->user_access == true) {
                    $oa_issues[] = $oa_issue[$key];
                }
            } else {
                $oa_issues[] = $oa_issue[$key];
            }

            unset($oa_issue);

            /*----------------------------------------------------------------------------*/
        }

        return $oa_issues;

    }

}
