<?php

namespace App\Http\Controllers;
use App\Http\Controllers\PaypalExpress;
use App\Http\Controllers\MigsController;
use App\Models\Article;
use App\Models\Author;
use App\Models\BookAccess;
use App\Models\Campaign;
use App\Models\Chapter;
use App\Models\ContentAccess;
use App\Models\Country;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Journal;
use App\Models\Log;
use App\Models\MarkList;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Orders;
use App\Models\Subject;
use App\Models\UserAccess\UserAccess;
use App\Models\BundleOffer;
use App\Rules\Captcha;
use App\User;
use Auth;
use Cookie;
use DB;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;

class EbookVolumeController extends BenthamController
{

    public function index(Request $request)
    {

        $editPermission   = false;
        $deletePermission = false;

        $param['ebook_id']  = $ebook_id  = $request->get('ebook_id');
        $param['volume_id'] = $volume_id = $request->get('volume_id');
        $param['year_id']   = $year_id   = $request->get('year_id');

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

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

            $ebook_volume_list = EbookVolume::GetEbookVolume($param);
            $volume_search     = EbookVolume::GetEbookVolumeByEbookId($ebook_id);

        }

        if ($ajx_search != null && $ajx_search == true) {
            if (!empty($ebook_id)) {
                $volume_search = EbookVolume::GetEbookVolumeByEbookId($ebook_id);
                return response()->json(array('volume_search' => $volume_search), 200);
            }
        }

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

            $ebook_volume_list = EbookVolume::GetEbookVolume();
        }

        $ebook_search = Ebook::GetEbookTitle();
        $year_search  = Journal::GetYear();

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

        return View::make('admin.ebook_volume.volume', with(['ebook_volume_list' => $ebook_volume_list,
        'volume_search' => $volume_search,
        'ebook_search' => $ebook_search,
        'year_search' => $year_search,
        'param' => $param,
        'editPermission' => $editPermission,
        'deletePermission' => $deletePermission]));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function add()
    {
        $ebook = Ebook::GetEbookTitle();

        $month_arr = array(
            '1'  => 'Janaury',
            '2'  => 'February',
            '3'  => 'March',
            '4'  => 'April',
            '5'  => 'May',
            '6'  => 'June',
            '7'  => 'July',
            '8'  => 'August',
            '9'  => 'September',
            '10' => 'October',
            '11' => 'November',
            '12' => 'December',
        );

        return View::make('admin.ebook_volume.ebook_volume_form', with(['ebook' => $ebook, 'month_arr' => $month_arr]));
    }

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

        // not in use
    }

    public function create(Request $request)
    {
        $ajx_search  = $request->get('ajx_search');
        $ebook_exist = $request->get('ebook_exist');

        if ($ajx_search == true && $ebook_exist == true) {
            $ebook_id     = $request->get('ebook_id');
            $volume_name  = $request->get('volume_name');
            $ebook_volume = EbookVolume::where('ebook_id', $ebook_id)->where('volume_name', $volume_name)->select('volume_name')->first();
            $volume_name  = isset($ebook_volume->volume_name) ? $ebook_volume->volume_name : null;
            return response()->json(array('volume_name' => $volume_name), 200);
        } else {
            $ebook       = Ebook::GetEbookTitle();
            $year_search = Journal::GetYear();
            $month_arr   = array(
                '1'  => 'Janaury',
                '2'  => 'February',
                '3'  => 'March',
                '4'  => 'April',
                '5'  => 'May',
                '6'  => 'June',
                '7'  => 'July',
                '8'  => 'August',
                '9'  => 'September',
                '10' => 'October',
                '11' => 'November',
                '12' => 'December',
            );

            $country = Country::GetCountryList();
            $page    = 'add';
            return View::make('admin.ebook_volume.ebook_volume_form', with(['ebook' => $ebook,
             'year_search' => $year_search,
              'month_arr' => $month_arr,
               'country' => $country,
                'page' => $page]));
        }
    }

    public function update(Request $request, $ebook_volume_id)
    {
        if (isset($request->update_ebook_volume_form)) {
            $result = $this->UpdateVolume($request, $ebook_volume_id);
        }
        if (isset($request->upload_cover_image)) {
            $result = $this->UploadCoverImage($request, $ebook_volume_id);
        }
        if (isset($request->upload_files)) {
            $result = $this->UploadFiles($request, $ebook_volume_id);
        }
        if (isset($request->submit_meta)) {
            $result = $this->SubmitMeta($request, $ebook_volume_id);
        }

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

    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $ajax   = $request->get('ajax');
        $action = $request->get('action');
        $method = $request->get('method');

        if ($ajax == true) {

            if ($method == 'author') {

                if ($action == 'SELECT') {
                    return $this->ajax_SELECT($request);
                }

                if ($action == 'INSERT') {
                    return $this->ajax_INSERT($request);
                }

                if ($action == 'DELETE') {
                    return $this->ajax_DELETE($request);
                }

                if ($action == 'UPDATE') {
                    return $this->ajax_UPDATE($request);
                }
            } else if ($method == 'Affiliation') {

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

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

            }
        }
    }

    public function destroy(Request $request, $ebook_volume_id)
    {
        $ebook_volume = array();
        $log_authors  = array();
        $log_author   = array();
        $log_meta     = array();
        $log_node     = array();

        try {
// try transaction start here for data integrity

            DB::beginTransaction();
            $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->get()->toArray()[0];

            $chapter = Chapter::where('ebook_volume_id', $ebook_volume_id)->where('ebook_id', $ebook_volume['ebook_id'])->first();

            if (empty($chapter)) {

                $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->get()->toArray()[0];
                //print_r($ebook_volume); die;
                $log_meta = (array) Meta::NodeMeta($ebook_volume['nid']);
                $log_node = (array) Node::GetNode($ebook_volume['nid']);

                $authors = Author::getAuthorDataById($ebook_volume_id, 'ebook_volume_id');

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

                //Author::DeleteAuthors($ebook_volume_id, 'ebook_volume_id');
                //-----------------------------Delete into log table-----------------------------------

                $log     = array_merge($log_node, $ebook_volume, $log_meta, $log_authors);
                $user    = Auth::user();
                $add_log = array(
                    'content_id'      => $ebook_volume['ebook_volume_id'],
                    'content_type_id' => config('constants.log_content_types.EbookVolume'),
                    '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);

                Node::DeleteNode($ebook_volume['nid']);
                Meta::DeleteMeta($ebook_volume['nid']);
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->delete();
                Author::DeleteAuthors($ebook_volume_id, 'ebook_volume_id');
                //-------------------------------------------------------------------------------------
            } else {
                return back()->with(['delete_msg' => 'chapter already exist in this volume']);
            }

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

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return Redirect::to('admin/ebook_volume');
        }
        return redirect()->back()->with('success', 'eBook Volume delete successfully.');}

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

        $ajx_search = $request->get('ajx_search');
        if ($ajx_search == true) {
            $ebook_id     = $request->get('ebook_id');
            $volume_name  = $request->get('volume_name');
            $ebook_volume = EbookVolume::where('ebook_id', $ebook_id)->where('volume_name', $volume_name)->select('volume_name')->first();
            $volume_name  = isset($ebook_volume->volume_name) ? $ebook_volume->volume_name : null;
            return response()->json(array('volume_name' => $volume_name), 200);
        } else {
            $volume = EbookVolume::GetEbookVolumeAndAuthorsById($volume_id);
            $volume = $volume[0];

            if (!empty($volume->expected_date)) {
                $expected_date               = explode('_', $volume->expected_date);
                $volume->expected_date_year  = $expected_date[1];
                $volume->expected_date_month = $expected_date[0];
            } else {
                $volume->expected_date_year  = '';
                $volume->expected_date_month = '';
            }

            $month_arr = array(
                '1'  => 'Janaury',
                '2'  => 'February',
                '3'  => 'March',
                '4'  => 'April',
                '5'  => 'May',
                '6'  => 'June',
                '7'  => 'July',
                '8'  => 'August',
                '9'  => 'September',
                '10' => 'October',
                '11' => 'November',
                '12' => 'December',
            );

            $ebook       = Ebook::GetEbookTitle();
            $year_search = Journal::GetYear();
            $country     = Country::GetCountryList();

            $selected_meta = Meta::NodeMeta($volume->nid);
            $page          = 'update';
            return View::make('admin.ebook_volume.ebook_volume_form', with(['user' => $user,
             'volume' => $volume,
              'volume_id' => $volume_id,
               'ebook' => $ebook,
                'year_search' => $year_search,
                 'month_arr' => $month_arr,
                  'selected_meta' => $selected_meta,
                   'country' => $country,
                    'page' => $page]));
        }
    }

    public function InsertVolume($request)
    {
        $exist_volume = '';
        $input     = $request->all();
        $validator = Validator::make($request->all(),
            [
                'ebook_id'    => 'required',
                'year_id'     => 'required',
                'volume_name' => 'required',
                'eisbn'       => 'required_if:select_ebook_type,PDF',
                'flyer_link'  => 'mimes:pdf',

            ]);

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

            $param['ebook_id']    = $ebook_id    = $request->get("ebook_id");
            $param['volume_name'] = $volume_name = $request->get("volume_name");

            $volume       = EbookVolume::GetEbookVolumeById($param);

            if($volume)
            {
                $exist_volume = $volume[0];
            }

            if (!empty($exist_volume)) {
                $validator->errors()->add('volume_name', 'ebook volume name already exist');
            }
        });

        if ($validator->fails()) {
            return array(false, $validator);
        }

        try {
// try transaction start here for data integrity

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

            //-------------------Insert into Ebook Volume table---------------
            $ebook_field = array('ebook_status', 'ebook_type', 'ebook_id', 'select_ebook_type', 'year_id', 'volume_name', 'ebook_subtitle',
                'isbn', 'issn', 'eisbn', 'eissn', 'flyer_link', 'ebook_price_pod', 'ebook_price',
                'chapter_price', 'file_name', 'sample_file_name', 'epub_file_name', 'supplementary_filename', 'introduction', 'doi', 'url', 'is_uploaded', 'index_on',
                'amazon_kindle', 'amazon_paperback', 'book_audience','ebook_meta_type',
            );

            $user                    = Auth::user();
            $add_ebook_volume['nid'] = $add_node['nid'];

            foreach ($ebook_field as $vals) {
                if($vals == "introduction" || $vals == "book_audience")
                {   
                    $add_ebook_volume[$vals] = htmlentities($request->get($vals));
                }
                else
                {
                    $add_ebook_volume[$vals] = $request->get($vals);
                }
            }

            $add_ebook_volume['publication_date'] = strtotime($request->get('publication_date'));

            $expected_date_year  = $request->get('expected_date_year');
            $expected_date_month = $request->get('expected_date_month');

            if (!empty($expected_date_year) && !empty($expected_date_month)) {
                $expected_date = $expected_date_month . '_' . $expected_date_year;
            } else {
                $expected_date = '';
            }

            $add_ebook_volume['expected_date'] = $expected_date;

            //-------------------Genrate DOI ------------------------------

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

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

                $doi = $this->GetEbookVolumeDOI($request);

            } else {

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

            $add_ebook_volume['doi'] = $doi;
            //-------------------------------------------------------------

            $add_ebook_volume['file_path']             = $this->get_file_path($request);
            $add_ebook_volume['ebook_price_podandpdf'] = $request->get('ebook_price_pod_pdf');
            $add_ebook_volume['created']               = time();
            $add_ebook_volume['created_by']            = $user->id;
            $add_ebook_volume['updated_by']            = $user->id;
            $add_ebook_volume['ebook_volume_id']       = EbookVolume::insertGetId($add_ebook_volume);

            //----------------------Upload ebook flyer-------------------------------

            $ebook_volume    = EbookVolume::where('ebook_volume_id', $add_ebook_volume['ebook_volume_id'])->get();
            $ebook_volume    = $ebook_volume[0];
            $ebook_volume_id = $ebook_volume->ebook_volume_id;
            $eisbn           = $ebook_volume->eisbn;
            $volume_name     = $ebook_volume->volume_name;

            $ebook_volume_path = $ebook_volume->file_path;
            $file_path         = config('constants.admin.root_path') . $ebook_volume_path;

            $ebook_flyer_name = '';

            //----------------------Upload flyer files-------------------------------

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

                $flyer_link->move($file_path, $ebook_flyer_name);

                $update_file_name['flyer_link'] = $ebook_flyer_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_file_name);
            }

            //-------------------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['ebook_volume'] = $add_ebook_volume;
            // $log_meta['node_meta']      = $add_node_meta;
            // $log_author['author']          = $add_author_data;

            $log     = array_merge($log_node, $log_volume);
            $add_log = array(
                'content_id'      => $add_ebook_volume['ebook_volume_id'],
                'content_type_id' => config('constants.log_content_types.EbookVolume'),
                '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/ebook_volume');
        }

        return array(true, $add_ebook_volume['ebook_volume_id']);
    }

    public function UpdateVolume($request, $ebook_volume_id)
    {
        $input = $request->all();
        $req   = array();

        $req['ebook_id']    = 'required';
        $req['year_id']     = 'required';
        $req['volume_name'] = 'required';
        $req['flyer_link']  = 'mimes:pdf';
        $req['eisbn']       = 'required_if:select_ebook_type,PDF';

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

        $validator->after(function ($validator) use ($request,$ebook_volume_id) {
            $param['ebook_volume_id'] = $ebook_volume_id;
            $param['ebook_id']        = $ebook_id        = $request->get("ebook_id");
            $param['volume_name']     = $volume_name     = $request->get("volume_name");

            $volume = EbookVolume::CheckEbookVolumeExist($ebook_volume_id, $ebook_id, $volume_name);

            if (!empty($volume)) {
                $validator->errors()->add('volume_name', 'ebook volume name already exist');
            }
        });

        if ($validator->fails()) {
            return array(false, $validator);
        }

        try {
// try transaction start here for data integrity

            DB::beginTransaction();
            $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->get();
            $ebook_volume = $ebook_volume[0];
            $eisbn        = $ebook_volume->eisbn;
            $volume_name  = $ebook_volume->volume_name;

            //-------------------Update into Ebook Volume table---------------
            $ebook_field = array('ebook_status', 'ebook_type', 'select_ebook_type', 'year_id', 'ebook_subtitle',
                'isbn', 'issn', 'eissn', 'eisbn', 'ebook_price_pod', 'ebook_price',
                'chapter_price', 'introduction', 'doi', 'url', 'is_uploaded', 'index_on', 'amazon_kindle', 'amazon_paperback', 'book_audience','ebook_meta_type',
            );


            foreach ($ebook_field as $vals) {
                if($vals == "introduction" || $vals == "book_audience")
                {   
                    $update_ebook_volume[$vals] = htmlentities($request->get($vals));
                }
                else
                {
                    $update_ebook_volume[$vals] = $request->get($vals);
                }

            }

            $user                                    = Auth::user();
            $update_ebook_volume['publication_date'] = strtotime($request->get('publication_date'));

            $expected_date_year  = $request->get('expected_date_year');
            $expected_date_month = $request->get('expected_date_month');

            if (!empty($expected_date_year) && !empty($expected_date_month)) {
                $expected_date = $expected_date_month . '_' . $expected_date_year;
            } else {
                $expected_date = '';
            }

            $update_ebook_volume['expected_date'] = $expected_date;

            //-------------------Genrate DOI ------------------------------

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

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

                $doi = $this->GetEbookVolumeDOI($request);

            } else {

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

            $update_ebook_volume['doi'] = $doi;
            //-------------------------------------------------------------
            $update_ebook_volume['file_path']             = $this->get_file_path($request);
            $update_ebook_volume['ebook_type']            = $request->get('ebook_type');
            $update_ebook_volume['ebook_status']          = $request->get('ebook_status');
            $update_ebook_volume['ebook_price_podandpdf'] = $request->get('ebook_price_pod_pdf');
            $update_ebook_volume['created']               = time();
            $update_ebook_volume['created_by']            = $user->id;
            $update_ebook_volume['updated_by']            = $user->id;

            EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_ebook_volume);

            $update_ebook_volume['ebook_volume_id'] = $ebook_volume_id;
            $update_ebook_volume['nid']             = $ebook_volume->nid;

            //----------------------Upload ebook flyer-------------------------------

            $ebook_volume_path = $update_ebook_volume['file_path'];
            $file_path         = config('constants.admin.root_path') . $ebook_volume_path;

            $ebook_flyer_name = '';

            //----------------------Upload pdf files-------------------------------

            if ($request->hasFile('flyer_link')) {
                $flyer_link       = $request->file('flyer_link');
                $ebook_flyer_name = $flyer_link->getClientOriginalName();

                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }

                $flyer_link->move($file_path, $ebook_flyer_name);

                $update_file_name['flyer_link'] = $ebook_flyer_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_file_name);
            }

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

            $log_volume['ebook_volume'] = $update_ebook_volume;

            $log     = array_merge($log_volume);
            $add_log = array(
                'content_id'      => $ebook_volume_id,
                'content_type_id' => config('constants.log_content_types.EbookVolume'),
                '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/ebook_volume');
        }

        return array(true, $ebook_volume_id);
    }

    public function SubmitMeta($request, $ebook_volume_id)
    {
        //-------------------Update into Meta table---------------
        $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->select('nid')->first();
        Meta::where('nid', $ebook_volume->nid)->delete();

        $add_node_meta['nid']           = $ebook_volume->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);

        return array(true, $ebook_volume_id);
    }

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

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

        return $add_author_data;

    }

    /**
     *
    Get All Author Rows of Ebook Volume
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function ajax_SELECT($request)
    {
        $ebook_volume_id = $request->get('ebook_volume_id');

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

    }

    /*
    Store Author Row of Ebook Volume
    Store Inserted Author Log
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response in JSON
     */

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

            DB::beginTransaction();

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

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

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

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

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

    /*
    Update Author Row of Ebook Volume
    Store Updated Author Log
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response in JSON
     */

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

            DB::beginTransaction();

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

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

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

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

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

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

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

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

    }

    /*
    DELETE Author Row of Ebook Volume
    Store DELETE Author Log
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response in JSON
     */

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

            DB::beginTransaction();

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

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

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

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

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

            $log = Log::AddLog($add_log);

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

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

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

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

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

    }

//----------------Author Affiliation--------------------
    public function ajax_SELECT_Author_Affiliation($request)
    {
        $author_id = $request->get('author_id');
        if (!empty($author_id)) {
            $selected_affiliation = Article::GetAuthorAffiliation($author_id, 'author_id');
            return response()->json(array('selected_affiliation' => $selected_affiliation), 200);
        }

    }

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

            DB::beginTransaction();

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

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

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

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

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

    }

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

            DB::beginTransaction();

            $update_affiliation['aff_id']      = $request->get('aff_id');
            $update_affiliation['institution'] = $request->get('institution');
            $update_affiliation['department']  = $request->get('department');
            $update_affiliation['address']     = $request->get('address');
            $update_affiliation['country']     = $request->get('country');
            $update_affiliation['city']        = $request->get('city');
            $update_affiliation['postal_code'] = $request->get('postal_code');
            $update_affiliation['phone']       = $request->get('phone');
            $update_affiliation['fax']         = $request->get('fax');
            $update_affiliation['web_view']    = $request->get('web_view');
            
            Article::UpdateAuthorAffiliation($update_affiliation);

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

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

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

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

    }

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

            DB::beginTransaction();

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

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

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

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

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

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

    }
    //------------------------------------------------------//
    public function UploadFiles($request, $ebook_volume_id)
    {
        $req = array();
        if (isset($request->file_name)) {
            $req['file_name'] = 'required|mimes:pdf';
        }
        if (isset($request->supplementary_filename)) {
            $req['supplementary_filename'] = 'mimes:rar,html,zip';
        }
        if (isset($request->sample_file_name)) {
            $req['sample_file_name'] = 'mimes:pdf';
        }
        if (isset($request->epub_file_name)) {
            $req['epub_file_name'] = 'mimes:epub';
        }
        if (isset($request->prc_file_name)) {
            //$req['prc_file_name'] = 'mimes:mobipocket';
        }

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

        if ($validator->fails()) {
            return array(false, $validator);
        } else {
            $ebook_volume    = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->get();
            $ebook_volume_id = $ebook_volume[0]->ebook_volume_id;
            $eisbn           = $ebook_volume[0]->eisbn;
            $isbn           = $ebook_volume[0]->isbn;
            $volume_name     = $ebook_volume[0]->volume_name;

            $file_path         = config('constants.admin.root_path') . $ebook_volume[0]->file_path;

            $article_file_name       = '';
            $image_file_name         = '';
            $supplementary_file_name = '';
            $sample_file_name        = '';
            $epub_file_name          = '';
            $sample_file             = '';

            //----------------------Upload pdf files-------------------------------

            if ($request->hasFile('file_name')) {
                $file_name         = $request->file('file_name');
                $article_file_name = $file_name->getClientOriginalName();
                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }

                $file_name->move($file_path, $article_file_name);

                $update_file_name['file_name'] = $article_file_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_file_name);
            }

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

                $update_supp_file_name['supplementary_filename'] = $supplementary_file_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_supp_file_name);
            }

            //----------------------Upload html files-------------------------------
            if ($request->hasFile('sample_file_name')) {
                $sample_file      = $request->file('sample_file_name');
                $sample_file_name = $sample_file->getClientOriginalName();
                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }
                $sample_file->move($file_path, $sample_file_name);
                $update_sample_file_name['sample_file_name'] = $sample_file_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_sample_file_name);
            }
            //----------------------Upload epub files-------------------------------
            if ($request->hasFile('epub_file_name')) {
                $epub_file      = $request->file('epub_file_name');
                $epub_file_name = $epub_file->getClientOriginalName();
                /*if (!is_dir($file_path . 'epub')) {
                    mkdir($file_path . 'epub', 0755, true);
                }
                $epub_file->move($file_path . 'epub', $epub_file_name);
                */
                $epub_file->move($file_path , $epub_file_name);

                $update_epub_file_name['epub_file_name'] = $epub_file_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_epub_file_name);

            }
            //----------------------Upload prc files-------------------------------
            if ($request->hasFile('prc_file_name')) {
                $prc_file      = $request->file('prc_file_name');
                $prc_file_name = $prc_file->getClientOriginalName();
                /*if (!is_dir($file_path . 'prc')) {
                    mkdir($file_path . 'prc', 0755, true);
                }
                $prc_file->move($file_path . 'prc', $prc_file_name);
                */
                
                $prc_file->move($file_path , $prc_file_name);
                $update_prc_file_name['prc_file_name'] = $prc_file_name;
                EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_prc_file_name);

            }

            return array(true, $ebook_volume_id);
        }
    }

    public function get_file_path($request)
    {

        $eisbn       = $request->get("eisbn");
        $isbn       = $request->get("eisbn");
        $volume_name = $request->get("volume_name");
        $select_ebook_type = $request->get("select_ebook_type");

        if(strtolower($select_ebook_type) == "video")
        {    
            $ebook_volume_path = "E-books/BEN/" . $isbn . "/" . $volume_name . "/EBOOK/";
        }
        else
        {
            $ebook_volume_path = "E-books/BEN/" . $eisbn . "/" . $volume_name . "/EBOOK/";
        }
        if (!is_dir($ebook_volume_path)) {
            mkdir($ebook_volume_path, 0755, true);
        }

        return $ebook_volume_path;

    }

    public static function GetEbookVolumeDOI($request)
    {

        $eisbn     = trim(str_replace("-", "", $request->get('eisbn')));
        $volume_no = trim($request->get('volume_name'));
        $year_id   = $request->get('year_id');

        $year = DB::table('year')->select('year')->where('id', $year_id)->first();
        $year = substr(trim($year->year), 2, 2);

        if ($volume_no < 10) {
            $volume_no = "0" . $volume_no;
        }

        $edition = "01";

        //$doi = "10.2174/".$eisbn."-1-".$year."-".$volume_no."-".$edition;
        $doi = "10.2174/" . $eisbn . "1" . $year . $volume_no . $edition;

        $doi = trim($doi);

        return $doi;
    }

    public function GetEbookVolumeList(Request $request)
    {  
        $all_ebook_volume=array();

        $ajx_call = $request->get("ACTION");

        if (strpos($request->path(), 'browse-ebook-subscribe') !== false) {
            session(['myebooksubscribption' => true]);
        }
        if (strpos($request->path(), 'bybook') !== false) {

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

        if ($ajx_call == 'SELECT') {
            $all_ebook_volume = EbookVolume::GetAllEbookVolumeList();
            return response()->json(array('ebook_list' => $all_ebook_volume), 200);
        }

        $ebook_volume = array();

        $letter = '';
        $param  = array();

        if (isset($request->letter)) 
		{

            if (is_numeric($request->letter)) 
            {
               $param['year'] = $request->letter;
            } 
            else 
            {
                if ($request->letter == 'video') 
                {
                    $param['select_ebook_type'] = 'video';
                } 
                elseif ($request->letter == 'series') 
                {
                    $param['ebook_type'] = 2;
                } 
                elseif ($request->letter == 'general') 
                {
                    $param['ebook_type'] = 1;
                } 
                elseif ($request->letter == 'open_access') 
                {
                    $param['open_access'] = 'open_access';
                } 
                else 
                {
                    $letter = $request->letter;
                }
            }
        } 
		elseif (isset($request->search_ebook)) 
		{
            
            if(strpos($request->search_value, '10.2174/')!== false){
               
                $chapter_obj = Chapter::GetChapterByDOI($request->search_value);
                if(!empty($chapter_obj)){
                    return Redirect::to('chapter/' . $chapter_obj->chapter_id);
                }
            }

           if(isset($request->search_by))
           {
                
               if ($request->search_by == 'chapter_title')
               {
                    $chapter_obj = Chapter::GetChapterByTitle($request->search_value);
                    if(!empty($chapter_obj)){
                        return Redirect::to('chapter/' . $chapter_obj->chapter_id);
                    }
                }

                if ($request->search_by == 'book_title') {
                $param['title'] = $request->search_value;
                }
                if ($request->search_by == 'year') {
                $param['year'] = $request->search_value;
                }
                if ($request->search_by == 'by_doi') {
                $param['doi'] = $request->search_value;
                }
                if ($request->search_by == 'by_isbn') {
                $param['isbn_eisbn'] = $request->search_value;
                }
            }
            else
            {
                $param['All'] = $request->search_value;
            }
        }
            if (session()->has('myebooksubscribption')) 
    		{
    			if (session()->has('ip_base_access') || session()->has('user_base_access')) 
    			{
    				$user_id = session()->get('user_id');
    				$param['user_id'] = $user_id;
    			}
    			
    			$param['ip_address'] = ip2long($request->ip());
                list($ebook_volume,$sample_types)    = EbookVolume::SearchEbookVolumeList($letter, $param, true);
                $searchFormRoute = 'browseebooksubscribe';
            } else {
                list($ebook_volume,$sample_types)    = EbookVolume::SearchEbookVolumeList($letter, $param);
                $searchFormRoute = 'bybook';
            }
        $year = Journal::GetYear();
         //       dd($ebook_volume );

        return view('ebook.ebook_volume_list', with(['all_ebook_volume' => $all_ebook_volume,
         'ebook_volume' => $ebook_volume,
          'year' => $year,
           'searchFormRoute' => $searchFormRoute,
           'sample_types' => $sample_types]));
    }

    public function GetEbookForthcoming(Request $request)
    {
        $ebook_volume_details = array();
        $chapter_details=array();
        $ebook=array();

        $year                 = Journal::GetYear();

        if (isset($request->letter) && $request->letter == 'generalebook') {
            $param['ebook_type']   = 1; //General eBook
            $param['ebook_status'] = 2; //pre-published
            $ebook_volume_details  = EbookVolume::GetEbookVolumeForthcoming($param);
            $title                 = "Forthcoming Title";
        }
        if (isset($request->letter) && $request->letter == 'series') {
            $param['ebook_type']   = 2; //Series
            $param['ebook_status'] = 2; //pre-published
            $ebook_volume_details  = EbookVolume::GetEbookVolumeForthcoming($param);
            $title                 = "Forthcoming Series";
        }
        // if (isset($request->letter) && $request->letter == 'futuregeneralebook')
        // {
        // $param['ebook_type'] = $request->letter;
        // $param['ebook_status'] = 3; //future
        // $ebook_volume_details = EbookVolume::GetEbookVolumeForthcoming($param);
        // $title = "Forthcoming Series";
        // }
        // if (isset($request->letter) && $request->letter == 'futureseries')
        // {
        // $param['ebook_type'] = $request->letter;
        // $param['ebook_status'] = 3; //future
        // $ebook_volume_details = EbookVolume::GetEbookVolumeForthcoming($param);
        // $title = "Forthcoming Series";
        // }

        return view('ebook.ebook_forthcoming', with(['ebook_volume_details' => $ebook_volume_details,
         'chapter_details' => $chapter_details,
          'ebook' => $ebook,
           'year' => $year,
            'title' => $title]));

    }

    public function ReadEbookPDF($param)
    {

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

        if (file_exists($file)) {

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

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

    public function GetEbookVolumeDetails(Request $request)
    {
        if($request->id == "download" && isset($request->page_name))
        {
            $ebook_volume_nid = $request->page_name;
            $ebook_volume = EbookVolume::where('nid', '=', $ebook_volume_nid)->first();

            if(!empty($ebook_volume))
            {
                $ebook_volume_id = $ebook_volume->ebook_volume_id;

                $file_path = $this->DirectEbookVolumeDownload($request,$ebook_volume_id);

                return response()->download($file_path);
            }
            else
            {
                return abort(404);
            }
        }
        if($request->id == "download" && $request->has('doi'))
        {
            $ebook_volume_doi = $request->doi;

            $ebook_volume = EbookVolume::where('doi', '=', $ebook_volume_doi)->first();


            if(!empty($ebook_volume))
            {
                $ebook_volume_id = $ebook_volume->ebook_volume_id;

                $file_path = $this->DirectEbookVolumeDownload($request,$ebook_volume_id);

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

        $type   = "";
        $eparam = '';
        if (isset($request->param)) {
            $eparam                               = $request->param;
            list($type, $ebook_volume_id, $token) = decrypt($request->param);
        } else {
            $type = "";
        }

        $ebook_volume_details        = array();
        $ebk_vol_access              = null;
        $DownloadAccess              = false;
        $VolumeDownloadAccess        = false;
        $ViewOption                  = 0;
        $chapter_before_level        = false;
        $download_access_data        = '';
        $access_base_text            = '';
        $sparam                      = array();
        $rparam                      = '';
        $content_download_type       = "";
        $terms_popup                 = true;
        $checkIfMarked               = false;
        $restricted_user_access_key  = '';
        $restricted_user_access_type = '';
        $related_ebook               = array();
        $related_journal             = array();
        $a                           = 0;
        $CountMultipleVolumeExist    = 0;
        $bundle_content              = array();
		$user_access_id				 = 0;
		$vol_type				     = 0;
        $ebooks=array();
        $vol_access_base_text="";
        $view_pdf = 0;

        $year                 = Journal::GetYear();
        $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->id, 'front');
        
        if (session()->has('user_id')) {
            $bundle_content = BundleOfferController::BundleOfferUserAccess(session()->get('user_id'));
        }

        if (count($ebook_volume_details) == 0) {
            return Redirect::to('/bybook');
        }
        $param['ebook_volume_id'] = $ebook_volume_id = $request->id;
        $param['view']            = 'user';
        $chapter_details          = Chapter::GetChapterListByEbookVolume($param,100);
		
        $ebook                    = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);

        if ($ebook_volume_details[0]->ebk_ebook_id > 1) 
		{
            $related_ebook   = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);            
            $related_journal = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
        }

        $discount = $this->getDiscount($ebook_volume_details);
		
        //used to check volume level prepetual access(if user has perchased that volume)
        //if access given then $DownloadAccess will be true
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $ebook_volume_id, 'volume')[0]->total > 0){                        
                $DownloadAccess        = true;
                $VolumeDownloadAccess  = true;
                $access_base_text      = "Subscribe";                        
                $content_download_type = 'P';
                $terms_popup           = true;   
                $ebk_vol_lvl_access    = true;
            }
        }


		if(!empty($chapter_details[0]))
		{
			$ebook_id = $chapter_details[0]->ebook_id;
			$ebook_volume_id = $chapter_details[0]->ebook_volume_id;
			$chapter_id  = $chapter_details[0]->chapter_id;

			//Check Content Access Volume Level
			$ebk_vol_lvl_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");
			$ebk_vol_lvl_access = $content_access = isset($ebk_vol_lvl_access[0]->access_type) ? $ebk_vol_lvl_access[0]->access_type : null;

			if ($ebk_vol_lvl_access) 
			{
				$DownloadAccess = $ebk_vol_lvl_access;
				$VolumeDownloadAccess = $ebk_vol_lvl_access; 
			}
            			
            
			// Check User Access Volume Level 
			if (!$DownloadAccess) 
			{
				$v_param['volume_id'] = $ebook_volume_id;
				$v_param['user_id'] = session()->get('user_id');
				$v_param['ip_address'] = $request->ip();
				
				$ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param,array('ebook_volume'=>true));
				
				if (!empty($ua_volume_lvl[0])) 
				{
					$DownloadAccess = $ua_volume_lvl[0]->volume_id;
					$VolumeDownloadAccess = $ua_volume_lvl[0]->volume_id;
					$content_download_type = $ua_volume_lvl[0]->content_download_type;
					$restricted_user_access_key = $ua_volume_lvl[0]->restricted_user_access_key;
					$voparam['user_access_id'] = $user_access_id = $ua_volume_lvl[0]->user_access_id;
					$vol_type = $ua_volume_lvl[0]->type;
					$terms_popup = $ua_volume_lvl[0]->terms_popup;
					$vol_access_base_text = $ua_volume_lvl[0]->access_base_text;
                    $voinfo = UserAccess::GetUserAccessInfo($voparam);
                    $ViewOption = $voinfo->view_option;
				}
			}
		
			//Check Content Access Chapter Level
			foreach($chapter_details as $k => $v)
			{
				$chapter_ids[] = $v->chapter_id;
			}
			
			$param['table'] = 'ebook_access';
			$param['chapter_ids'] = $chapter_ids;
			$param['condition'] = true;
			$chapter_lvl_access = ContentAccess::GetContentAccessById($param);
			
			
			foreach ($chapter_details as $key => $chapter) 
			{
				$oa_chapters[$key] = $chapter_details[$key];
				
				$oa_chapters[$key]->open_access 			= false;
				$oa_chapters[$key]->download_access 		= false;
				$oa_chapters[$key]->content_download_type 	= '';
				$oa_chapters[$key]->access_base_text      	= '';
				$oa_chapters[$key]->terms_popup          	= '';
				$oa_chapters[$key]->restricted_user_access_key   = '';
				$oa_chapters[$key]->restricted_user_access_type  = '';
                $oa_chapters[$key]->user_access_id               = '';
                $oa_chapters[$key]->view_option             = 0;
                $oa_chapters[$key]->type = '';

				if(!empty($ebk_vol_lvl_access))
				{
					$open_access_before = $ebk_vol_lvl_access;
				}
				
				if(!empty($open_access_before))
				{
					$oa_chapters[$key]->open_access      = true;
					$oa_chapters[$key]->download_access      = 1;
					
					$oa_chapters[$key]->terms_popup          = true;
					if($open_access_before  == 1)
					{
						$oa_chapters[$key]->content_download_type = 'F';
                       // $oa_chapters[$key]->access_base_text = 'promotion: free to download';
                        $oa_chapters[$key]->access_base_text = '';
					}               
					elseif($open_access_before  == 2)
					{
						$oa_chapters[$key]->content_download_type = 'FO';
						$oa_chapters[$key]->access_base_text = 'open access plus';
					}
				}
				elseif (!empty($chapter_lvl_access))
				{
					foreach($chapter_lvl_access as $a_k => $a_v)
					{
						if ($a_v->content_type_id == $chapter->chapter_id)
						{
							$oa_chapters[$key]->open_access      = true;
							$oa_chapters[$key]->download_access      = 1;
							
							$oa_chapters[$key]->terms_popup          = true;
							
							if($a_v->content_type_access_id  == 1)
							{
								$oa_chapters[$key]->content_download_type = 'F';
                                //$oa_chapters[$key]->access_base_text = 'promotion: free to download';
                                $oa_chapters[$key]->access_base_text = '';
							}               
							elseif($a_v->content_type_access_id  == 2)
							{
								$oa_chapters[$key]->content_download_type = 'FO';
								$oa_chapters[$key]->access_base_text = 'open access plus';
							}
							
						}
					}
				}                
                
			}
			
			//-------------------------------------------------------------------
		
			// Check User Access Chapter Level 
			$c_param['user_id'] = session()->get('user_id');
			$c_param['ip_address'] = $request->ip();
			
			$ua_chapter_lvl = UserAccess::GetAllContentUserAccess($c_param,array('chapter'=>true));
			
			$ua_chapter_list = array();
			
			foreach($oa_chapters as $ao_k => $ao_v)
			{
				$ua_chapter[$ao_k] = $oa_chapters[$ao_k];
				$ua_chapter[$ao_k]->user_access = false;
				
				if ($ao_v->open_access == false)
				{
					$ua_chapter[$ao_k]->download_access = 0;
					$ua_chapter[$ao_k]->access_base_text = '';
					$ua_chapter[$ao_k]->DownloadAccess        = false;
					$ua_chapter[$ao_k]->free                  = false;        
					$ua_chapter[$ao_k]->tracksAccessByVolume  = false;
					$ua_chapter[$ao_k]->access_data           = '';
					$ua_chapter[$ao_k]->restricted_user_access_key = '';
					$ua_chapter[$ao_k]->user_access_id 			   = '';
					
					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))
					{
                        $cparam['user_access_id']=$user_access_before->user_access_id;
                        $user_access_info = UserAccess::GetUserAccess($cparam);  

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

                                $ua_chapter[$ao_k]->view_option = $user_access_info->view_option;
                                $ua_chapter[$ao_k]->user_access = true;
								$ua_chapter[$ao_k]->user_access_id = $ua_v->user_access_id;
								$ua_chapter[$ao_k]->terms_popup = $ua_v->terms_popup;
								$ua_chapter[$ao_k]->access_base_text = $ua_v->access_base_text;
								$ua_chapter[$ao_k]->content_download_type = $ua_v->content_download_type;
								$ua_chapter[$ao_k]->restricted_user_access_key = $ua_v->restricted_user_access_key;
								$ua_chapter[$ao_k]->restricted_user_access_type = $ua_v->restricted_user_access_type;
								$ua_chapter[$ao_k]->tracksAccessByVolume = $ua_v->tracksAccessByVolume;
								$ua_chapter[$ao_k]->DownloadAccess = true;
								$ua_chapter[$ao_k]->download_access = 1;
								$ua_chapter[$ao_k]->free = false;
								$ua_chapter[$ao_k]->type = $ua_v->type;
								
							}
						}
					}
				}
				
				if (isset($request->page_name) && $request->page_name==='subscribe') 
				{
					if (isset($ua_chapter[$ao_k]->type))
					{
						// include only User Access Articles
						$ua_chapter_list[] = $ua_chapter[$ao_k];
					}
				}
				else
				{
					$ua_chapter_list[] = $ua_chapter[$ao_k];
				}
				
				unset($ua_chapter);
				
			}
		
			foreach($chapter_details as $alk => $alv)
			{
				unset($chapter_details[$alk]);
				
				if (!empty($ua_chapter_list[$alk]))
				{
					$chapter_details[$alk] = $ua_chapter_list[$alk];
				}
			}
	
		/*----------------------------------------------------------------------------*/

			foreach ($chapter_details as $key => $chapter) 
			{
			   
               if(session()->get('user_id')){    
                    if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $chapter->chapter_id, 'chapter')[0]->total > 0){  

                        $chapter_details[$key]->view_option = 0;
                        $chapter_details[$key]->download_access = 1;
                        $chapter_details[$key]->DownloadAccess = true;
                        $chapter_details[$key]->access_base_text      = "Subscribe";                        
                        $chapter_details[$key]->content_download_type = 'P';
                        $chapter_details[$key]->terms_popup           = true;
                    }
                }

				//---------------------------------------------------------------------
				// Access Denail Report
				// Check If User has Access but on this EbookVolume
					$this->AddAccessDenail($request,$DownloadAccess,$ebook_volume_id);
				//---------------------------------------------------------------------

				if (session()->has('user_id')) {
					$checkIfMarked = MarkList::checkIfMarked(2, $chapter->nid, session()->get('user_id'));
					if (!empty($checkIfMarked)) {
						$checkIfMarked = true;
					}

				}
				$chapter_details[$key]->checkIfMarked = $checkIfMarked;
                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $chapter_details[$key]->terms_popup   = false;
				/*----------------------------------------------------------------------*/
				$AuthorNames     = '';
				$chapter_authors = Author::GetAuthorsByContentId($chapter->chapter_id, 'chapter_id');
				
				if (!empty($chapter_authors)) 
				{
					$AuthorNames = '';
					foreach ($chapter_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;
				}

				$chapter_details[$a]->authors          = $AuthorNames;
				$chapter_details->items()[$a]->authors = $AuthorNames;
				$a++;
			}

		  
			if (isset($request->page_name)) 
			{

                if ($request->page_name==='subscribe') {

                    $template = 'ebook.ebook_volume_details';
                    $page     = 'ebook_volume';  

                }

			} 
			else 
			{
				$template = 'ebook.ebook_volume_details';
				$page     = 'ebook_volume';
			}
			
			$view_pdf = 0;

			if ($type === 'readebookpdf')
			{
                if($DownloadAccess){
                    $page     = $request->page_name;
                    $template = 'ebook.ebook_volume_related';                
    				$view_pdf = 1;
                }else{
                    $template = 'ebook.ebook_volume_details';
                    $page     = 'ebook_volume';
                }
			}
		}


        if ($request->page_name==='related-ebooks' || $request->page_name==='related-journals') {

            $template = 'ebook.ebook_volume_related';
            $page     = $request->page_name;  

        }
		
		if(!isset($template))
		{
			//return abort(403, 'Unauthorized action.');
            $template = 'ebook.ebook_volume_details';
            $page     = 'ebook_volume';
		}
        $user_id   = isset(Auth::user()->id) ? Auth::user()->id : session()->get('user_id');
        if($user_id) 
        {  
            if(empty($content_download_type))
                {
                  $content_download_type='D';
                }

            $add_investigation = array(
                'user_id'               => $user_id,
                'ebook_id'              => $ebook_volume_details[0]->ebk_ebook_id,
                'volume_id'             => $ebook_volume_details[0]->ebk_vol_id,
                'ip_address'            => ip2long(\Request::ip()),
                'content_download_type' => $content_download_type,
                'investigation_type'    => 1,
            );

            $this->AddAccessInvestigation($request,$add_investigation);
        }  

        
        
        $authors = Author::getAuthorDataById($request->id, 'ebook_volume_id');

                /*-----------By Jalil Sahib Instruction------------
                Email Subject: Fwd: Changes Suggested on Eurekaselecet
                Dated: From Mohammad Azhar on 2022-02-08 18:01
                --------------------------------------------------*/
                $terms_popup = false;
                
        return view($template, with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'authors' => $authors,
            'ebook' => $ebook,
            'ebooks' => $ebooks,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist,
            'related_ebook' => $related_ebook,
            'related_journal' => $related_journal,
            'year' => $year,
            'discount' => $discount,
            'page' => $page,
            'DownloadAccess' => $DownloadAccess,
            'vol_type' => $vol_type,
            'vol_access_base_text' => $vol_access_base_text,
            'VolumeDownloadAccess' => $VolumeDownloadAccess,
            'ViewOption'    =>  $ViewOption,
            'content_download_type' => $content_download_type,
            'restricted_user_access_key' => $restricted_user_access_key,
            'user_access_id' => $user_access_id,
            'access_base_text' => $access_base_text,
            'download_access_data' => $download_access_data,
            'terms_popup' => $terms_popup,
            'restricted_user_access_type' => $restricted_user_access_type,
            'view_pdf' => $view_pdf,
            'eparam' => $eparam,
			'rparam' => $rparam,
            'bundle_content' => $bundle_content]));
    }

    public function EbookOrderForm(Request $request)
    {   
        $ajax = $request->get('ajax');
        if ($ajax == true) {
            return $this->validate_promo_code($request);
        } else {
            //Create object of ebook Form  // path: App/Classes/EbookForm

            $ebook_volume_details     = array();
            $CountMultipleVolumeExist = 0;
            $subject_ebooks=array();
            $subject_journals=array();
            $promo_code = isset($request->promo_code) ? $request->promo_code : '';

            $year                 = Journal::GetYear();
            $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
            $ebook_volume_id      = $request->ebook_volume_id;

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);

            // Get Volume Level Content Access (Single Row Query)
            $ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
            $ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

            $param['ebook_volume_id'] = $request->ebook_volume_id;
            $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

            if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
                $ebook = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
                // $subject_ebooks = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                // $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                $country = Country::GetCountryList();
            }

            $discount = $this->getDiscount($ebook_volume_details);

            return view('form.form_ebook_order', with(['ebook_volume_details' => $ebook_volume_details,
                'chapter_details' => $chapter_details,
                'ebook' => $ebook,
                'CountMultipleVolumeExist' => $CountMultipleVolumeExist,
                'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                'year' => $year,
                'country' => $country,
                'ebk_vol_access' => $ebk_vol_access,
                'discount' => $discount,
                'promo_code' => $promo_code]));
        }
    }

    public function EbookOrderFormPreview(Request $request)
    {
		$ajax = $request->get('ajax');
        if ($ajax == true) 
		{
            return $this->validate_promo_code($request);
        } 
		else 
		{
			$validator = Validator::make($request->all(),
			[
				'name'     => 'required',
				'email'  => 'required|string|email|max:255',
				'city'     => 'required',
				'country'  => 'required',
				'org_name' => 'required',
                'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.']);

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

				$year                 = Journal::GetYear();
				$ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
				$ebook_volume_id      = $request->ebook_volume_id;
				// Get Volume Level Content Access (Single Row Query)
				$ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
				$ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

				// $chapter_details = Chapter::where('ebook_volume_id',$request->id);

				$param['ebook_volume_id'] = $request->ebook_volume_id;
				$chapter_details          = Chapter::GetChapterListByEbookVolume($param);

				if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
					$ebook = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
					// $subject_ebooks = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
					// $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
					$country = Country::GetCountryList();
				}

				$preview['name']              = $request->name;
				$preview['email']             = $request->email;
				$preview['phone']             = $request->phone;
				$preview['country']           = $request->country[0];
				$preview['city']              = $request->city;
				$preview['zip']               = $request->zip;
				$preview['organization_name'] = $request->org_name;
				$preview['organization_ips']  = $request->org_ip;
				$preview['address']           = $request->address;
				$preview['comments']          = $request->comments;
				$preview['promo_code']        = $request->promo_code;

				$promo_details = $this->validate_promocode($preview['promo_code'], '');

                $validate_promocode = $this->validate_promo_code($request);

                //dd($validate_promocode->original[0]); die;

				$preview['total_amount'] = $total_print_amount = $multi_user_price = round(($ebook_volume_details[0]->ebook_price * 4));

				if (!empty($promo_details) && $validate_promocode->original[0] == true) {
					$preview['discount_percentage'] = $promo_details->discount;
					$discount                       = $this->getDiscount($ebook_volume_details);
					$discount_rate                  = (($total_print_amount * $promo_details->discount) / 100);
					$grand_total_print              = ($total_print_amount) - ($discount_rate);
					$preview['discounted_amount']   = $grand_total_print = round($grand_total_print, 2);
					$preview['discounted_amount'] = round($preview['discounted_amount']) ;
				} else {
					$preview['discounted_amount']   = '';
					$discount['total_net_price']    = '';
					$discount['total_net_discount'] = '';
				}
				return view('form.form_ebook_order', with(['ebook_volume_details' => $ebook_volume_details,
                'chapter_details' => $chapter_details,
                'ebook' => $ebook,
                'year' => $year,
                'country' => $country,
                'ebk_vol_access' => $ebk_vol_access,
                'preview' => $preview,
                'discount' => $discount]));
			}
		}
    }

    public function EbookOrderFormSubmit(Request $request)
    {
        $promo_details = '';
        
        $ebook_volume = EbookVolume::where('ebook_volume_id', $request->ebook_volume_id)->select('*')->first();
        $ebook        = Ebook::where('ebook_id', $ebook_volume->ebook_id)->first();

        // $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);

        //=============================================================================================

        $multi_user_price = round(($ebook_volume->ebook_price * 4));

        if (!empty($request->promo_code)) {
            //$promo_details = $this->validate_promocode($request->promo_code, '');
             $validate_promocode = $this->validate_promo_code($request);

            if($validate_promocode->original[0] == true)
            {
                $promo_details = $this->validate_promocode($request->promo_code, '');
            }

        }

        if (isset($promo_details) && !empty($promo_details)) {

            $total_print_amount  = $multi_user_price;
            $discount_rate       = (($total_print_amount * $promo_details->discount) / 100);
            $print_discount_rate = $promo_details->discount;

            $grand_total_print = ($total_print_amount) - ($discount_rate);
            $grand_total_print = round($grand_total_print, 2);
			$grand_total_print = round($grand_total_print);

        } else {
            $grand_total_print = $multi_user_price;
        }

        //=============================================================================================

        $preview['nid']             = $ebook_volume->nid;
        $preview['ebook_volume_id'] = $request->ebook_volume_id;
        $preview['name']            = $request->name;
        $preview['email']           = $request->email;
        $preview['phone']           = $request->phone;
        $preview['book_title']      = $ebook->title;
        $preview['book_eisbn']      = $ebook_volume->eisbn;

        $preview['country'] = $request->country;
        $preview['city']    = $request->city;
        $preview['address'] = $request->address;
        $preview['zip']     = $request->zip;

        $preview['org_name']   = $request->organization_name;
        $preview['ip_address'] = $request->organization_ips;
        $preview['comments']   = $request->comments;

        $preview['actual_amount']   = $multi_user_price;
        $preview['estimated_price'] = $multi_user_price;
        $preview['discount_rate']   = isset($print_discount_rate) ? $print_discount_rate : null;
        $preview['last_updated']    = now();
        $preview['status']          = 'P';

        $preview['remote_ip']       = $request->ip();
        $preview['print_promocode'] = $request->promo_code;

        $ebook        = new Ebook;
        $ebook->table = 'tbl_ebook_order';
        $order_id     = $ebook->insertGetId($preview);

        // Payment With Master Card
        $order_entry = DB::table('tbl_ebook_order')->where('oid', $order_id)->first();
    //-------------------------MIGS Payment (Block Temparay)------------------------------

        $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = 'PO' . $order_id;
        $migs['amount']             = $grand_total_print;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/ebookOrderFormMigsResponse/". $migs['order_id'];  
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/ebookOrderFormMigsResponse/". $migs['order_id'];

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

        return view('migs', with(['migs' => $migs]));
    //-----------------------------------MIGS End-------------------------------
    //--------------------------Paypal Payment - Temparary Add Here-------------------------
/*
        $paypal['paypalEnv']          = env('paypalEnv');
        $paypal['paypalURL']          = env('paypalURL');
        $paypal['business']           = env('email_business', '');
        $paypal['invoice']            = $order_id;
        $paypal['item_name']          = 'Order# MU' . $order_id . ': Multiuser Ebook Order for (' . $ebook->title . ' Volume:' . $ebook_volume->volume_name . ' )';
        $paypal['amount']             = $grand_total_print;
        $paypal['currency_code']      = 'USD';
        $paypal['paypalClientID']     = env('paypalClientID');
        $paypal['return']             = url("/ebookOrderPaypalResponse/");

        return view('paypal', with(['paypal' => $paypal]));
        */
    //--------------------------Paypal Payment - End Here-------------------------------
    }
	
	public function EbookOrderFormUpdate($request,$o_entry,$pay_method)
	{  
		$user = User::where('name','MultiuserOrder')->first();
		if (isset($user->id))
		{
			// Add New Order
			$new_order['uid'] = $user->id;
			$new_order['order_status'] = 'compeleted';
			$new_order['primary_email'] = $user->email;
			$new_order['order_total'] = $o_entry->estimated_price;
			$new_order['payment_method'] = $pay_method;
			$new_order['created'] = time();
			$new_order['modified'] = time();
			$order_id = Orders::CreateOrder($new_order);
			
			// Add Product 
			$porder['order_id'] = $order_id;
			$porder['nid'] = $o_entry->nid;
			$porder['title'] = "MU#".$o_entry->oid.":".$o_entry->book_title;
			$porder['model'] = "";
			$porder['qty'] = 1;
			$porder['price'] = $o_entry->estimated_price;
			Orders::AddProducts($porder);
			
			
			if ($pay_method == 'migs')
			{
				$update_order['response_message'] = 'Master Card Successfully Done';
			}

			if ($pay_method == 'paypal')
			{
				$update_order['response_message'] = 'Paypal Payment Successfully Done - '.$request->transaction_no;
			}
			
			
			// Update Ebook Order
			$update_order['order_id'] = $order_id;
			$update_order['estimated_price'] = $o_entry->estimated_price;
			$update_order['last_updated'] = now();
			$update_order['status'] = 'C';
			$update_order['response_code'] = 0;
			
			EbookVolume::UpdateEbookOrder($o_entry->oid,$update_order);
		
		}
    }  	

    public function EbookOrderFormMigsResponse(Request $request)
    {
        $oid = substr($request->order_id, 2, strlen($request->order_id));

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

        $o_entry = EbookVolume::GetEbookOrder($oid);

        $ebook_volume_details = array();

        $year         = Journal::GetYear();
        $ebook_volume = EbookVolume::GetEbookVolumeAndAuthorsById($o_entry->ebook_volume_id)->first();

        $ebook_volume_details[0] = $ebook_volume;

        $param['ebook_volume_id'] = $o_entry->ebook_volume_id;
        $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $o_entry->ebook_volume_id);


        if ($ebook_volume->ebk_ebook_id > 1) 
        {
            $ebook            = Ebook::where('ebook_id', $ebook_volume->ebk_ebook_id)->first();
            $subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume->ebk_ebook_id);
            $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume->ebk_ebook_id);
            $country          = Country::GetCountryList();
        }

        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;
                    $version         = $apiResponse->transaction[$i]->version;
              $cardType        = $apiResponse->sourceOfFunds->type;
                    $orderInfo       = $apiResponse->transaction[$i]->order->id;
                    $receiptNo       = $apiResponse->transaction[$i]->transaction->receipt;
                    $merchantID      = $apiResponse->transaction[$i]->transaction->acquirer->merchantId;
                    $authorizeID     = $apiResponse->transaction[$i]->transaction->authorizationCode;
                    $merchTxnRef     = $apiResponse->transaction[$i]->order->id;
                    $transactionNo   = $apiResponse->transaction[$i]->transaction->acquirer->transactionId;
                    $acqResponseCode = $apiResponse->transaction[$i]->transaction->acquirer->id;
                    $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    $plain_message   = html_entity_decode($apiResponse->transaction[$i]->response->acquirerMessage, ENT_QUOTES, 'UTF-8');
              $result          = $apiResponse->result;
              $status          = $apiResponse->status;


			$detail = $this->EbookOrderFormUpdate($request,$o_entry,'migs');

            $to                 = $o_entry->email;
            $from               = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
            $subject            = "Library / Institutional-User Purchase Order # " . $oid;
            $detail['name']     = $o_entry->name;
            $detail['response'] = true;

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

            $discount   = $this->getDiscount($ebook_volume_details);

            $message[0] = 'mastercard';
            $message[1] = 'Transaction with MasterCard completed successfully';

            $form = 'Library / Institutional-User Purchase Form';

            return view('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
            'discount' => $discount,
            'message' => $message,
            'form' => $form,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));
                }
           }
			}
        }
        else
        {     
            // Update Ebook Order
            $update_order['order_id'] = $oid;
            $update_order['last_updated'] = now();
            $update_order['status'] = 'F';
            $update_order['response_code'] = 'C';
            
            EbookVolume::UpdateEbookOrder($oid,$update_order);

            $discount = $this->getDiscount($ebook_volume_details);

            $paypal['paypalEnv']          = env('paypalEnv');
            $paypal['paypalURL']          = env('paypalURL');
            $paypal['business']           = env('email_business', '');
            $paypal['invoice']            = $o_entry->oid;
            $paypal['item_name']          = 'Order# MU' . $o_entry->oid . ': Multiuser Ebook Order for (' . $o_entry->book_title . ' Volume:' . $o_entry->volume_name . ' )';
            $paypal['amount']             = $o_entry->actual_amount;
            $paypal['currency_code']      = 'USD';
            $paypal['paypalClientID']     = env('paypalClientID');
            $paypal['return']             = url("/ebookOrderPaypalResponse");

            $message[0] = false;
            $message[1] = 'Transaction Failed with MasterCard';

            $form = 'Library / Institutional-User Purchase Form';

            return view('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
/*            'copy' => $copy,
*/            'discount' => $discount,
            'paypal' => $paypal,
            'message' => $message,
            'form' => $form,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));
        }

    }

    public function EbookOrderPaypalResponse(Request $request)
    {  
        $o_entry = EbookVolume::GetEbookOrder($request->invoice);

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

        if($paymentCheck && $paymentCheck->state == 'approved')
        {
            // Paypal Payment Done Successfully
            $response   = true;
            $message[0] = true;
            $message[1] = 'Transaction with Paypal completed successfully';
            $request->request->add(['transaction_no' => $paymentCheck->transactions[0]->related_resources[0]->sale->id]);
			$detail = $this->EbookOrderFormUpdate($request,$o_entry,'paypal');
			
            $to                 = $o_entry->email;
            $from               = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
            $subject            = "Library / Institutional-User Purchase Order # " . $o_entry->oid;
            $detail['name']     = $o_entry->name;
            $detail['response'] = true;

            SendSmtpMail('email_template.ebook_order', $detail, $to, $from, $subject, 'Admin', $cc);
        } 
        else 
        {
            // Paypal Payment Failed
            $response   = false;
            $message[0] = false;
            $message[1] = 'Transaction Failed with Paypal';

            $to                 = $o_entry->email;
            $from               = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2');
            $subject            = "Library / Institutional-User Purchase Order # " . $o_entry->oid;
            $detail['name']     = $o_entry->name;
            $detail['response'] = false;

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

        $ebook_volume_details = array();

        $year         = Journal::GetYear();
        $ebook_volume = EbookVolume::GetEbookVolumeAndAuthorsById($o_entry->ebook_volume_id)->first();

        $ebook_volume_details[0] = $ebook_volume;

        $param['ebook_volume_id'] = $o_entry->ebook_volume_id;
        $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $o_entry->ebook_volume_id);

        if ($ebook_volume->ebk_ebook_id > 1) {
            $ebook            = Ebook::where('ebook_id', $ebook_volume->ebk_ebook_id)->first();
            $subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume->ebk_ebook_id);
            $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume->ebk_ebook_id);
            $country          = Country::GetCountryList();
        }

        $discount = $this->getDiscount($ebook_volume_details);

        $form = 'Library / Institutional-User Purchase Form';

        return View::make('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
        'chapter_details' => $chapter_details,
        'ebook' => $ebook,
        'subject_ebooks' => $subject_ebooks,
        'subject_journals' => $subject_journals,
        'year' => $year,
        'country' => $country,
        // 'copy' => $copy,
        'discount' => $discount,
        'message' => $message,
        'form' => $form,
        'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));

    }

    public function OrderPrintVersion(Request $request)
    {
        $ajax       = $request->get('ajax');
        $promo_code = isset($request->promo_code) ? $request->promo_code : '';

        // validation Promo from ajax request
        if ($ajax == true) {

            return $this->validate_promo_code($request);  

        } else {

            $ebook_volume_details     = array();
            $CountMultipleVolumeExist = 0;

            $year                 = Journal::GetYear();
            $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
            $ebook_volume_id      = $request->ebook_volume_id;

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);

            // Get Volume Level Content Access (Single Row Query)
            $ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
            $ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

            // $chapter_details = Chapter::where('ebook_volume_id',$request->id);

            $param['ebook_volume_id'] = $request->id;
            $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

            if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
                $ebook            = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
                $subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                $country          = Country::GetCountryList();
            }

            $copy = $request->copy;

            $discount = $this->getDiscount($ebook_volume_details);

            return view('form.form_order_print_version', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
            'ebk_vol_access' => $ebk_vol_access,
            'copy' => $copy,
            'discount' => $discount,
            'promo_code' => $promo_code]));
        }
    }

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

		 // validation Promo from ajax request
        if ($ajax == true) {

            return $this->validate_promo_code($request);  

        } else {
			$messages = [
				'email.email' => 'The billing email must be a valid email address.',
				'semail.email' => 'The shipping email must be a valid email address.',
			];
			
			$validator = Validator::make($request->all(),
			[

				'fname'  => 'required',
				'lname'  => 'required',
				'email'  => 'required|string|email|max:255',
				'sfname' => 'required',
				'slname' => 'required',
				'semail' => 'required|string|email|max:255',
                'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.'],$messages);
			
			 $ebook_volume_details = array();

			$year                 = Journal::GetYear();
			$ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
			$ebook_volume_id      = $request->ebook_volume_id;

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $request->ebook_volume_id);

			// Get Volume Level Content Access (Single Row Query)
			$ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
			$ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

			// $chapter_details = Chapter::where('ebook_volume_id',$request->id);

			$param['ebook_volume_id'] = $request->ebook_volume_id;
			$chapter_details          = Chapter::GetChapterListByEbookVolume($param);

			if ($ebook_volume_details[0]->ebk_ebook_id > 1) 
			{
				$ebook            = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
				$subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
				$subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
				$country          = Country::GetCountryList();
			}

			if ($validator->fails()) 
			{
				$copy = $request->copy;
				$discount = $this->getDiscount($ebook_volume_details);
				return view('form.form_order_print_version', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
            'ebk_vol_access' => $ebk_vol_access,
            'copy' => $copy,
            'discount' => $discount,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist]))->withErrors($validator);
            } 
			else 
			{
				$result = $this->GetOrderPrintVersionPreview($ebook, $ebook_volume_details, $request);

				$preview_billing  = $result[0];
				$preview_shipping = $result[1];
				$discount         = $result[2];
				$copy = $request->copy;
                
				return view('form.form_order_print_version', with(['ebook_volume_details' => $ebook_volume_details,
                'chapter_details' => $chapter_details,
                'ebook' => $ebook,
                'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                'year' => $year,
                'country' => $country,
                'ebk_vol_access' => $ebk_vol_access,
                'preview_billing' => $preview_billing,
                'preview_shipping' => $preview_shipping,
                'copy' => $copy,
                'discount' => $discount,
                'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));

			}
		}

    }

    public function OrderPrintVersionSubmit(Request $request)
    {  

        $ebook_volume = EbookVolume::where('ebook_volume_id', $request->ebook_volume_id)->first();
        $ebook        = Ebook::where('ebook_id', $ebook_volume->ebook_id)->first();

        $print_order['nid']        = $ebook_volume->nid;
        $print_order['ebook_volume_id']        = $ebook_volume->ebook_volume_id;
        $print_order['book_title'] = $ebook->title;
        $print_order['book_eisbn'] = $ebook_volume->eisbn;

        $print_order['print_copies'] = $request->billing_print_copies;
        $print_order['fname']        = $request->billing_fname;
        $print_order['lname']        = $request->billing_lname;
        $print_order['address']      = addslashes($request->billing_address);
        $print_order['city']         = $request->billing_city;
        $print_order['state']        = $request->billing_state;
        $print_order['zip_code']     = $request->billing_zip;
        $print_order['country']      = $request->billing_country;
        $print_order['phone']        = $request->billing_phone;
        $print_order['email']        = $request->billing_email;

        $print_order['sfname']    = $request->shipping_fname;
        $print_order['slname']    = $request->shipping_lname;
        $print_order['saddress']  = addslashes($request->shipping_address);
        $print_order['scity']     = $request->shipping_city;
        $print_order['sstate']    = $request->shipping_state;
        $print_order['szip_code'] = $request->shipping_zip;
        $print_order['scountry']  = $request->shipping_country;
        $print_order['sphone']    = $request->shipping_phone;
        $print_order['semail']    = $request->shipping_email;

        $print_order['comments']        = $request->shipping_comments;
        $print_order['last_updated']    = now();
        $print_order['status']          = 'P';
        $print_order['amount']          = $request->billing_total_amount;
        $print_order['shipment_amount'] = $request->billing_shipment_price;
        $print_order['order_type']      = $request->billing_order_type;

        if (!empty($request->billing_discount_rate) && $request->billing_discount_rate > 0) {
            $print_order['discount_rate'] = $request->billing_discount_rate;
        } else {
            $print_order['discount_rate'] = 0;
        }
        $print_order['actual_amount']   = $request->billing_ebook_actual_price;
        $print_order['print_promocode'] = $request->billing_promo_code;

        $copy = $request->billing_print_copies;

        $ebook                = new Ebook;
        $ebook->table         = 'tbl_ebook_print_order';
        $ebook_print_order_id = $ebook->insertGetId($print_order);

		$po_entry = EbookVolume::GetEbookPrintOrder($ebook_print_order_id);
		
        if ($copy == "More than 5") //More than 5
        {
            $to      = $request->billing_email;
            $from    = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
            $subject = " Order No# " . $ebook_print_order_id;

            SendSmtpMail('email_template.print_order_morethenfive', $print_order, $to, $from, $subject, 'Admin', $cc);

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

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


            $ebook_volume_details = array();

            $year         = Journal::GetYear();
            $ebook_volume = EbookVolume::GetEbookVolumeAndAuthorsById($po_entry->ebook_volume_id)->first();

            $ebook_volume_details[0] = $ebook_volume;

            $param['ebook_volume_id'] = $po_entry->ebook_volume_id;
            $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $po_entry->ebook_volume_id);

            if ($ebook_volume->ebk_ebook_id > 1) {
                $ebook            = Ebook::where('ebook_id', $ebook_volume->ebk_ebook_id)->first();
                $subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume->ebk_ebook_id);
                $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume->ebk_ebook_id);
                $country          = Country::GetCountryList();
            }

            $discount   = $this->getDiscount($ebook_volume_details);
            $message[0] = 'mastercard';
            $message[1] = 'Thanks for Submission';
			
			$form = 'eBook Print-on-Demand Order';

            return view('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
             'chapter_details' => $chapter_details,
              'ebook' => $ebook,
               'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                 'year' => $year,
                  'country' => $country,
                   'copy' => $copy,
                    'discount' => $discount,
                     'message' => $message,
                     'form' => $form,
                      'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));

        } 
		else 
		{
//----------------------------MIGS Payment (Block Temparay)---------------------------------------
        $migs['merchat_id']         = env('migs_id');
        $migs['order_id']           = 'PO' . $po_entry->poid;
        $migs['amount']             = $po_entry->amount;
        $migs['currency_code']      = 'USD';
        $migs['return_url']         = "http://".$_SERVER['HTTP_HOST']."/orderPrintVersionMigsResponse/". $migs['order_id'];  
        $migs['cancel_url']         = "http://".$_SERVER['HTTP_HOST']."/orderPrintVersionMigsResponse/". $migs['order_id'];

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

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

//-----------------------------------MIGS End-------------------------------
    //--------------------------Paypal Payment - Temparary Add Here-------------------------------
    /*        $paypal['paypalEnv']          = env('paypalEnv');
            $paypal['paypalURL']          = env('paypalURL');
            $paypal['business']           = env('email_business', '');
            $paypal['invoice']            = $po_entry->poid;
            $paypal['item_name']          = 'Order# PO' . $po_entry->poid . ': E Book Print Version for (' . $po_entry->book_title . ' Volume:' . $po_entry->volume_name . ' )';
            $paypal['amount']             = $po_entry->amount;
            $paypal['currency_code']      = 'USD';
            $paypal['paypalClientID']     = env('paypalClientID');
            $paypal['return']             = url("/ebookPrintVersionPaypalResponse");

            return view('paypal', with(['paypal' => $paypal]));
      */  //--------------------------Paypal Payment - End Here-------------------------------
        }

    }
	
	public function OrderPrintVersionUpdate($request,$po_entry,$pay_method)
    {  
        $user = User::getUserByName("PrintOrder");

        $order_data['uid']           = $user->id;
        $order_data['order_status']  = 'completed';
        $order_data['order_total']   = 0;
        $order_data['primary_email'] = $user->email;
        $order_data['created']       = time();
        $order_data['modified']      = time();
		$order_data['payment_method']= $pay_method;
		
        $order_id = Orders::CreateOrder($order_data);
        
		if ($pay_method == 'migs')
		{
            $migs_obj = new MigsController;
            $apiResponse = $migs_obj->TransactionMigsResponse($request->order_id);

            $update_po_entry['amount'] = $apiResponse->transaction[0]->transaction->amount;
			$update_po_entry['response_message'] = 'Master Card Successfully Done';
		}
		
		if ($pay_method == 'paypal')
		{
            $paypal_obj = new PaypalExpress;
            $paymentID = $request->paymentID;
            $token = $request->token;
            $payerID = $request->payerID;
            $productID = $request->invoice;
            // Validate transaction via PayPal API
            $paymentCheck = $paypal_obj->PaypalValidate($paymentID, $token, $payerID, $productID);

			$update_po_entry['amount']       = $paymentCheck->transactions[0]->amount->total;	
			$update_po_entry['response_message'] = 'Paypal Payment Successfully Done - '.$paymentCheck->transactions[0]->related_resources[0]->sale->id;
		}
	
        $update_po_entry['last_updated']     = now();
        $update_po_entry['status']           = 'C';
        $update_po_entry['response_code']    = 0;
        
        $update_po_entry['order_id']         = $order_id;

        DB::table('tbl_ebook_print_order')->where('poid', $po_entry->poid)->update($update_po_entry);

        return $user;
    }
	

    public function OrderPrintVersionMigsResponse(Request $request)
    {  
        $poid = substr($request->order_id, 2, strlen($request->order_id));
        $migs_obj = new MigsController;
        $apiResponse = $migs_obj->TransactionMigsResponse($request->order_id);
		
		$po_entry = EbookVolume::GetEbookPrintOrder($poid);

		$ebook_volume_details = array();

		$year         = Journal::GetYear();
		$ebook_volume = EbookVolume::GetEbookVolumeAndAuthorsById($po_entry->ebook_volume_id)->first();

		$ebook_volume_details[0] = $ebook_volume;

		$param['ebook_volume_id'] = $po_entry->ebook_volume_id;
		$chapter_details          = Chapter::GetChapterListByEbookVolume($param);
		
		if ($ebook_volume->ebk_ebook_id > 1) 
		{
			$ebook            = Ebook::where('ebook_id', $ebook_volume->ebk_ebook_id)->first();
			$subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume->ebk_ebook_id);
			$subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume->ebk_ebook_id);
			$country          = Country::GetCountryList();
			$CountMultipleVolumeExist = 0;
			$CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume->ebk_ebook_id, $po_entry->ebook_volume_id);
		}

        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;
                    $version         = $apiResponse->transaction[$i]->version;
              $cardType        = $apiResponse->sourceOfFunds->type;
                    $orderInfo       = $apiResponse->transaction[$i]->order->id;
                    $receiptNo       = $apiResponse->transaction[$i]->transaction->receipt;
                    $merchantID      = $apiResponse->transaction[$i]->transaction->acquirer->merchantId;
                    $authorizeID     = $apiResponse->transaction[$i]->transaction->authorizationCode;
                    $merchTxnRef     = $apiResponse->transaction[$i]->order->id;
                    $transactionNo   = $apiResponse->transaction[$i]->transaction->acquirer->transactionId;
                    $acqResponseCode = $apiResponse->transaction[$i]->transaction->acquirer->id;
                    $txnResponseCode = html_entity_decode($apiResponse->transaction[$i]->response->acquirerCode, ENT_QUOTES, 'UTF-8');
                    $plain_message   = html_entity_decode($apiResponse->transaction[$i]->response->acquirerMessage, ENT_QUOTES, 'UTF-8');
              $result          = $apiResponse->result;
              $status          = $apiResponse->status;


			$user = $this->OrderPrintVersionUpdate($request,$po_entry,'migs');
			
            $to             = $po_entry->email;
            $from           = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
            $subject        = "eBook Print-on-Demand Order # " . $poid;
            $detail['name'] = $po_entry->fname . ' ' . $po_entry->lname;
			$detail['book_title'] = $po_entry->book_title;
            $detail['book_eisbn'] = $po_entry->book_eisbn;
            $detail['ebook_volume_id'] = $po_entry->ebook_volume_id;

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

            $discount   = $this->getDiscount($ebook_volume_details);
            $message[0] = 'mastercard';
            $message[1] = 'Transaction with MasterCard completed successfully';

            $form = 'eBook Print-on-Demand Order';

            return view('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
            'discount' => $discount,
            'message' => $message,
            'form' => $form,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));
            }
           } 
			}
        } 
        else
		{
            $update_order['order_id'] = $poid;
            $update_order['last_updated'] = now();
            $update_order['status'] = 'F';
            $update_order['response_code'] = 'C';
            
            DB::table('tbl_ebook_print_order')->where('poid', $poid)->update($update_order);
          
			$discount  = $this->getDiscount($ebook_volume_details);

			//define(__HASH_KEY__,$key = 'UR3K@AXEidE-EIA32D35F7-432-234323DGeD5eL3cT');

			$ebook_print_order_entry = DB::table('tbl_ebook_print_order')->where('poid', $po_entry->poid)->first();

            $paypal['paypalEnv']          = env('paypalEnv');
            $paypal['paypalURL']          = env('paypalURL');
            $paypal['business']           = env('email_business', '');
            $paypal['invoice']            = $po_entry->poid;
            $paypal['item_name']          = 'Order# PO' . $po_entry->poid . ': E Book Print Version for (' . $po_entry->book_title . ' Volume:' . $po_entry->volume_name . ' )';
            $paypal['amount']             = $po_entry->amount;
            $paypal['currency_code']      = 'USD';
            $paypal['paypalClientID']     = env('paypalClientID');
            $paypal['return']             = url("/ebookPrintVersionPaypalResponse");


			// Test or Local Server Paypal Response URL
			//$paypal['return']        = 'http://newjms.eurekaselect.com/paypal_response';
			//$paypal['cancel_return'] = 'http://newjms.eurekaselect.com/paypal_response';

			$message[0] = false;
			$message[1] = 'Transaction Failed with MasterCard';
			
			$form = 'eBook Print-on-Demand Order';

			return view('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
            'chapter_details' => $chapter_details,
            'ebook' => $ebook,
            'subject_ebooks' => $subject_ebooks,
            'subject_journals' => $subject_journals,
            'year' => $year,
            'country' => $country,
            'discount' => $discount,
            'paypal' => $paypal,
            'message' => $message,
            'form' => $form,
            'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));

        }
    }

    public function OrderPrintVersionPaypalResponse(Request $request)
    {
        
        $po_entry = EbookVolume::GetEbookPrintOrder($request->invoice);

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

        // If the payment is valid and approved
        if($paymentCheck && $paymentCheck->state == 'approved')
        {
            $request->request->add(['transaction_no' => $paymentCheck->transactions[0]->related_resources[0]->sale->id]);
            $user = $this->OrderPrintVersionUpdate($request,$po_entry,'paypal');

            // Paypal Payment Done Successfully
            $response   = true;
            $message[0] = true;
            $message[1] = 'Transaction with Paypal completed successfully';

            $to             = $po_entry->email;
            $from           = env('email_admin', '');
            $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
            $subject        = "eBook Print-on-Demand Order # " . $po_entry->poid;
            $detail['name'] = $po_entry->fname . ' ' . $po_entry->lname;
			$detail['book_title'] = $po_entry->book_title;
            $detail['book_eisbn'] = $po_entry->book_eisbn;
			$detail['ebook_volume_id'] = $po_entry->ebook_volume_id;

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

        } else {
            // Paypal Payment Failed
            $response   = false;
            $message[0] = false;
            $message[1] = 'Transaction Failed with Paypal';

        }

        $ebook_volume_details = array();

        $year         = Journal::GetYear();
        $ebook_volume = EbookVolume::GetEbookVolumeAndAuthorsById($po_entry->ebook_volume_id)->first();

        $ebook_volume_details[0] = $ebook_volume;

        $param['ebook_volume_id'] = $po_entry->ebook_volume_id;
        $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $po_entry->ebook_volume_id);

        if ($ebook_volume->ebk_ebook_id > 1) {
            $ebook            = Ebook::where('ebook_id', $ebook_volume->ebk_ebook_id)->first();
            $subject_ebooks   = Subject::RelatedeBookBySubjectId($ebook_volume->ebk_ebook_id);
            $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume->ebk_ebook_id);
            $country          = Country::GetCountryList();
        }

        $discount = $this->getDiscount($ebook_volume_details);
		
		$form = 'eBook Print-on-Demand Order';

        return View::make('form.form_payment_response', with(['ebook_volume_details' => $ebook_volume_details,
                'chapter_details' => $chapter_details,
                'ebook' => $ebook,
                'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                'year' => $year,
                'country' => $country,
                'discount' => $discount,
                'message' => $message,
                'form' => $form,
                'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));


    }
	
	
	
	

    public function EbookPreOrderForm(Request $request)
    {
        $subject_ebooks=array();
        $subject_journals=array();
        $content_download_type      = '';
        $restricted_user_access_key='';
        $user_access_id=0;


        $ajax = $request->get('ajax');
        if ($ajax == true) {
            return $this->validate_promo_code($request);
        } else {
            //Create object of ebook Form  // path: App/Classes/EbookForm

            $ebook_volume_details = array();

            $year                 = Journal::GetYear();
            $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
            $ebook_volume_id      = $request->ebook_volume_id;

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);

            // Get Volume Level Content Access (Single Row Query)
            $ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
            $ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

            $param['ebook_volume_id'] = $request->ebook_volume_id;
            $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

            if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
                $ebook = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
                // $subject_ebooks = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                // $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                $country = Country::GetCountryList();
            }

            $discount = $this->getDiscount($ebook_volume_details);
            $authors = Author::getAuthorDataById($request->ebook_volume_id, 'ebook_volume_id');

            return view('form.form_pre_order', with(['ebook_volume_details' => $ebook_volume_details,
                'chapter_details' => $chapter_details,
                'authors' => $authors,
                'ebook' => $ebook,
                'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                'year' => $year,
                'country' => $country,
                'ebk_vol_access' => $ebk_vol_access,
                'discount' => $discount,
                'user_access_id' => $user_access_id,
                'restricted_user_access_key' =>  $restricted_user_access_key,
                'content_download_type' => $content_download_type,
                'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));
        }
    }

    public function EbookPreOrderPreview(Request $request)
    {   
        $subject_ebooks=array();
        $subject_journals=array();
        $content_download_type='';
        $restricted_user_access_key='';
        $user_access_id='';

        $validator = Validator::make($request->all(),
            [
                'first_name'           => 'required',
                'last_name'            => 'required',
                'email'                => 'required|string|email|max:255',
                'title'                => 'required',
                'order_type'           => 'required',
                'country'              => 'required',
                'city'                 => 'required',
                'address'              => 'required',
                'no_of_copies'         => 'required_if:order_type,Print Version',
                'captcha' => 'required|captcha'], 
            ['captcha.captcha' => 'Invalid captcha code.']);


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

            $ebook_volume_details = array();

            $year                 = Journal::GetYear();
            $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
            $ebook_volume_id      = $request->ebook_volume_id;

            // Get Volume Level Content Access (Single Row Query)
            $ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
            $ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

            $param['ebook_volume_id'] = $request->ebook_volume_id;
            $chapter_details          = Chapter::GetChapterListByEbookVolume($param);

            if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
                $ebook = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
                // $subject_ebooks = Subject::RelatedeBookBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                // $subject_journals = Subject::RelatedeBookJournalBySubjectId($ebook_volume_details[0]->ebk_ebook_id);
                $country = Country::GetCountryList();
            }

            $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);


            $discount = $this->getDiscount($ebook_volume_details);

            $preview["first_name"] = $request->first_name;
            $preview["last_name"]  = $request->last_name;
            $preview["email"]      = $request->email;

            $preview["title"]         = $request->title;
            $preview["user_category"] = $request->user_category;
            $preview["order_type"]    = $request->order_type;

            $preview["country"] = $request->country;
            $preview["city"]    = $request->city;
            $preview["state"]   = $request->state;

            $preview["phone"] = $request->phone;
            $preview["fax"]   = $request->fax;
            $preview["zip"]   = $request->zip;

            $preview["org_name"]     = $request->org_name;
            $preview["address"]      = $request->address;
            $preview["comments"]     = $request->comments;
            $preview["no_of_copies"] = $request->no_of_copies;

            $authors = Author::getAuthorDataById($ebook_volume_id, 'ebook_volume_id');

            return view('form.form_pre_order', with(['ebook_volume_details' => $ebook_volume_details,
                'preview' => $preview,
                'chapter_details' => $chapter_details,
                'ebook' => $ebook,
                'authors' => $authors,
                'subject_ebooks' => $subject_ebooks,
                'subject_journals' => $subject_journals,
                'year' => $year,
                'country' => $country,
                'ebk_vol_access' => $ebk_vol_access,
                'discount' => $discount,
                'content_download_type' => $content_download_type,
                'restricted_user_access_key' => $restricted_user_access_key,
                'user_access_id' => $user_access_id,
                'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));
        }

    }

    public function EbookPreOrderSubmit(Request $request)
    {

        $year                 = Journal::GetYear();
        $ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($request->ebook_volume_id);
        $ebook_volume_id      = $request->ebook_volume_id;
		
		// Get Volume Level Content Access (Single Row Query)
		$ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access", $ebook_volume_id, "v");
		$ebk_vol_access = $content_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : null;

		$param['ebook_volume_id'] = $request->ebook_volume_id;
		$chapter_details          = Chapter::GetChapterListByEbookVolume($param);


        if ($ebook_volume_details[0]->ebk_ebook_id > 1) {
            $ebook   = Ebook::where('ebook_id', $ebook_volume_details[0]->ebk_ebook_id)->first();
            $country = Country::GetCountryList();
        }
		
		$CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_volume_details[0]->ebk_ebook_id, $ebook_volume_id);

        $pre_order_data["first_name"] = $request->first_name;
        $pre_order_data["last_name"]  = $request->last_name;
        $pre_order_data["email"]      = $request->email;

        $pre_order_data["title"]         = $request->title;
        $pre_order_data["user_category"] = $request->user_category;
        $pre_order_data["order_type"]    = $request->order_type;

        $pre_order_data["country"]  = $request->country;
        $pre_order_data["city"]     = $request->city;
        $pre_order_data["province"] = $request->state;

        $pre_order_data["phone"] = $request->phone;
        $pre_order_data["fax"]   = $request->fax;
        $pre_order_data["zip"]   = $request->zip;

        $pre_order_data["organization_name"] = $request->org_name;
        $pre_order_data["address"]           = $request->address;
        $pre_order_data["comment"]           = $request->comments;

        $pre_order_data["volume_nid"]  = $ebook_volume_details[0]->nid;
        $pre_order_data["ebook_volume_id"]  = $ebook_volume_details[0]->ebook_volume_id;
        $pre_order_data["ebook_type"]  = $ebook_volume_details[0]->ebook_type;
        $pre_order_data["ebook_title"] = $ebook->title;

        if ($request->order_type == "Print Version") {
            $order_type = 'Print Version';
            $pre_order_data["no_of_copies"] = $request->no_of_copies;

        } elseif ($request->order_type == "Electronic Version") {

            $order_type = 'Electronic Version';
            $pre_order_data["no_of_copies"] = 0;
        }

        $pre_order_data["last_updated"] = now();

        $ebook                                = new Ebook;
        $ebook->table                         = 'tbl_ebook_preorders';
        $pre_order_data["ebook_pre_order_id"] = $ebook->insertGetId($pre_order_data);

        $node['reciever'] = $request->first_name;

        if ($ebook_volume_details[0]->ebook_type == 1 && $ebook_volume_details[0]->ebook_status == 2) {
            $text = 'Forthcoming General eBook';
        } elseif ($ebook_volume_details[0]->ebook_type == 2 && $ebook_volume_details[0]->ebook_status == 2) {
            $text = 'Forthcoming Series eBook';
        } elseif ($ebook_volume_details[0]->ebook_type == 2 && $ebook_volume_details[0]->ebook_status == 3) {
            $text = 'Future Series eBook';
        } elseif ($ebook_volume_details[0]->ebook_type == 1 && $ebook_volume_details[0]->ebook_status == 3) {
            $text = 'Future General eBook';
        }

        $pre_order_data["user_category_text"] = $request->user_category;

        $pre_order_data["order_type_text"] = $request->order_type;

        $to      = $request->email;
        $from    = env('email_admin', '');
        $cc      = env('email_xolva_2').','.env('email_support_2').','.env('email_epub');
        $subject = $text . " Order No# " . $pre_order_data["ebook_pre_order_id"];

        SendSmtpMail('email_template.ebook_pre_order', $pre_order_data, $to, $from, $subject, 'Admin', $cc);
		
		return view('form.form_pre_order_thankyou', with(['ebook_volume_details' => $ebook_volume_details,
        'chapter_details' => $chapter_details,
        'ebook' => $ebook,
        'year' => $year,
        'country' => $country,
        'ebk_vol_access' => $ebk_vol_access,
        'CountMultipleVolumeExist' => $CountMultipleVolumeExist]));

        // if ($ebook_volume_details[0]->ebook_type == 1)
		// {
            // return Redirect::to('forthcoming/generalebook/');
        // } else {
            // return Redirect::to('forthcoming/series/');
        // }
    }
	

    public function download_volume_file(Request $request)
    {

        $SecondsGap                 = 30; //default is 30 sec
        $chapter_id                 = '';
        $file_path                  = '';
        $content_download_type      = '';
        $restricted_user_access_key = '';
        $clientIP                   = ip2long($request->ip());
		$user_id                    = isset(Auth::user()->id) ? Auth::user()->id : 0;

        $param = Crypt::decrypt($request->param);
		
        list($ebook_volume_id, $file_type, $content_download_type, $restricted_user_access_key, $user_access_id) = explode("||", $param);
		
		$user_access = UserAccess::where('user_access_id',$user_access_id)->first();
		
        if(!empty($user_access))
		{
			$user_id = $user_access->user_id;
		}
        elseif($user_id == 0)
        {
           $user_id = session()->get('user_id'); 
        }
       
        if ($user_id > 0) 
		{
            $volume_gap = EbookVolume::VolumeDownloadGap($user_id, $ebook_volume_id, $SecondsGap);            

            if ($volume_gap->rcd > 0) {
                $last_session_userid = $request->session()->getId()."-".microtime(true);
                session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_volume set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$volume_gap->id."'");

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

        }
		
        $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->first();

        if ($file_type == 'sample') {
            $download_file_type = 0;
            $investigation_type = 0;
            $file_path          = config('constants.admin.root_path') . 'E-books/BEN/' . $ebook_volume->eisbn . '/' . $ebook_volume->volume_name . '/EBOOK/' . $ebook_volume->sample_file_name;
        }
        if ($file_type == 'pdf') {
            $download_file_type = 1;
            $investigation_type = 2;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->file_name;
        }
        if ($file_type == 'epub') {
            $download_file_type = 3;
            $investigation_type = 4;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.'epub/'.$ebook_volume->epub_file_name;

            if(!file_exists($file_path)){
                $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->epub_file_name;
            }
        }
        if ($file_type == 'prc') {
            $download_file_type = 4;
            $investigation_type = 5;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.'prc/'.$ebook_volume->prc_file_name;
            if(!file_exists($file_path)){
                $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->prc_file_name;
            }
        }
        if ($file_type == 'supp') {
            $download_file_type = 0;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->supplementary_filename;
        }
        if ($file_type == 'video') {
			$investigation_type = 2;
            $download_file_type = 5;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path. $ebook_volume->supplementary_filename;
        }
        if ($file_type == 'flyer') {
            $file_path = config('constants.admin.root_path') . 'images/ebook-flyer/' . $ebook_volume->flyer_link;
        }
		
        if (file_exists($file_path) || $file_type == 'html') 
		{
			
			// check User Access On Article befor Download
			if(!empty($user_access))
			{
				$return = $this->CheckUserAccessOnEbook($request,$ebook_volume,$user_access,$restricted_user_access_key,$content_download_type,$clientIP,$user_id);
				if ($return == false)
				{
					return back();
				}
			}

            if ($file_type != 'supp') 
			{
                if($user_id > 0 && isset($ebook_volume->ebook_volume_id))
                {
                    $this->setUserDownloadSession($request,$user_id);
                    $add_download_count = array(
                        'user_id'               => $user_id,
                        'ebook_id'              => $ebook_volume->ebook_id,
                        'volume_id'             => $ebook_volume->ebook_volume_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'content_download_type' => $content_download_type,
                        'is_agree'              => 1,
                        'download_file_type'    => $download_file_type,
                        //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                        'session_id'            => session()->get('last_session_userid'),
                    );
                    
                    $last_download_count = EbookVolume::AddVolumeDownload($add_download_count);
                    $add_download_count['investigation_type']=$investigation_type;
                    $add_download_count['ip_address']=ip2long(\Request::ip());
                    $last_inv_id = $this->AddAccessInvestigation($request,$add_download_count);

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

                        $add_user_access_chapter = array(
                            'user_access_id'        => $user_access_id,
                            'download_count_id'     => $last_download_count,
                            'investigation_id'      => $last_inv_id,
                            'user_id'               => $user_id,
                            'user_email'            => $request->download_email,
                            'ebook_id'              => $ebook_volume->ebook_id,
                            'ebook_volume_id'       => $ebook_volume->ebook_volume_id,
                            'timestamp'             => time(),
                            'ip_address'            => $request->ip(),
                            'is_agree'              => 1,
                            'download_file_type'    => 1,
                            'content_download_type' => $content_download_type,
                        );

                        UserAccess::AddUserAccessDownloadEbookVolume($add_user_access_chapter);
                    }
                    //-------direct download End-----------
                
                }
            }
            if ($file_type == 'html') 
			{
                return $file_path;
            } else {
                return response()->download($file_path);
            }
        } else {

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

    public function download_volume_bundle_file(Request $request)
    {

        $SecondsGap                 = 30; //default is 30 sec
        $chapter_id                 = '';
        $file_path                  = '';
        $content_download_type      = '';
        $restricted_user_access_key = '';
        $clientIP                   = ip2long($request->ip());

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

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

        if (isset(Auth::user()->id)) {

            $bundle_content = BundleOfferController::BundleOfferUserAccess(Auth::user()->id);
            $volume_gap = EbookVolume::VolumeDownloadGap(Auth::user()->id, $ebook_volume_id, $SecondsGap);            

            if ($volume_gap->rcd > 0) {
                $last_session_userid = $request->session()->getId()."-".microtime(true);
                session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_volume set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$volume_gap->id."'");

                Session::flash('message', " Cannot download, try again after $SecondsGap seconds");
                return back();
            }
            else if ($bundle_content->ebook == 0) {                

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

        }

        $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->first();

        if ($file_type == 'sample') {
            $download_file_type = 0;
            $file_path          = config('constants.admin.root_path') . 'E-books/BEN/' . $ebook_volume->eisbn . '/' . $ebook_volume->volume_name . '/EBOOK/' . $ebook_volume->sample_file_name;
        }
        if ($file_type == 'pdf') {
            $download_file_type = 1;
            $investigation_type = 2;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->file_name;
        }
        if ($file_type == 'epub') {
            $download_file_type = 3;
            $investigation_type = 4;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.'epub/'.$ebook_volume->epub_file_name;
        }
        if ($file_type == 'prc') {
            $download_file_type = 4;
            $investigation_type = 5;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.'prc/'.$ebook_volume->prc_file_name;
        }
        if ($file_type == 'supp') {
            $download_file_type = 0;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->supplementary_filename;
        }
        if ($file_type == 'video') {
            $download_file_type = 5;
            $file_path          = config('constants.admin.root_path').$ebook_volume->file_path. $ebook_volume->supplementary_filename;
        }
        if ($file_type == 'flyer') {
            $file_path = config('constants.admin.root_path') . 'images/ebook-flyer/' . $ebook_volume->flyer_link;
        }

        if (file_exists($file_path) || $file_type == 'html') {
            if ($file_type != 'supp') {
                if(isset(Auth::user()->id) && isset($ebook_volume->ebook_volume_id))
                {
                    $this->setUserDownloadSession($request,Auth::user()->id);
                    $add_download_count = array(
                        'user_id'               => isset(Auth::user()->id) ? Auth::user()->id : 0,
                        'ebook_id'              => $ebook_volume->ebook_id,
                        'volume_id'             => $ebook_volume->ebook_volume_id,
                        'timestamp'             => time(),
                        'ip_address'            => $request->ip(),
                        'content_download_type' => $content_download_type,
                        'is_agree'              => 1,
                        'download_file_type'    => $download_file_type,
                        //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                        'session_id'            => session()->get('last_session_userid'),
                    );
                    EbookVolume::AddVolumeDownload($add_download_count);
                    $add_download_count['investigation_type']=$investigation_type;
                    $this->AddAccessInvestigation($request,$add_download_count);

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

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

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

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

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

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

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

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

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

                if ($gap_res) {

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

                } else {

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

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

                        return $id;
                    }
                }
            }
        }
    }

    public function UploadCoverImage($request, $ebook_volume_id)
    {
        if ($request->hasFile('image_file_name')) {
            $ebook_volume    = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->get();
            $ebook_volume_id = $ebook_volume[0]->ebook_volume_id;
            $eisbn           = $ebook_volume[0]->eisbn;
            $volume_name     = $ebook_volume[0]->volume_name;

            $image_file = $request->file('image_file_name');

            $update_image_file_name['image_file_name'] = $image_file_name = $image_file->getClientOriginalName();

            $ebook_volume_path = $ebook_volume[0]->file_path;
            $file_path         = config('constants.admin.root_path') . $ebook_volume_path;

            if (!is_dir($file_path)) {
                mkdir($file_path, 0755, true);
            }
            $image_file->move($file_path . 'image', $image_file_name);

            EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_image_file_name);

            return array(true, $ebook_volume_id);
        }
    }

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

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

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

                        if ($result == true) {
                            $msg = array(true, 'Promo Code Validate Successfully');
                        } else {
                            $msg = array(false, 'Promo Code Validate Error');
                        }
                    } else {
                        $msg = array(false, 'Promo Code Date Expired');
                    }
                } else {
                    $msg = array(false, 'Promo Code is not Active');
                }
            } else {
                $msg = array(false, 'promo code is incorrect');
            }
        } else {
            $msg = array(false, 'please enter promo code');
        }

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

    public function testpaypalresponse()
    {

        $test = array(
            "payer_email"            => "arshad@xolva.com",
            "payer_id"               => "LQU5PG7USMC4N",
            "payer_status"           => "VERIFIED",
            "first_name"             => "Arshad",
            "last_name"              => "Ekhlaque",
            "address_name"           => "Arshad Ekhlaque",
            "address_street"         => "1 Main St",
            "address_city"           => "San Jose",
            "address_state"          => "CA",
            "address_country_code"   => "US",
            "address_zip"            => "95131",
            "residence_country"      => "US",
            "txn_id"                 => "7H343666BF098314M",
            "mc_currency"            => "USD",
            "mc_fee"                 => "0.33",
            "mc_gross"               => "1.00",
            "protection_eligibility" => "ELIGIBLE",
            "payment_fee"            => "0.33",
            "payment_gross"          => "1.00",
            "payment_status"         => "Completed",
            "payment_type"           => "instant",
            "item_name"              => "Order# PO1900: E Book Print Version for (Test eBook  Volume:8 )",
            "quantity"               => "1",
            "txn_type"               => "web_accept",
            "payment_date"           => "2019-04-29T10:16:47Z",
            "business"               => "arsal-facilitator@xolva.com",
            "receiver_id"            => "B8V7AJPSHF376",
            "notify_version"         => "UNVERSIONED",
            "invoice"                => "1900",
            "verify_sign"            => "AMflWePQZdV0RHg.GLS4Zx7KxMHQAz2kipOWrLF9pM4EjdX8hx2Q57Lc");

        $test2 = array(
            "payer_email"            => "arsal-buyer@xolva.com",
            "payer_id"               => "DY6TZKL9G7SFW",
            "payer_status"           => "VERIFIED",
            "first_name"             => "test",
            "last_name"              => "buyer",
            "address_name"           => "test buyer",
            "address_street"         => "1 Main St",
            "address_city"           => "San Jose",
            "address_state"          => "CA",
            "address_country_code"   => "US",
            "address_zip"            => "95131",
            "residence_country"      => "US",
            "txn_id"                 => "0NY94753BF247942M",
            "mc_currency"            => "USD",
            "mc_fee"                 => "0.33",
            "mc_gross"               => "1.00",
            "protection_eligibility" => "ELIGIBLE",
            "payment_fee"            => "0.33",
            "payment_gross"          => "1.00",
            "payment_status"         => "Completed",
            "payment_type"           => "instant",
            "item_name"              => "Order# PO1901: E Book Print Version for (Test eBook  Volume:8 )",
            "quantity"               => "1",
            "txn_type"               => "web_accept",
            "payment_date"           => "2019-04-30T04:55:13Z",
            "business"               => "arsal-facilitator@xolva.com",
            "receiver_id"            => "B8V7AJPSHF376",
            "notify_version"         => "UNVERSIONED",
            "invoice"                => "1901",
            "verify_sign"            => "ARveBiwHyANMkuk0D1am6Fhek-jTAC5rxHhxdZc.FaYiB5UDrul70fX1");

        return View::make('form.test_paypal_response', with(['test' => 'test', 'test2' => 'test2']));

    }
    public function testmastercardresponse()
    {

        $test = array(

            "Title"                 => "MiGS Transaction",
            "vpc_3DSECI"            => "02",
            "vpc_3DSXID"            => "QtQp2meAhyb4nqKsqNT0+XbVYew=",
            "vpc_3DSenrolled"       => "Y",
            "vpc_3DSstatus"         => "Y",
            "vpc_AVSResultCode"     => "Unsupported",
            "vpc_AcqAVSRespCode"    => "Unsupported",
            "vpc_AcqCSCRespCode"    => "Unsupported",
            "vpc_AcqResponseCode"   => "14",
            "vpc_Amount"            => "100",
            "vpc_BatchNo"           => "20181224",
            "vpc_CSCResultCode"     => "Unsupported",
            "vpc_Card"              => "MC",
            "vpc_Command"           => "pay",
            "vpc_Currency"          => "USD",
            "vpc_Locale"            => "en",
            "vpc_MerchTxnRef"       => "1900",
            "vpc_Merchant"          => "TEST803336000",
            "vpc_Message"           => "Declined",
            "vpc_OrderInfo"         => "PO1984",
            "vpc_ReceiptNo"         => "835815547720",
            "vpc_RiskOverallResult" => "ACC",
            "vpc_SecureHash"        => "C517D1D16A5A96A1949E8EB8BF5B2180BCAC89D5FEF397A4E2702CF4308A1327",
            "vpc_SecureHashType"    => "SHA256",
            "vpc_TransactionNo"     => "2090000102",
            "vpc_TxnResponseCode"   => "0",
            "vpc_VerSecurityLevel"  => "05",
            "vpc_VerStatus"         => "Y",
            "vpc_VerToken"          => "jHyn+7YFi1EUAREAAAAvNUe6Hv8=",
            "vpc_VerType"           => "3DS",
            "vpc_Version"           => "1",
        );

        return View::make('form.test_migs_response', with(['test' => 'test']));
    }

    public function getDiscount($ebook_volume_details)
    {

        if ($ebook_volume_details[0]->ebook_price_podandpdf > 0) {
            $discount['ebook_price_podandpdf'] = $ebook_price_podandpdf = $ebook_volume_details[0]->ebook_price_podandpdf;
            $discount['total_net_price']       = $total_net_price = round($ebook_volume_details[0]->ebook_price + $ebook_volume_details[0]->ebook_price_pod);

            $total_net_discount             = (1 - ($ebook_price_podandpdf / $total_net_price)) * 100;
            $discount['total_net_discount'] = $total_net_discount = round($total_net_discount);
        } else {
            $discount['ebook_price_podandpdf'] = '';
            $discount['total_net_price']       = '';
            $discount['total_net_discount']    = '';
        }
        return $discount;
    }

    public function validate_promocode($code, $param = null)
    {
        $single_code = strtoupper(substr($code, 0, 3));

        //single promo code
        if (($single_code == 'BSP' && strlen($code) <= 15) || ($single_code == 'CAT' && strlen($code) == 6)) {
            $promo_query = DB::table('campaign as c')
                ->leftJoin('ebook_volume as ev', 'ev.ebook_id', '=', 'c.ebook_ids')
                ->select('c.campaign_name', 'c.discount', 'c.start_date', 'c.end_date', 'c.single_discount_code',
                    DB::raw("to_days(CURDATE()) as total_days"),
                    DB::raw("to_days(c.start_date) as starting_days"),
                    DB::raw("to_days(c.end_date) as end_days")
                )
                ->whereBetween(DB::raw("to_days(CURDATE())"), [DB::raw("to_days(c.start_date)"), DB::raw("to_days(c.end_date)")])
				->where('c.status', 'Active')
                ->where('c.single_discount_code', $code)
                ->get()->first();
        } else {
            $promo_query = DB::table('campaign as c')
                ->leftJoin('ebook_volume as ev', 'ev.ebook_id', '=', 'c.ebook_ids')
                ->leftJoin('campaign_multi_discount_codes as cm', 'c.id', '=', 'cm.campaign_id')
                ->select('c.campaign_name', 'c.discount', 'c.start_date', 'c.end_date', 'c.single_discount_code', 'cm.discount_codes as mulitple_codes',
                    DB::raw("to_days(CURDATE()) as total_days"),
                    DB::raw("to_days(c.start_date) as starting_days"),
                    DB::raw("to_days(c.end_date) as end_days")
                )
                ->whereBetween(DB::raw("to_days(CURDATE())"), [DB::raw("to_days(c.start_date)"), DB::raw("to_days(c.end_date)")])
				->where('c.status', 'Active')
                ->where('c.single_discount_code', $code)
                ->get()->first();
        }

        return $promo_query;
    }

    public function GetOrderPrintVersionPreview($ebook, $ebook_volume, $request)
    {   
        $preview_billing['fname']   = $request->fname;
        $preview_billing['lname']   = $request->lname;
        $preview_billing['address'] = $request->address;
        $preview_billing['city']    = $request->city;
        $preview_billing['state']   = $request->state;
        $preview_billing['zip']     = $request->zip;
        $preview_billing['country'] = $request->billing_country;
        $preview_billing['phone']   = $request->phone;
        $preview_billing['email']   = $request->email;

        $preview_billing['promo_code'] = $request->promo_code;
        $preview_billing['order_type'] = $request->order_type;
        $preview_billing['print_discount_rate'] = '';

        $discount     = (50 / 100);
        $Aebook_price = $ebook_volume[0]->ebook_price;
        $pod_price    = $ebook_volume[0]->ebook_price_pod;
        $copies       = $request->printcopies;

        //------------------------Check Order Type---------------------//

        // Print On Demand and Web Price value is PODandPDF
        if ($preview_billing['order_type'] == "PODandPDF") {
		
            $total_amount_of_print = ceil(($discount * $Aebook_price) + ($pod_price * $copies));
        }
        //simple POD price * no. of copies
        else {
		
            $total_amount_of_print = $pod_price * $copies;
        }
		
        //---------------------------------------------------------------//

        if ($request->printcopies == 0) {
            $preview_billing['print_copies'] = 'More than 5';
        } else {
            $preview_billing['print_copies'] = $request->printcopies;
        }

        if(!empty($request->promo_code))
        {
        //------------------------Validate Promo Code---------------------//
            $promo_details = $this->validate_promocode($request->promo_code);

            $validate_promocode = $this->validate_promo_code($request);

            if (!empty($promo_details) && $validate_promocode->original[0] == true) {
                $preview_billing['print_discount_rate'] = $promo_details->discount;
            } 
        }
        //---------------------------------------------------------------//

        //------------------------Get Actual Price-----------------------//
        $order_type                            = $request->order_type;
        $ebook_price                           = $ebook_volume[0]->ebook_price;
        $ebook_price_pod                       = $ebook_volume[0]->ebook_price_pod;
        $printcopies                           = $request->printcopies;
        $ebook_actual_price                    = $total_amount_of_print;
        $preview_billing['ebook_actual_price'] = $ebook_actual_price;
        //---------------------------------------------------------------//

        if ($request->printcopies > 0) 
		{
            //------------------------Get Shipment Price---------------------//
            $print_shipment_price              = $this->get_print_shipment_price($request->printcopies, $total_amount_of_print);
            $preview_billing['shipment_price'] = $print_shipment_price;
            //---------------------------------------------------------------//

            //------------------------Get Total Amount-----------------------//
            $total_print_amount = $this->get_total_print_amount($print_shipment_price, $total_amount_of_print);

            if (!empty($promo_details) && $validate_promocode->original[0] == true) 
            {
                $discount_rate                        = (($total_amount_of_print * $promo_details->discount) / 100);
                $grand_total_print = ($total_amount_of_print) - ($discount_rate);
                $grand_total_print                    = round($grand_total_print, 2);
				$preview_billing['grand_total_print'] = round($grand_total_print);
                $p_total                              = $grand_total_print + $print_shipment_price;
                $preview_billing['total_amount']      = round($p_total);
            } else {
                $grand_total_print               = $total_print_amount;
                $preview_billing['total_amount'] = round($grand_total_print);
            }

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

        } else {
            // if print copies more than 5 then shipment/print amount should be zero
            $total_print_amount= 0;
            $preview_billing['shipment_price']      = $print_shipment_price= 0;
            $preview_billing['print_discount_rate'] = $discount_amount = 0;
            $preview_billing['total_amount']        = $grand_total_print= 0;
        }

        $preview_shipping['fname']    = $request->sfname;
        $preview_shipping['lname']    = $request->slname;
        $preview_shipping['address']  = $request->saddress;
        $preview_shipping['city']     = $request->scity;
        $preview_shipping['zip']      = $request->szip;
        $preview_shipping['email']    = $request->semail;
        $preview_shipping['phone']    = $request->sphone;
        $preview_shipping['country']  = $request->shipping_country;
        $preview_shipping['state']    = $request->sstate;
        $preview_shipping['comments'] = $request->comments;

        $discount = $this->getDiscount($ebook_volume);

        return array($preview_billing, $preview_shipping, $discount);

    }

    public function getEbookActualPrice($ebook_price, $ebook_price_pod, $printcopies, $order_type)
    {
        $total_amount_of_print = '';

        $discount = (50 / 100);
        //POD + PDF amount as 50% discount
        if ($order_type == "Print On Demand and Web Price") {
            $total_amount_of_print = round(ceil(($discount * $ebook_price) + ($ebook_price_pod * $printcopies)));
        }
        //simple POD price * no. of copies
        else {
            $total_amount_of_print = round($ebook_price_pod * $printcopies);
        }

        return $total_amount_of_print;
    }

    //function calculate shipment price
    public function get_print_shipment_price($copies, $total_amount_of_print)
    {
        $CONST_shipment_single_ebook = 20;
        $CONST_shipment_multi_ebook  = 12;
        $shipment_price              = $CONST_shipment_single_ebook + ($copies - 1) * $CONST_shipment_multi_ebook;

        return $shipment_price;
    } //get_print_shipment_price

    public function get_total_print_amount($print_shipment_price, $total_amount_of_print)
    {
        $total_print_amount = round($print_shipment_price + $total_amount_of_print);

        return $total_print_amount;
    } //get_total_print_amount

    public function checkOrderType($poid)
    {
        $ebook_print_order = DB::table('tbl_ebook_print_order')->select('nid', 'order_type')->where('poid', $poid)->get()->first();

        if ($ebook_print_order->order_type == 'Print On Demand') //   1 check order type
        {
            $message[0] = 'Thank you for your order';
            $message[1] = 'Your print order will be processed for delivery within 6-8 weeks.';
            $message[2] = 'If you have any further queries please feel free to contact us at <a href="mailto:ebooksales@benthamscience.org">ebooksales@benthamscience.org';

            return $message;

        } elseif ($ebook_print_order->order_type == 'Print On Demand and Web Price') //   2 check order type
        {
            $ebook_node = DB::table('node')->select('type')->where('nid', $ebook_print_order->nid)->get()->first();

            if ($ebook_node->type == 'volume') {
                $ebook_node = DB::table('volume')
                    ->Join('ebook', 'ebook.id', '=', 'volume.ebook_id')
                    ->select('volume', 'v.volume_id', 'file_path', 'file_name', 'supplementary_filename', 'ebook_id', 'title', 'voucher_id', 'is_packaged')
                    ->where('v.nid', $ebook_print_order->nid)->get()->first();

                $add_access['user_id']   = Auth::user('id');
                $add_access['volume_id'] = $ebook_node->volume_id;
                $add_access['order_id']  = $poid;
                $volume_access_id        = DB::table('perpetual_volume_access')->insertGetId($add_access);

                //  -----------------Create Successful Message----------------------------------------------------
                $encrypt       = encrypt($ebook_print_order->nid . " || " . $poid);
                $download_link = 'http://103.236.135.35:97/podpdf/download/' . $encrypt;
                $link          = '<a href="' . $download_link . '"><b>Click here for download</b></a>';

                $mailto = '<a href="mailto:ebooksales@benthamscience.org"><b>ebooksales@benthamscience.org</b></a>';

                $message[0] = 'Thank you for your order';
                $message[1] = 'Your print order will be processed for delivery within 6-8 weeks.';
                $message[2] = 'You can download pdf from this link:' . $link;
                $message[3] = 'If you have any further queries please feel free to contact us at ' . $mailto;
                return $message;

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

            }
        }
    }

    public function DeleteEbookVolumeFile(Request $request, $ebook_volume_id, $file_type)
    {
        $user = Auth::user();
        //-----------------------------Insert into log table-----------------------------------
        $ebook_volume = EbookVolume::where('ebook_volume_id', $ebook_volume_id)->first();
        $log          = (array) $ebook_volume;
        $add_log      = array(
            'content_id'      => $ebook_volume_id,
            'content_type_id' => config('constants.log_content_types.EbookVolume'),
            'action'          => config('constants.log_action_types.delete_file'),
            'log_data'        => json_encode($log),
            'created_dated'   => time(),
            'created_by'      => Auth::user()->id,
            'ip'              => ip2long($request->ip()),
        );
        $log = Log::AddLog($add_log);

        //--------------------------------------------------------------
        if($file_type == "image_file_name")
        {
           $filename=config('constants.admin.root_path').$ebook_volume->file_path.'image/'.$ebook_volume->image_file_name;

           if(file_exists($filename))
            {
                File::delete($filename);
            }
        }

        $update_ebook_volume['ebook_volume_id'] = $ebook_volume_id;
        $update_ebook_volume[$file_type]        = null;
        $update_ebook_volume['last_modified']   = time();
        $update_ebook_volume['updated_by']      = $user->id;
        EbookVolume::where('ebook_volume_id', $ebook_volume_id)->update($update_ebook_volume);

        return redirect()->back();
    }

    public function DownloadFlyer($filepath)
    {

        $file_path = Crypt::decrypt($filepath);
        if (file_exists($file_path)) {
            return response()->download($file_path);
        } else {
            Session::flash('message', " File does not exist!");
            return back();
        }
    }
	public function AddAccessDenail($request,$DownloadAccess,$ebook_volume_id)
	{  
		$user_type = "";
        if (session()->has('ip_base_access') || session()->has('user_base_access'))
		{
			if(!$DownloadAccess)
			{
				$access_user_data = session()->get('access_user_data');

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

						if ($access_type_id == 333) //corporate
						{
							$user_type = 'C';
						}
						elseif ($access_type_id == 111 || $access_type_id == 222 || $access_type_id == 888) //trial
						{
							$user_type = 'T';
						}
						elseif ($access_type_id == 444 || $access_type_id == 555 || $access_type_id == 666) //restricted Token
						{
							$user_type = 'R';
						}
						
						if($user_type != "")
						{ 
							$access_denail_data['ev_id'] = $ebook_volume_id;
							$access_denail_data['cat_id'] = 1;
							$access_denail_data['user_id'] = $user->id;
							$access_denail_data['user_type'] = $user_type;
							$access_denail_data['created_on'] = time();
							$access_denail_data['ip_address'] = ip2long($request->ip());
							UserAccess::InsertEbookAccessDenail($access_denail_data);
						}
					}	
				}				
			}
		}
	}
	
	public function CheckUserAccessOnEbook($request,$ebook_volume,$user_access,$restricted_user_access_key,$content_download_type,$clientIP,$user_id)
	{
		if (session()->has('ip_base_access') || session()->has('user_base_access'))
		{
			$ebook_id = $ebook_volume->ebook_id;
			$volume_id = $ebook_volume->ebook_volume_id;
			
			// Check User Access Trail (Trail) Ebook Volume Level 
			$v_param['access_type_id'] = 111;
			$v_param['access_on'] = 'ebook_volume';
			$v_param['user_id'] = session()->get('user_id');
			$v_param['ip_address'] = $request->ip();
			$v_param['curr_date'] = true;
			$v_param['volume_id'] = $volume_id;
			
			$trail_access = UserAccess::GetUserAccessOnContent($v_param);
			
			if(!empty($trail_access[0]) && $user_access->view_option==0)
			{
				$trial_count = DB::table('download_count_volume')->where('ebook_id',$ebook_id)->where('volume_id',$volume_id)->where('user_id',$user_access->user_id)->count();
				
				if ($trial_count >= 5)
				{
					Session::flash('message', "You have Trial Access and you have already downloaded " . $trial_count . " Ebooks ");
					return false;
				}
				
			}

            if(DB::select("select block FROM download_total where block = 'y' and uid = ".$user_id."")){
                Session::flash('message', " Your download limit has been exceeded!");
                redirect('/bybook');
            }

            if($content_download_type == 'P')
            { 
                $res_obj = DB::select("select * FROM perpetual_volume_access where user_id = ".$user_id." and volume_id = ".$volume_id);
                foreach ($res_obj as $row)
                {
                    $query1 = DB::select("insert into perpetual_history (user_id, type, type_id, order_id)
                                            values (".$row->user_id.",'v',".$row->volume_id.",".$row->order_id." )" );
                    $query2 = DB::select(" delete from perpetual_volume_access where id = ".$row->id );        
                  }
            }//restrict prepetual ends
            
            if (!empty($restricted_user_access_key)) 
			{
                $user_name = trim($request->user_name);
                $password  = trim($request->password);
				
                if ($user_access) 
				{
                    if ($user_access->access_type_id != 666) 
					{
                        $vru_count = UserAccess::VerifyRestrictUser($restricted_user_access_key, $user_name, $password, $user_access);

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

                if ($user_access->access_type_id == 666) 
				{
                    UserAccess::UpdateWithoutKeyRestrictedUserInfo($restricted_user_access_key, $clientIP, $volume_id, 'e', $user_access);
                }
				else 
				{
                    UserAccess::UpdateRestrictedUserInfo($restricted_user_access_key, $user_name, $clientIP, $volume_id, 'e', $user_access);
                }
            }
        }    
		
		return true;
	}

    public function DirectEbookVolumeDownload($request,$ebook_volume_id)
    {
    $param = array();
    $aparam = array();
    $download_type = array();
    $VolumeDownloadAccess  = false;
    $content_id = $ebook_volume_id;
    $user_id = 0;
    $user_access_id = '';
    $content_download_type  = '';
    $restricted_user_access_key  = '';
    $ebook_access = false;
    $chapter_access = false;
    $access_base_type = 0;
    $SecondsGap = 30; //default is 30 sec

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


                $ebook_volume = EbookVolume::where('ebook_volume_id', '=', $ebook_volume_id)->first();

                // ebook_volume existing check
                if(!empty($ebook_volume))
                {
                    //used to check volume level prepetual access(if user has perchased that volume)
                    //if access given then $DownloadAccess will be true
                    if(($VolumeDownloadAccess == false) && session()->get('user_id'))
                    {     
                        if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $ebook_volume_id, 'volume')[0]->total > 0){                        
                            $DownloadAccess        = true;
                            $VolumeDownloadAccess  = true;
                            $access_base_text      = "Subscribe";                        
                            $content_download_type = 'P';
                            $terms_popup           = true;   
                            $ebk_vol_lvl_access    = true;
                        }
                    }

                    //Check Content Access Volume Level
                    $ebk_vol_lvl_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");
                    $ebk_vol_lvl_access = $content_access = isset($ebk_vol_lvl_access[0]->access_type) ? $ebk_vol_lvl_access[0]->access_type : null;

                    if ($ebk_vol_lvl_access) 
                    {
                        $VolumeDownloadAccess = $ebk_vol_lvl_access; 
                    }

                    // Check User Access Volume Level 
                    if (!$VolumeDownloadAccess) 
                    {
                        $v_param['volume_id'] = $ebook_volume_id;
                        $v_param['user_id'] = session()->get('user_id');
                        $v_param['ip_address'] = $request->ip();
                        
                        $ua_volume_lvl = UserAccess::GetAllContentUserAccess($v_param,array('ebook_volume'=>true));
                        if (!empty($ua_volume_lvl[0])) 
                        {
                            $content_download_type = $ua_volume_lvl[0]->content_download_type;
                            $restricted_user_access_key = $ua_volume_lvl[0]->restricted_user_access_key;
                            $voparam['user_access_id'] = $user_access_id = $ua_volume_lvl[0]->user_access_id;
                            $vol_type = $ua_volume_lvl[0]->type;
                            $vol_access_base_text = $ua_volume_lvl[0]->access_base_text;
                            $voinfo = UserAccess::GetUserAccessInfo($voparam);
                            $ViewOption = $voinfo->view_option;

                            if($ViewOption == 0)
                            {
                                $VolumeDownloadAccess = $ua_volume_lvl[0]->volume_id;
                            }
                        }
                    }

                }
                    if(!$VolumeDownloadAccess)  {

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

                    }

                if($VolumeDownloadAccess)
                {
                    $volume_gap = EbookVolume::VolumeDownloadGap($user_id, $ebook_volume_id, $SecondsGap);            
                    if ($volume_gap->rcd > 0) 
                    {
                        $last_session_userid = $request->session()->getId()."-".microtime(true);
                        session(['last_session_userid' => $last_session_userid]);
                        DB::select("update download_count_volume set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$volume_gap->id."'");

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

                    if($user_id > 0 && isset($ebook_volume->ebook_volume_id))
                    {
                        $download_file_type = 1;
                        $investigation_type = 2;

                        if(empty($content_download_type))
                            {
                              $content_download_type='D';
                            }

                        $add_download_count = array(
                            'user_id'               => $user_id,
                            'ebook_id'              => $ebook_volume->ebook_id,
                            'volume_id'             => $ebook_volume->ebook_volume_id,
                            'timestamp'             => time(),
                            'ip_address'            => $request->ip(),
                            'content_download_type' => $content_download_type,
                            'is_agree'              => 1,
                            'download_file_type'    => $download_file_type,
                            //'user_agent'            => $_SERVER['HTTP_USER_AGENT'],
                            'session_id'            => session()->get('last_session_userid'),
                        );
                        EbookVolume::AddVolumeDownload($add_download_count);
                        
                        $add_download_count['investigation_type']=$investigation_type;
                    
                        $this->AddAccessInvestigation($request,$add_download_count);
                    
                    }

                    $file_path = config('constants.admin.root_path').$ebook_volume->file_path.$ebook_volume->file_name;

                       // dd($file_path);
                        return $file_path;
                }
    }

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

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

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

        if ($email_token == $request->link) 
        {
            $user = User::where('name', '=', $name)->first();

            if ($user) 
            {
                $param['user_id'] = null;
                $user_id = $user->id;
                $access_data = UserAccess::CheckUserAccess($user_id);
                // User Access Check
                if (!empty($access_data)) 
                {
                    $ebook_volume = EbookVolume::where('ebook_volume_id', '=', $content_id)->first();
                    // chapter existing check
                    if(!empty($ebook_volume))
                    {
                        $ebook_volume_id = $param['ebook_volume_id'] = $ebook_volume->ebook_volume_id;
                        $ebook_volume_nid    = $ebook_volume->nid;
                        $ebook_id            = $ebook_volume->ebook_id;

                        $param['view']            = 'user';
                        $chapter_details          = Chapter::GetChapterListByEbookVolume($param,100);

                        if(!empty($chapter_details[0]))
                        {
                            //Check Content Access Volume Level
                            $ebook_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");

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

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

                            }

                            if (!$DownloadAccess) 
                            {
                                // Check User Access Ebook Volume Level 
                                $param['volume_id'] = $ebook_volume_id;
                                $param['user_id'] = $user_id;
                                $param['ip_address'] = $request->ip();
                                $access_on = "ebook_volume";

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

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

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

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

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

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

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

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

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

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

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

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

                            if ($DownloadAccess) 
                            {
                                $param['ebook_volume_id']  = $ebook_volume_id;
                                $param['user_email'] = $email;
                                $ebook_volume_download = UserAccess::GetUserAccessDownloadEbookVolume($param);

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

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

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

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