<?php

namespace App\Http\Controllers;

use App\Models\Author;
use App\Models\Chapter;
use App\Models\Country;
use App\Models\Doi;
use App\Models\Article;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Keywords;
use App\Models\Log;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Subject;
use App\Models\BookAccess;
use App\Models\ContentAccess;
use App\Models\UserAccess\UserAccess;
use App\Models\MarkList;
use App\Models\BundleOffer;
use App\User;
use DB;
use Cookie;
use App\Classes\EbookForm;
use Auth;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Session;

class ChapterController extends BenthamController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index(Request $request)
    {

        $editPermission   = false;
        $deletePermission = false;

		$ebook_volume_search=array();
		$param['title_search']    = $issue_id    = $request->get('title_search');
		$param['ebook_id']        = $ebook_id        = $request->get('ebook_id');
		$param['ebook_volume_id'] = $ebook_volume_id = $request->get('ebook_volume_id');
		
        $frm_search = $request->get('frm_search');
        $ajx_search = $request->get('ajx_search');

        ///------------------------------------------------------///
        // ------------Get Ebook Volume   from ajax call---------///
        ///------------------------------------------------------///
        if ($ajx_search != null && $ajx_search == true) 
		{
            if (!empty($ebook_id)) 
			{
				$p['ebook_id'] = $ebook_id;
                $ebook_volume_search = EbookVolume::where('ebook_id',$ebook_id)->pluck('volume_name','ebook_volume_id');
                return response()->json(array('ebook_volume_search' => $ebook_volume_search), 200);
            }
        } 		
		else
		{
			if ($frm_search != null && $frm_search == true) 
			{
				
				$p['ebook_id'] = $ebook_id;
                $ebook_volume_search = EbookVolume::where('ebook_id',$ebook_id)->pluck('volume_name','ebook_volume_id');
				
			}
			$join['ebook_volume'] = true;
			$chapter = Chapter::GetChapterList($param,$join);
			$ebook_search = Ebook::GetEbookTitle();
			
			if (checkPermission('chapter', 'edit')) {
				$editPermission = true;
			}if (checkPermission('chapter', 'delete')) {
				$deletePermission = true;
			}

			return view('admin.chapter.chapter', with(['chapter' => $chapter, 'ebook_search' => $ebook_search,'ebook_volume_search' => $ebook_volume_search, 'editPermission' => $editPermission, 'deletePermission' => $deletePermission, 'param' => $param]));
		}
        
    }
	
	
    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // return view('admin.show',compact('journal'));
    }

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

		$ajx_search = $request->get('ajx_search');
		$chapter_exist = $request->get('chapter_exist');
		
		if ($ajx_search == true && $chapter_exist == true)
		{
			$param['ebook_id'] = $request->get('ebook_id');
			$ebook_volume_id = $request->get('ebook_volume_id');
			$chapter_no = $request->get('chapter_no');
			
			$this->CheckIfChapterExist();
		}
		else
		{
			$selected_keywords = "";
			$ebook             = Ebook::GetEbooks("", "", "off");
			$country           = Country::GetCountryList();
			$selected_chapter  = Chapter::GetChapterById($id);

			$ebook_volume      = EbookVolume::GetEbookVolumeByVolumeId($selected_chapter->ebook_volume_id);
			$selected_meta     = Meta::NodeMeta($selected_chapter->nid);
			$selected_author   = Author::getAuthorDataById($selected_chapter->chapter_id, 'chapter_id');
			$chapter_keywords  = Keywords::getKeywordDataById($selected_chapter->chapter_id, 'chapter_id');
			if (isset($chapter_keywords)) {
				foreach ($chapter_keywords as $key => $value) {
					$selected_keywords .= $value->keyword . ",";
				}
				$selected_keywords = rtrim($selected_keywords, ',');
			}
			$page = 'update';
			return view('admin.chapter.chapter_form', with(['user' => $user,'ebook' => $ebook, 'ebook_volume' => $ebook_volume, 'country' => $country, 'selected_chapter' => $selected_chapter, 'selected_meta' => $selected_meta, 'selected_author' => $selected_author, 'selected_keywords' => $selected_keywords,'page' => $page]));
		}
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $ebook_id   = $request->get('ebook_id');
        $ajx_search = $request->get('ajx_search');
		$chapter_exist = $request->get('chapter_exist');
		

        if ($ajx_search == true) 
		{
			if ($chapter_exist == true)
			{
				$ebook_id = $request->get('ebook_id');
				$ebook_volume_id = $request->get('ebook_volume_id');
				$chapter_no = $request->get('chapter_no');
				$chapter = Chapter::where('ebook_id',$ebook_id)
				->where('ebook_volume_id',$ebook_volume_id)
				->where('chapter_no',$chapter_no)
				->select('chapter_no')->first();
				$chapter_number = isset($chapter->chapter_no) ? $chapter->chapter_no : null;
				return response()->json(array('chapter_number' => $chapter_number), 200);		
			}
			else
			{
				$p['ebook_id']       = $ebook_id;
				$ebook_volume_search = EbookVolume::GetEbookVolumeByEbookId($p);
				return response()->json(array('ebook_volume_search' => $ebook_volume_search), 200);
			}
        }
		else
		{

			$ebook   = Ebook::GetEbooks("", "", "off");
			$country = Country::GetCountryList();
			$selected_author = "";
			$page = 'add';
			return view('admin.chapter.chapter_form', with(['ebook' => $ebook, 'country' => $country, 'selected_author' => $selected_author,'page' => $page]));
		}
    }

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

		if ($ajax == true)
		{
            if($method=='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_chapter_form))
			{
				$result = $this->InsertChapter($request);
				
				if ($result[0] == false) 
				{
					$validator = $result[1];
					return back()->withInput()->withErrors($validator);
				}
				else
				{
					$chapter_id = $result[1];
					return Redirect::to('admin/chapters/'.$chapter_id.'/edit');
				}
				
			}
		}
	}
	
	 /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
	 
    public function update(Request $request, $chapter_id)
    {
		if(isset($request->update_chapter_form))
		{
			$result = $this->UpdateChapter($request,$chapter_id);
		}
		if(isset($request->upload_files))
		{
			$result = $this->UploadFiles($request,$chapter_id);
		}
		if(isset($request->submit_meta))
		{
			$result = $this->SubmitMeta($request,$chapter_id);
		}
		
		if ($result[0] == false) 
		{
			$validator = $result[1];
			return back()->withInput()->withErrors($validator);
		}
		else
		{
			$chapter_id = $result[1];
			return Redirect::to('admin/chapters/'.$chapter_id.'/edit');	
		}
	}	
	
	public function InsertChapter($request)
	{
        //--------------Add Chapter Validation------------------

		$validate_chapter = array(
		'ebook_id'           => 'required',
		'ebook_volume_id'    => 'required',
		'chapter_no'         => 'required|numeric',
		'title'              => 'required',
		'first_page'         => 'required',
		'last_page'          => 'required',
		'page_count'         => 'required'
		);
		
        $validator = Validator::make($request->all(),$validate_chapter);

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

            try {// try transaction start here for data integrity

                    DB::beginTransaction();

                    //---------------Log Array--------------
                    $add_chapter  = array();
                    $log_authors  = array();
                    $log_keywords = array();
                    $log_meta     = array();

                    //---------------Initilize file name variables--------------
                    $supplementary_file_name = "";
                    $html_file_name          = "";
                    $epub_file_name          = "";
                    $prc_file_name           = "";
					
					//echo $request->input('ebook_id')." - ".$request->input('ebook_volume_id'); die;
					//---------------------Check DOI-----------------------
                    $arr = explode("/", $request->input('doi')); //if doi is entered
                    $doi='';
                    if (trim($arr[0]) != "10.2174" || $request->input('doi') == null) {
                        //checking if publisher code is correct

                        $doi_data = Doi::GetFirstChapterDOI($request->input('ebook_id'), $request->input('ebook_volume_id'));

                        if(!empty($doi_data)){
	                        $eisbn     = trim(str_replace("-", "", $doi_data->eisbn));
	                        $year      = substr(trim($doi_data->year), 2, 2);
	                        $volume_no = trim($doi_data->volume_no);

	                        $first_page = $request->input('chapter_no');

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

	                        if (strlen($first_page) == "1") {
	                            $spageno = "000" . $first_page;
	                        }

	                        if (strlen($first_page) == "2") {
	                            $spageno = "00" . $first_page;
	                        }

	                        if (strlen($first_page) == "3") {
	                            $spageno = "0" . $first_page;
	                        }

	                        if (strlen($first_page) == "4") {
	                            $spageno = $first_page;
	                        }

	                        //$doi = "10.2174/".$issn."-1-".$year."-".$volume_no."-".$issue_no."-".$spageno;
	                        $doi = "10.2174/" . $eisbn . "1" . $year . $volume_no . $spageno;
	                        $doi = trim($doi);
	                    }
                    } else {

                        $doi = $request->input('doi');
                    }
					
                    //---------------------Insert into node table---------------

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

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

                    $chapter_path = Chapter::GetChapterFilePath($request->input('ebook_volume_id'));
                    //---------------------Insert into chapter table--------
						$add_chapter = array('nid' => $node_id,
                        'ebook_id'                 => $request->input('ebook_id'),
                        'ebook_volume_id'          => $request->input('ebook_volume_id'),
                        'chapter_no'               => $request->input('chapter_no'),
                        'title'                    => $request->input('title'),
                        'abstract'                 => $abstract,
                        'file_path'                => $chapter_path,
						'doi'               	   => $doi,
                        'is_uploaded'              => $request->input('is_uploaded'),
                        'is_packaged'              => $request->input('is_packaged'),
                        'video_link'               => $request->input('video_link'),
                        'created'                  => time(),
                        'created_by'               => $user->id);

						$add_chapter['first_page'] = ($request->has('first_page')) ? $request->get('first_page') : '';

                        $add_chapter['last_page']  = ($request->has('last_page')) ? $request->get('last_page') : '';
						$add_chapter['page_count'] = ($request->has('page_count')) ? $request->get('page_count') : 0;
					
                    $chapter_id = Chapter::AddChapter($add_chapter);
                    $add_chapter['chapter_id'] = $chapter_id;

                    //-------------------Insert into Keywords table---------------
                    if ($request->input('keywords') != "") {
                        $keywordsArray = explode(",", $request->input('keywords'));
                        if (!empty($keywordsArray)) {

                            for ($a = 0; $a < count($keywordsArray); $a++) {
                                $add_keywords[] = array('keyword' => $keywordsArray[$a],
                                    'chapter_id'                    => $chapter_id);

                                $log_keywords['chapter_keywords'][$a] = $add_keywords;
                            }
                            // print_r($add_keywords); die;
                                Keywords::AddKeywords($add_keywords);
                        }
                    }

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

                    $log     = array_merge($add_node, $add_chapter,$log_keywords);
                    $add_log = array(
                        'content_id'      => $chapter_id,
                        'content_type_id' => config('constants.log_content_types.Chapter'),
                        'action'          => config('constants.log_action_types.insert'),
                        'log_data'        => json_encode($log),
                        'created_dated'   => time(),
                        'created_by'      => Auth::user()->id,
                        'ip'              => ip2long($request->ip()),
                    );
                    $log = Log::AddLog($add_log);
                            DB::commit();
                        } catch (Exception $e) {

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

			return array(true,$chapter_id);
        }
    }
	
	public function UpdateChapter($request, $chapter_id)
    {
		$validate = array(
				'chapter_no'         => 'required|numeric',
				'title'              => 'required',
				'first_page'         => 'required',
				'last_page'          => 'required',
                'doi'          		 =>  'unique:chapter,doi,'.$chapter_id.',chapter_id'  

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

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

            try {// try transaction start here for data integrity

                    DB::beginTransaction();
                    //---------------Log Array--------------
                    $add_chapter    = array();
                    $update_chapter = array();
                    $log_authors    = array();
                    $log_keywords   = array();
                    $log_meta       = array();

                    //----------initilize variables-----------
                    $ebook_id        = $request->input('ebook_id');
                    $ebook_volume_id = $request->input('ebook_volume_id');
                    $node_id         = $request->input('nid');
                    $chapter_path    = Chapter::GetChapterFilePath($request->input('ebook_volume_id'));
                    $user            = Auth::user();
					
					//---------------------Check DOI-----------------------
                    $arr = explode("/", $request->input('doi')); //if doi is entered

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

                        $doi_data = Doi::GetChapterDOI($request->input('ebook_id'), $request->input('ebook_volume_id'));
                        //print_r($doi_data); die;
                        //$chapter_id = trim($doi_data->chapter_id);

                        $eisbn     = trim(str_replace("-", "", $doi_data->eisbn));
                        $year      = substr(trim($doi_data->year), 2, 2);
                        $volume_no = trim($doi_data->volume_no);

                        $first_page = $request->input('chapter_no');

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

                        if (strlen($first_page) == "1") {
                            $spageno = "000" . $first_page;
                        }

                        if (strlen($first_page) == "2") {
                            $spageno = "00" . $first_page;
                        }

                        if (strlen($first_page) == "3") {
                            $spageno = "0" . $first_page;
                        }

                        if (strlen($first_page) == "4") {
                            $spageno = $first_page;
                        }

                        //$doi = "10.2174/".$issn."-1-".$year."-".$volume_no."-".$issue_no."-".$spageno;
                        $doi = "10.2174/" . $eisbn . "1" . $year . $volume_no . $spageno;
                        //echo $doi; die;
                        $doi = trim($doi);

                    } else {

                        $doi = $request->input('doi');
                    }
                    
                    $selected_chapter = Chapter::GetChapterById($chapter_id);
					
					//$abstract = htmlentities($request->get("abstract"));
					$abstract = htmlspecialchars($request->input('abstract'), ENT_QUOTES); 
     				$abstract = str_replace("'", "''", $abstract);
                    //---------------------Update chapter table--------
                    $add_chapter = array(
                        'chapter_id'      => $chapter_id,
                        'nid'             => $node_id,
                        'ebook_id'        => $request->input('ebook_id'),
                        'ebook_volume_id' => $request->input('ebook_volume_id'),
                        'chapter_no'      => $request->input('chapter_no'),
                        'title'           => $request->input('title'),
                        'page_count'      => $request->input('page_count'),
                        'first_page'      => $request->input('first_page'),
                        'last_page'       => $request->input('last_page'),
                        'abstract'        => $abstract,
						'doi'        	  => $doi,
                        'is_uploaded'     => $request->input('is_uploaded'),
                        'is_packaged'     => $request->input('is_packaged'),
                        'video_link'      => $request->input('video_link'),
                        'last_modified'   => time(),
                        'updated_by'      => $user->id);
                   // dd($add_chapter);
                    Chapter::UpdateChapter($add_chapter);
                   

                    //-------------------Insert into Keywords table---------------

                    if ($request->input('keywords') != "") {
                        Keywords::DeleteKeywords($chapter_id, 'chapter_id');
                        $keywordsArray = explode(",", $request->input('keywords'));
                        if (!empty($keywordsArray)) {

                            for ($a = 0; $a < count($keywordsArray); $a++) {
                                $add_keywords[] = array('keyword' => $keywordsArray[$a],
                                    'chapter_id'                    => $chapter_id);

                                $log_keywords['chapter_keywords'][$a] = $add_keywords;

                            }
                                Keywords::AddKeywords($add_keywords);
                        }
                    }
                    else
                    {
	                    Keywords::DeleteKeywords($chapter_id, 'chapter_id');	
                    }

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

                    $log     = array_merge($add_chapter, $update_chapter, $log_keywords, $log_authors, $log_meta);
                    $add_log = array(
                        'content_id'      => $chapter_id,
                        'content_type_id' => config('constants.log_content_types.Chapter'),
                        'action'          => config('constants.log_action_types.update'),
                        'log_data'        => json_encode($log),
                        'created_dated'   => time(),
                        'created_by'      => Auth::user()->id,
                        'ip'              => ip2long($request->ip()),
                    );
                    $log = Log::AddLog($add_log);

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

                DB::rollback();
                Session::flash('error', 'Somthing wrong with this page. Please try again!');
                return Redirect::to('admin/chapters');
            }
            return array(true,$chapter_id);
			
        }
    }
	
	public function UploadFiles($request,$chapter_id)
	{
        $req = array();
		
		if (isset($request->chapter_file))
		{
			$req['chapter_file'] = 'required|mimes:pdf';	
		}	
		if (isset($request->supplementary_file))
		{
			$req['supplementary_file'] = 'mimes:rar,zip';	
		}	
		if (isset($request->epub_file))
		{
			$req['epub_file'] = 'mimes:epub';	
		}	
		if (isset($request->prc_file))
		{
			//$req['prc_file'] = 'mimes:mobipocket';	
		}
		if (isset($request->html_file))
		{
			$req['html_file'] = 'mimes:html';	
		}
		
		$validator = Validator::make($request->all(),$req);
		
		if ($validator->fails()) 
		{
			return array(false,$validator);
        }
		else 
		{ 
			$chapter = Chapter::where('chapter_id',$chapter_id)->get();
			$chapter_path = $chapter[0]->file_path;
			
			//----------------------Upload chapter pdf files-------------------------------
			$chapter_path = config('constants.admin.root_path').$chapter_path;

			if ($request->hasfile('chapter_file')) {
				$chapter_file = $request->file('chapter_file');

				$chapter_file_name = $chapter_file->getClientOriginalName();

				if (!is_dir($chapter_path)) {
					mkdir($chapter_path, 0755, true);
				}
				$chapter_file->move($chapter_path, $chapter_file_name);
				$update_chapter_files['file_name'] = $chapter_file_name;
			}

			//----------------------Upload chapter supplementar files-------------------------------

			if ($request->hasfile('supplementary_file')) {
				$supplementary_file = $request->file('supplementary_file');

				$supplementary_file_name = $supplementary_file->getClientOriginalName();

				if (!is_dir($chapter_path)) {
					mkdir($chapter_path, 0755, true);
				}
				$supplementary_file->move($chapter_path, $supplementary_file_name);
				$update_chapter_files['supplementary_filename'] = $supplementary_file_name;
			}

			//----------------------Upload chapter html files-------------------------------

			if ($request->hasfile('html_file')) {
				$html_file = $request->file('html_file');

				$html_file_name = $html_file->getClientOriginalName();

				if (!is_dir($chapter_path . 'html')) {
					mkdir($chapter_path . 'html', 0755, true);
				}
				$html_file->move($chapter_path . 'html', $html_file_name);
				$update_chapter_files['html_filename'] = $html_file_name;
			}

			//----------------------Upload chapter epub files-------------------------------

			if ($request->hasfile('epub_file')) {
				$epub_file = $request->file('epub_file');

				$epub_file_name = $epub_file->getClientOriginalName();

				if (!is_dir($chapter_path . 'epub')) {
					mkdir($chapter_path . 'epub', 0755, true);
				}
				$epub_file->move($chapter_path . 'epub', $epub_file_name);
				$update_chapter_files['epub_filename'] = $epub_file_name;
			}

			//----------------------Upload chapter epub files-------------------------------

			if ($request->hasfile('prc_file')) {
				$prc_file = $request->file('prc_file');

				$prc_file_name = $prc_file->getClientOriginalName();

				if (!is_dir($chapter_path . 'prc')) {
					mkdir($chapter_path . 'prc', 0755, true);
				}
				$prc_file->move($chapter_path . 'prc', $prc_file_name);
				$update_chapter_files['prc_filename'] = $prc_file_name;
			}

			//------------------Update column in for uploaded file names and doi of chapter table-----------------
			$update_chapter_files['chapter_id'] = $chapter_id;
			Chapter::UpdateChapter($update_chapter_files);
			return array(true,$update_chapter_files['chapter_id']);
			//return $update_chapter_files;

		}

	}
	
	public function SubmitMeta(Request $request, $chapter_id)
	{
		//-------------------Insert into Node Meta table---------------
		
		$chapter = Chapter::where('chapter_id',$chapter_id)->first();
		Meta::DeleteMeta($chapter_id);
		$add_node_meta = array('nid' => $chapter->nid,
			'title'                      => $request->input('title'),
			'abstract'                   => $request->input('meta_abstract'),
			'canonical_url'              => $request->input('meta_canonical_url'),
			'copyright'                  => $request->input('meta_copyright'),
			'description'                => $request->input('meta_description'),
			'keywords'                   => $request->input('meta_keywords'));

		$node_meta        = Meta::AddNodeMeta($add_node_meta);
		$log_meta['meta'] = $add_node_meta;

			return array(true,$chapter_id);
	}
	


   
		
	

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

        //---------------Log Array--------------
        $chapter      = array();
        $log_author  = array();
        $log_authors  = array();
        $log_keywords = array();
        $log_keyword = array();
        $log_meta     = array();
        $log_node     = array();
        $nid          = $request->input('nid');

        $chapter                 = (array) Chapter::GetChapterById($id);
        $chapter_path            = $chapter['file_path'];
        $chapter_file_name       = $chapter['file_name'];
        $supplementary_file_name = $chapter['supplementary_filename'];
        $html_file_name          = $chapter['html_filename'];
        $epub_file_name          = $chapter['epub_filename'];
        $prc_file_name           = $chapter['prc_filename'];
        $log_node                = (array) Node::GetNode($nid);
        
        try {// try transaction start here for data integrity

                DB::beginTransaction();

        //------------------Delete files---------//
        //File::delete($chapter_path . $chapter_file_name, $chapter_path . $supplementary_file_name, $chapter_path . 'html/' . $html_file_name, $chapter_path . 'epub/' . $epub_file_name, $chapter_path . 'prc/' . $prc_file_name);
        $node = (array) Node::GetNode($nid);
        $log_meta = (array) Meta::NodeMeta($nid);
        $authors  = Author::getAuthorDataById($id, 'chapter_id');
        $keywords = Keywords::getKeywordDataById($id, 'chapter_id');
        if($authors)
        {   
            foreach ($authors as $key => $value) {
                $log_author[] = $value;
            }
         $log_authors['author']=$log_author;
        }

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

        Node::DeleteNode($nid);
        Meta::DeleteMeta($nid);
        Chapter::DeleteChapter($id);
        Author::DeleteAuthors($id, 'chapter_id');
        Keywords::DeleteKeywords($id, 'chapter_id');

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

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

            DB::rollback();
            Session::flash('error', 'Somthing wrong with this page. Please try again!');
            return Redirect::to('admin/chapters');
        }
        return redirect()->back()->with('success', 'Chapter delete successfully.');
        //return redirect()->route('chapter.index')->with('success', 'Chapter delete successfully.');
    }
	
	// function insertAuthor($request,$chapter_id)
	// {
		// $sequence = $request->input('sequence');
		// $author_type = $request->input('author_type');
		// $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');
		// $affiliation = $request->input('affiliation');
		
        // foreach($sequence as $key => $vals)
		// {
			// $is_principle = $request->input('principle_'.$key);
			// $add_author['iseditorcoeditor'] = $author_type[$key];
			// $add_author['sequence'] = $sequence[$key];
			// $add_author['is_principle'] = isset($is_principle) ? $is_principle : 0 ;
			// $add_author['initials'] = $initials[$key];
			// $add_author['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['affiliation'] = $affiliation[$key];
			// $add_author['chapter_id'] = $chapter_id;
			// $add_author_data[] = $add_author;
			// Author::insert($add_author);	
		// }
		
		// return $add_author_data;
	// }
	
    public function ajax_SELECT($request)
    {

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

    }

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

                DB::beginTransaction();

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

                $add_log = array(
                    'content_id'      => $add_author['author_id'],
                    'content_type_id' => config('constants.log_content_types.Author'),
                    'action'          => config('constants.log_action_types.insert'),
                    'log_data'        => json_encode($add_author),
                    '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_author), 200);

    }

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

                DB::beginTransaction();

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

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

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

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

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

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

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

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

    }

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

                DB::beginTransaction();

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

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

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

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

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

                Author::where('author_id', $author_id)->delete();
                
                if($selected_affiliation != null)
                {
                    Article::RemoveAuthorAffiliation($author_id,'author_id');
                }

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

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

    }

    public function ajax_INSERT_Author_Affiliation($request)
    {
        $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);

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

    }

    public function ajax_UPDATE_Author_Affiliation($request)
    {

        $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);
       
        return response()->json(array('update' => $update_affiliation), 200);

    }

    public function ajax_DELETE_Author_Affiliation($request)
    {
        $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');

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

    }
    //------------------------------------------------------//	
public function GetChapterVideo(Request $request)
    {
		

		$nid = $request->node_id;
		$chapter_details = Chapter::where('nid',$nid)->first();
		$chapter_id = $chapter_details->chapter_id;
		$ebook_volume_id = $chapter_details->ebook_volume_id;
		
		$ebook = Ebook::where('ebook_id', $chapter_details->ebook_id)->first();

		$ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($chapter_details->ebook_volume_id,'front');

        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook->ebook_id,$ebook_volume_id);

		$DownloadAccess = false;
		//check for chapter level content access	
		$chp_content_access = ContentAccess::CheckOpenFreeAcccess("ebook_access",$chapter_id ,"c");
		$chp_content_access = isset($chp_content_access[0]->total_count) ? $chp_content_access[0]->total_count : 0;
		
		if($chp_content_access > 0)
		{	  	
			$DownloadAccess = true;
			$user_access_type= 'f';
		}
		
		// check for volume level content access 
		if(!$DownloadAccess) 
		{
			$ebk_vol_access = ContentAccess::CheckOpenFreeAcccess("ebook_access",$ebook_volume_id ,"v");
			$ebk_vol_access = isset($ebk_vol_access[0]->total_count) ? $ebk_vol_access[0]->total_count : 0;
			if($ebk_vol_access > 0)
				$DownloadAccess = true;
				$user_access_type= 'f';
		}

		//check if user has perpetual access (if artcile purchased by login user)
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $ebook_volume_id, 'volume')[0]->total > 0){                        
                $DownloadAccess        = true;
                $user_access_type = 'P';
            }
        }

        //check if user has perpetual access (if artcile purchased by login user)
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $chapter_id, 'chapter')[0]->total > 0){                        
                $DownloadAccess        = true;
                $user_access_type = 'P';
            }
        }
		
		if (!$DownloadAccess) 
		{
			// Check User Access Ebook Volume Level 
			$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])) 
			{
                $parama['user_access_id']=$ua_volume_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($parama);   
                
                $view_option                 = $user_access_info->view_option;
				$DownloadAccess 			 = $ua_volume_lvl[0]->volume_id;
				$user_access_id         	 = $ua_volume_lvl[0]->user_access_id;
				$content_download_type       = $ua_volume_lvl[0]->content_download_type;
				$access_base_text            = $ua_volume_lvl[0]->access_base_text;
				$terms_popup                 = $ua_volume_lvl[0]->terms_popup;
				$restricted_user_access_key  = $ua_volume_lvl[0]->restricted_user_access_key;
				$restricted_user_access_type = $ua_volume_lvl[0]->restricted_user_access_type;
				$type 						 = $ua_volume_lvl[0]->type;
			}
		}
		
		if (!$DownloadAccess) 
		{
			// Check User Access Chapter Level 
			$p_article['chapter_id'] = $chapter_id;
			$p_article['user_id'] = session()->get('user_id');
			$p_article['ip_address'] = $request->ip();
            $p_article['disease_access'] = "chapter";

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

			$ua_chapter_lvl = UserAccess::GetAllContentUserAccess($p_article,array($access=>true));

			if (!empty($ua_chapter_lvl[0])) 
			{
                $param['user_access_id']=$ua_chapter_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($param);   
                
                $view_option                 = $user_access_info->view_option;
				$DownloadAccess 			 = $ua_chapter_lvl[0]->chapter_id;
				$user_access_id         	 = $ua_chapter_lvl[0]->user_access_id;
				$content_download_type       = $ua_chapter_lvl[0]->content_download_type;
				$access_base_text            = $ua_chapter_lvl[0]->access_base_text;
				$terms_popup                 = $ua_chapter_lvl[0]->terms_popup;
				$restricted_user_access_key  = $ua_chapter_lvl[0]->restricted_user_access_key;
				$restricted_user_access_type = $ua_chapter_lvl[0]->restricted_user_access_type;
				$type 						 = $ua_chapter_lvl[0]->type;
			}
		}
		
		if (!empty($DownloadAccess)) 
		{
			$chapter_details->user_access_id = $user_access_id;
			
            $this->setUserDownloadSession($request, session()->get('user_id'));

			$add_download_count = array(
			'user_id'		        => session()->get('user_id'),
			'ebook_id'              => $chapter_details->ebook_id,
			'chapter_id'            => $chapter_details->chapter_id,
			'timestamp'             => time(), 
            'ip_address'            => \Request::ip(),
            'content_download_type' => $content_download_type,
			'is_agree'              => 1,
			'download_file_type'    => 1,
			'session_id'            => session()->get('last_session_userid')
			);

			Chapter::AddChapterDownload($add_download_count);

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


		$page = 'video';
		return view('ebook.chapter_video', with(['ebook_volume_details' => $ebook_volume_details,'CountMultipleVolumeExist' => $CountMultipleVolumeExist,'chapter_details' => $chapter_details,'ebook' => $ebook,'DownloadAccess' => $DownloadAccess,'page' => $page]));
		
	}
	
	 public function ReadChapterPDF($param)
    {

        list($type, $chapter_id, $token) = decrypt($param);
        $contenttype                     = 'application/pdf';
        $chapter                         = Chapter::where('chapter_id', $chapter_id)->first();
        $file                            = config('constants.admin.root_path') . $chapter->file_path . $chapter->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);
    }
    //------------Read Chapter Direct URL Function Start--------
	public function GetReadChapterDetails(Request $request)
    {	
        $cparam='';
        if (isset($request->view_type) && $request->view_type==1) 
        {
            $pdf_type="readchapterpdf";
        } 
        else 
        {
            $pdf_type = "";
        }

        $content_download_type='S';

        $cparam=encrypt(array('readchapterpdf',$request->chapter_id,config('constants.admin.token'),$content_download_type));

        return redirect()->route('chapter', ['id' => $request->chapter_id,'param' => $cparam]);

	}	
    //------------Read Chapter Direct URL Function End--------
	public function GetChapterDetails(Request $request)
    {	
    	
        if($request->id == "download" && isset($request->param))
        {
            $chapter_nid = $request->param;
            $chapter = Chapter::where('nid', '=', $chapter_nid)->first();

            if(!empty($chapter))
            {
                $chapter_id = $chapter->chapter_id;

                $file_path = $this->DirectChapterDownload($request,$chapter_id);

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

            $chapter = Chapter::where('doi', '=', $chapter_doi)->first();


            if(!empty($chapter))
            {
                $chapter_id = $chapter->chapter_id;

                $file_path = $this->DirectChapterDownload($request,$chapter_id);

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

    	$read_download_type="";
    	$pdf_type = "";
        $cparam='';
        if (isset($request->param)) {
            $cparam = $request->param;
            list($pdf_type, $ebook_volume_id, $token) = decrypt($request->param);

            if($pdf_type=="readchapterpdf")
            {   
                list($pdf_type, $ebook_volume_id, $token, $read_download_type) = decrypt($request->param);
            }

        } else {
            $pdf_type = "";
        }

		$chapter_id = $request->id;
		$ebook_volume_details = array();
		$access_base_text ='';
		$discount="";
		$year    = "";
		$ebk_vol_access="";
		$related_journal =array();
		$related_ebook=array();
		$chapter_details = Chapter::where('chapter_id',$request->id)->first();
		if(empty($chapter_details))
		{
			//Session::flash('message', " Link not exist!");
			return abort(404);
		}
        $authors = Author::getAuthorDataById($request->id, 'chapter_id');
 
	
        $kword           = "";
		$keywords = Keywords::where('chapter_id',$request->id)->get();

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

		$ebook = Ebook::where('ebook_id', $chapter_details->ebook_id)->first();
		
		if ($chapter_details->ebook_id > 1) 
		{
            
            $related_ebook   = Subject::RelatedeBookBySubjectId($chapter_details->ebook_id);
            $related_journal = Subject::RelatedeBookJournalBySubjectId($chapter_details->ebook_id);
        }

		$ebook_volume_details = EbookVolume::GetEbookVolumeAndAuthorsById($chapter_details->ebook_volume_id,'front');
		if(count($ebook_volume_details)==0){
            return Redirect::to('/bybook');
        }
		$ebook_volume_id = $ebook_volume_details[0]->ebook_volume_id;
		$ebook_volume_name = $ebook_volume_details[0]->volume_name;
		$ebook_id = $ebook->ebook_id;
		
		
		$DownloadAccess        		 = false;
        $content_download_type       = $read_download_type ? $read_download_type : "";
        $access_base_text     		 = "";
        $terms_popup           		 = true;
        $checkIfMarked         		 = false;
        $restricted_user_access_key  ='';
        $restricted_user_access_type ='';
        $CountMultipleVolumeExist	 = 0;
        $bundle_content              = "";
		$user_access_id				 = 0;
        $view_option                 = 0;
        $view_abstract               = 1;
        $param                       = array();
        $type 						 ='';

        $CountMultipleVolumeExist = EBookVolume::CountMultipleVolumeExist($ebook_id,$ebook_volume_id);

		//check chapter level content access
		$chapter_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $chapter_id, "c");
		if ($chapter_access[0]->total_count > 0)
		{
			$DownloadAccess = true;
			if ($chapter_access[0]->access_type == 1) 
			{
				$content_download_type = 'F';	
			}
			else
			{
				$content_download_type = 'FO';
			}
			$terms_popup           = true;
		}

		//check ebook volume level content access
		if (!$DownloadAccess) {
			$ebook_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");
			
			if ($ebook_access[0]->total_count > 0) {
				$DownloadAccess        = true;
				$free                  = true;
				if ($chapter_access[0]->access_type == 1) 
				{
					$content_download_type = 'F';	
				}
				else
				{
					$content_download_type = 'FO';
				}
				$terms_popup           = true;
				
			}
		}

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

        //check if user has perpetual access (if artcile purchased by login user)
        if(($DownloadAccess == false) && session()->get('user_id')){     
            if(ContentAccess::CheckPerpetualAccess(session()->get('user_id'), $chapter_id, 'chapter')[0]->total > 0){                        
                $DownloadAccess        = true;
                $access_base_text      = "Subscribe";                        
                $content_download_type = 'P';
                $terms_popup           = true;
            }
        }
		
		if (!$DownloadAccess) 
		{
			// Check User Access Ebook Volume Level 
			$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])) 
			{
                $parama['user_access_id']=$ua_volume_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($parama);   
                
                $view_option                 = $user_access_info->view_option;
				$DownloadAccess 			 = $ua_volume_lvl[0]->volume_id;
				$user_access_id         	 = $ua_volume_lvl[0]->user_access_id;
				$content_download_type       = $ua_volume_lvl[0]->content_download_type;
				$access_base_text            = $ua_volume_lvl[0]->access_base_text;
				$terms_popup                 = $ua_volume_lvl[0]->terms_popup;
				$restricted_user_access_key  = $ua_volume_lvl[0]->restricted_user_access_key;
				$restricted_user_access_type = $ua_volume_lvl[0]->restricted_user_access_type;
				$type 						 = $ua_volume_lvl[0]->type;
			}
		}
		
		if (!$DownloadAccess) 
		{
			// Check User Access Chapter Level 
			$p_article['chapter_id'] = $chapter_id;
			$p_article['user_id'] = session()->get('user_id');
			$p_article['ip_address'] = $request->ip();
            $p_article['disease_access'] = "chapter";

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

			$ua_chapter_lvl = UserAccess::GetAllContentUserAccess($p_article,array($access=>true));

			if (!empty($ua_chapter_lvl[0])) 
			{
                $param['user_access_id']=$ua_chapter_lvl[0]->user_access_id;
                $user_access_info = UserAccess::GetUserAccess($param);   
                
                $view_option                 = $user_access_info->view_option;
				$DownloadAccess 			 = $ua_chapter_lvl[0]->chapter_id;
				$user_access_id         	 = $ua_chapter_lvl[0]->user_access_id;
				$content_download_type       = $ua_chapter_lvl[0]->content_download_type;
				$access_base_text            = $ua_chapter_lvl[0]->access_base_text;
				$terms_popup                 = $ua_chapter_lvl[0]->terms_popup;
				$restricted_user_access_key  = $ua_chapter_lvl[0]->restricted_user_access_key;
				$restricted_user_access_type = $ua_chapter_lvl[0]->restricted_user_access_type;
				$type 						 = $ua_chapter_lvl[0]->type;
			}
		}
		
		if (!empty($DownloadAccess)) 
		{
			$chapter_details->user_access_id = $user_access_id;
		}
		
		//---------------------------------------------------------------------
		// Access Denail Report
		// Check If User has Access but on this Chapter
			$this->AddAccessDenail($DownloadAccess,$ebook_volume_id,$chapter_id);
		//---------------------------------------------------------------------
		
		$discount = $this->getDiscount($ebook_volume_details);
		$page= 'chapter';
		
		

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

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

        }

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

					if(!empty($user_access))
					{
						$return = $this->CheckUserAccessOnChapter($request,$chapter,$user_access,$restricted_user_access_key,$content_download_type,$clientIP,$user_id);
						if ($return == false)
						{
							return redirect()->route('chapter', ['id' => $chapter_id]);

						}
					}

		            $this->setUserDownloadSession($request, session()->get('user_id'));

					$add_download_count = array(
					'user_id'		        => session()->get('user_id'),
					'ebook_id'              => $chapter_details->ebook_id,
					'chapter_id'            => $chapter_details->chapter_id,
					'timestamp'             => time(), 
		            'ip_address'            => \Request::ip(),
		            'content_download_type' => $content_download_type,
					'is_agree'              => 1,
					'download_file_type'    => 5,
					'session_id'            => session()->get('last_session_userid')
					);

					Chapter::AddChapterDownload($add_download_count);

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

                }
            }
                       
        }

        // View abstract add investigation
         if (Auth::user() && $view_abstract==1) 
         { 
            if(empty($content_download_type))
                {
                  $content_download_type='D';
                }

            $add_investigation = array(
			'user_id'		        => Auth::user()->id,
			'ebook_id'              => $chapter_details->ebook_id,
			'chapter_id'            => $chapter_details->chapter_id,
			'timestamp'             => time(), 
            'ip_address'            => ip2long(\Request::ip()),
            'content_download_type' => $content_download_type,
            'investigation_type'    => 1,
            );

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


         }

                /*-----------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('ebook.chapter_details', with(['ebook_volume_details' => $ebook_volume_details,
			'view_option' => $view_option,
			'chapter_details' => $chapter_details,
			'ebook' => $ebook,
			'CountMultipleVolumeExist' => $CountMultipleVolumeExist,
			'authors' => $authors,
			'kword' => $kword,
			'year' => $year,
			'discount' => $discount,
			'ebk_vol_access' => $ebk_vol_access,
			'DownloadAccess' => $DownloadAccess,
			'type' => $type,
			'content_download_type' => $content_download_type,
			'page' => $page,
			'access_base_text' => $access_base_text,
			'terms_popup' => $terms_popup,
			'restricted_user_access_key' => $restricted_user_access_key,
			'restricted_user_access_type' => $restricted_user_access_type,
			'user_access_id' => $user_access_id,
			'checkIfMarked' => $checkIfMarked,
			'related_journal' => $related_journal,
			'related_ebook' => $related_ebook,
			'view_pdf' => $view_pdf,
			'cparam' => $cparam,
			'bundle_content' => $bundle_content]));
    }
	
	 public function ChapterDownlodFile(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($chapter_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) 
		{
            $chapter_gap=Chapter::ChapterDownloadGap($user_id,$chapter_id,$SecondsGap);            
            if($chapter_gap->rcd > 0)
              {  
              	$last_session_userid = $request->session()->getId()."-".microtime(true);
             	session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_chapter set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$chapter_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);

        }    

        $chapter = Chapter::where('chapter_id',$chapter_id)->first();
		
        if ($file_type == 'pdf')
        {
            $download_file_type=1;
            $investigation_type = 2;
            $file_path = config('constants.admin.root_path').$chapter->file_path.$chapter->file_name;
			
        }
        if ($file_type == 'supplementary')
        {
            $download_file_type=0;
            $file_path = config('constants.admin.root_path').$chapter->file_path.$chapter->supplementary_filename;
        }
        if ($file_type == 'html')
        {
            $download_file_type=2;
            $investigation_type = 3;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'html/'.$chapter->html_filename;
        }
        if ($file_type == 'epub')
        {
            $download_file_type=3;
            $investigation_type = 4;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'epub/'.$chapter->epub_filename;
        }
        if ($file_type == 'prc')
        {
            $download_file_type=4;
            $investigation_type = 5;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'prc/'.$chapter->prc_filename;
        }
		
        if (file_exists($file_path))
        {
			// check User Access On Article befor Download
			
			if(!empty($user_access))
			{
				$return = $this->CheckUserAccessOnChapter($request,$chapter,$user_access,$restricted_user_access_key,$content_download_type,$clientIP,$user_id);
				if ($return == false)
				{
					return back();
				}
			}
			
            if($file_type != 'supplementary') 
			{
				if($user_id > 0  && isset($chapter->chapter_id))
				{
					$this->setUserDownloadSession($request,$user_id);
					$add_download_count = array(
						'user_id'               => $user_id,
						'ebook_id'              => $chapter->ebook_id,
						'chapter_id'            => $chapter->chapter_id,
						'timestamp'             => time(), 
						'ip_address'            => $request->ip(),
						'content_download_type' => $content_download_type,
						'is_agree'              => 1,
						'download_file_type'    => $download_file_type,
						'session_id'            => session()->get('last_session_userid')
					);
					Chapter::AddChapterDownload($add_download_count);

                    $add_download_count['investigation_type']=$investigation_type;
                    $add_download_count['ip_address']=ip2long(\Request::ip());
                 
                    $this->AddAccessInvestigation($request,$add_download_count);
				}
			}
			
            return response()->download($file_path);
        }
		else
		{
			 Session::flash('message', " File does not exist!");
			 return back();
        }
    }

	 public function ChapterDownlodBundleFile(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($chapter_id, $file_type, $content_download_type,$restricted_user_access_key) = explode ("||", $param);  

        if(isset(Auth::user()->id)) 
        {
			$bundle_content = BundleOfferController::BundleOfferUserAccess(Auth::user()->id);
            $chapter_gap=Chapter::ChapterDownloadGap(Auth::user()->id,$chapter_id,$SecondsGap);            
            if($chapter_gap->rcd > 0)
              {  
              	$last_session_userid = $request->session()->getId()."-".microtime(true);
             	session(['last_session_userid' => $last_session_userid]);
                DB::select("update download_count_chapter set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$chapter_gap->id."'");

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

                Session::flash('message', " Chapter 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);

        }    

        $chapter = Chapter::where('chapter_id',$chapter_id)->first();

        if ($file_type == 'pdf')
        {
            $download_file_type=1;
            $investigation_type = 2;
            $file_path = config('constants.admin.root_path').$chapter->file_path.$chapter->file_name;
        }
        if ($file_type == 'supplementary')
        {
            $download_file_type=0;
            $file_path = config('constants.admin.root_path').$chapter->file_path.$chapter->supplementary_filename;
        }
        if ($file_type == 'html')
        {
            $download_file_type=2;
             $investigation_type = 3;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'html/'.$chapter->html_filename;
        }
        if ($file_type == 'epub')
        {
            $download_file_type=3;
            $investigation_type = 4;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'epub/'.$chapter->epub_filename;
        }
        if ($file_type == 'prc')
        {
            $download_file_type=4;
            $investigation_type = 5;
            $file_path = config('constants.admin.root_path').$chapter->file_path.'prc/'.$chapter->prc_filename;
        }
		
        if (file_exists($file_path))
        {
                if($file_type != 'supplementary') {
	                if(isset(Auth::user()->id) && isset($chapter->chapter_id))
	                {
		               	$this->setUserDownloadSession($request,Auth::user()->id);
		                $add_download_count = array(
		                    'user_id'               => isset(Auth::user()->id)?Auth::user()->id:0,
		                    'ebook_id'              => $chapter->ebook_id,
		                    'chapter_id'            => $chapter->chapter_id,
		                    'timestamp'             => time(), 
		                    'ip_address'            => $request->ip(),
		                    'content_download_type' => $content_download_type,
		                    'is_agree'              => 1,
		                    'download_file_type'    => $download_file_type,
		                    'session_id'            => session()->get('last_session_userid')
		                );
		                Chapter::AddChapterDownload($add_download_count);

	                    $add_download_count['investigation_type']=$investigation_type;
	                    $add_download_count['ip_address']=ip2long(\Request::ip());
	                 
	                    $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'            => $chapter->chapter_id,
	                            'content_type'          => 'c',
	                            'downloaded_on'         => time(),
	                            'ip'                    => $request->ip(),
	                        );

	                        BundleOffer::AddBundleOfferOrderContent($add_bundle_count);
	                    }

		            }

                }
            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['chapter_id'] != 0) {

            $query_check = "select * from chapter_access_investigation_report where (user_id = ".$data['user_id']." and ebook_id = ".$data['ebook_id']." and chapter_id = ".$data['chapter_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 chapter_access_investigation_report where (user_id = ".$data['user_id']." and ebook_id = ".$data['ebook_id']." and chapter_id = ".$data['chapter_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 chapter_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['chapter_id'] != 0) {

                       $this->setUserInvestigationSession($request, $user_id);
                       
                       $id = DB::table('chapter_access_investigation_report')->insertGetId(
                                        ['ebook_id' => $data['ebook_id'], 
                                        'chapter_id' => $data['chapter_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;
                    }
                }
            }
        }
    }

	function CheckIfChapterExist($param)
	{
		$ebook_id = $param['ebook_id'];
		$ebook_volume_id = $param['ebook_volume_id'];
		$chapter_no = $param['chapter_no'];
		
		if ($ebook_id && $ebook_volume_id && $chapter_no)
		{
			$ebook_id = $request->get('ebook_id');
			$ebook_volume_id = $request->get('ebook_volume_id');
			$chapter_no = $request->get('chapter_no');
			$chapter = Chapter::where('ebook_id',$ebook_id)
			->where('ebook_volume_id',$ebook_volume_id)
			->where('chapter_no',$chapter_no)
			->select('chapter_no')->first();
			$chapter_number = isset($chapter->chapter_no) ? $chapter->chapter_no : null;
			return response()->json(array('chapter_number' => $chapter_number), 200);		
		}
	}
	
	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 = $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;
	}

	/*
    get Chapter SGML 
     */

	public function chapter_GetSGML($chapter_id){
	
		$chapter_obj =	Chapter::GetChapterById($chapter_id);
		$ebook_obj =	Ebook::GetEbookById($chapter_obj->ebook_id);		
		$ebook_vol_obj = EbookVolume::GetEbookVolumeByVolumeId($chapter_obj->ebook_volume_id);

		
		$SGMFile = str_replace(".pdf", "", $chapter_obj->file_name) .".sgm";
		
		//$fh = fopen($SGMFile, 'w') or die("can't open file");
		
		$str = "<!DOCTYPE header SYSTEM \"SSSH2.dtd\" >\r\n";	
		$str .= "<header>\r\n";	
		$str .= "<pinfo>\r\n";
		$str .= "<pnm>Bentham Science Publishers\r\n";
		$str .= "<loc>ebook\r\n";
		$str .= "<jinfo>\r\n";
		$str .= "<jtl>".$ebook_obj[0]->title."\r\n";
		$str .= "<jsbt>\r\n";
		$str .= "<issn>".$ebook_vol_obj->eisbn."\r\n";
		$str .= "<pubinfo>\r\n";
		$str .= "<vid>".$ebook_vol_obj->volume_name."\r\n";
		$str .= "<iid>1\r\n";
		$str .= "<cd>".getMonthFromId(Date('m',$chapter_obj->created))." ".Date('Y',$chapter_obj->created)."\r\n";
		$str .= "<genhdr language=\"EN\">\r\n";
		$str .= "<artinfo>\r\n";
		$str .= "<altid>\r\n";
		$str .= "<artty RV>\r\n";
		$str .= "<ppct count =\"".$chapter_obj->page_count."\">\r\n";
		$str .= "<ppf>".$chapter_obj->first_page."\r\n";
		$str .= "<ppl>".$chapter_obj->last_page."\r\n";
		$str .= "<crn>Copyright (c) ".Date("Y")." Bentham Science Publishers\r\n";
		$str .= "<atl>".str_replace("&amp;amp;", "&",  htmlentities($chapter_obj->title, ENT_QUOTES, 'UTF-8'))."\r\n";
		$str .= "<aug>\r\n";
		
		//Get author data
		$result_authors  = Author::getAuthorDataById($chapter_id, 'chapter_id');
        $strAff='';
        if(!empty($result_authors)){
	        foreach($result_authors as $author){        
	            
	            $str .= "<au>\r\n";
	            $str .= "<fnms>".$author->first_name."</fnms>\r\n";
	            $str .= "<inits>".$author->initials."</inits>\r\n";
	            $str .= "<snm>".$author->last_name."</snm>\r\n";
	          
	            if($author->country=='0')
	            {
	              $country="";
	            }
	            else
	            {}
	            
	            if((trim($author->web_view) != "")) 
	               { $str .= "<aff>".rtrim($author->web_view, ',')."</aff>\r\n";}
	         
	              else if(trim($author->author_affiliation) != "" )
	              {  $str .= "<aff>".rtrim($author->author_affiliation, ',')."</aff>\r\n";}
	              else if(trim($author->country) != "")
	              {$str .= "<aff>".$author->country."</aff>\r\n";}

	            else
	            {$str .= "<aff></aff>\r\n";}
	          
	                  
	            $str .= "</au>\r\n";
	            
	        }
    	}
		
		$strAff = substr($strAff, 0, -1); 
		$str .= "<aff>".str_replace("&amp;amp;", "&",  htmlentities($strAff, ENT_QUOTES, 'UTF-8'))."\r\n";
		$str .= "</aug>\r\n";
		$str .= "<abs>\r\n";
		$str .= "<p>\r\n";
		$str .= str_replace("&amp;amp;", "&",  htmlentities($chapter_obj->abstract, ENT_QUOTES, 'UTF-8')) ."\r\n";
		$str .= "</p>\r\n";
		$str .= "</abs>\r\n";
		
		//Get keyword data
		$str .= "<kwdg>\r\n";
		$result_keywords = Keywords::getKeywordDataById($chapter_id, 'chapter_id');
        if(!empty($result_keywords)){
            foreach($result_keywords as $data){        
              $str .= "<kwd>".ltrim(str_replace("&amp;amp;", "&",  htmlentities($data->keyword, ENT_QUOTES, 'UTF-8')))."</kwd>\r\n";    
            }
        }
		
		$str .= "</kwdg>\r\n";
		
		$str .= "</header>\r\n";
		
		header('Cache-Control: must-revalidate');
		header("Content-Type: application/xml");

	    header("Content-Disposition: attachment; filename=\"{$SGMFile}\"");
		print($str); exit;
		
	}
      public function DeleteChapterFile(Request $request,$chapter_id,$file_type)
      {
                $user                     = Auth::user();
                //-----------------------------Insert into log table-----------------------------------
                $chapter     = Chapter::GetChapterById($chapter_id);
                $log = (array) $chapter;
                $add_log     = array(
                    'content_id'      => $chapter_id,
                    'content_type_id' => config('constants.log_content_types.Chapter'),
                    '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);
                //--------------------------------------------------------------

                $update_chapter['chapter_id']       = $chapter_id;
                $update_chapter[$file_type]         = NULL;
                $update_chapter['last_modified']    = time();
                $update_chapter['updated_by']       = $user->id;

                Chapter::where('chapter_id', $chapter_id)->update($update_chapter);

        
                return redirect()->back();
    }
	  
	public function AddAccessDenail($DownloadAccess,$ebook_volume_id,$chapter_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) //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['c_id'] = $chapter_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::InsertChapterAccessDenail($access_denail_data);
						}
					}	
				}				
			}
		}
	}
	
	public function CheckUserAccessOnChapter($request,$chapter,$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 = $chapter->ebook_id;
			$volume_id = $chapter->ebook_volume_id;
			$chapter_id = $chapter->chapter_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['volume_id'] = $volume_id;
			
			$trail_access = UserAccess::GetUserAccessOnContent($v_param);
			
			if(empty($trail_access[0]))
			{
				// Check User Access Trail (Trail) Chapter Level 
				$a_param['access_type_id'] = 111;
				$a_param['access_on'] = 'chapter';
				$a_param['user_id'] = session()->get('user_id');
				$a_param['ip_address'] = $request->ip();
				$a_param['chapter_id'] = $chapter_id;
				
				$trail_access = UserAccess::GetUserAccessOnContent($a_param);
			}
			
			if(!empty($trail_access[0])  && $user_access->view_option==0)
			{
				
				$query_download_check = "select count(*) total FROM download_count_chapter where ebook_id = " . $ebook_id . " and user_id = " . $user_access->user_id;
				$trial_count          = DB::select($query_download_check);
				$count                = $trial_count[0]->total;
				
				if ($count >= 5)
				{
					Session::flash('message', "You have Trial Access and you have already downloaded " . $count . " Chapters ");
					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_chapter_access where user_id = ".$user_id." and chapter_id = ".$chapter_id);
                foreach ($res_obj as $row)
                {
                    $query1 = DB::select("insert into perpetual_history (user_id, type, type_id, order_id)
                                            values (".$row->user_id.",'c',".$row->chapter_id.",".$row->order_id." )" );
                    $query2 = DB::select(" delete from perpetual_chapter_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, $chapter_id, 'c', $user_access);
                }
				else 
				{
                    UserAccess::UpdateRestrictedUserInfo($restricted_user_access_key, $user_name, $clientIP, $chapter_id, 'c', $user_access);
                }
            }
        }    
		
		return true;
	}

	public function ValidateAPIHost($host)
	{

        $count = DB::select("select count(*) as total from api_hosts where host='$host' and status='A'");
      if($count>0){
        return true;
      }else{
        return false;
      }
    }

    public function DirectChapterDownload($request,$chapter_id)
    {
    $param = array();
    $aparam = array();
    $download_type = array();
    $DownloadAccess = false;
    $content_id = $chapter_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;

                $chapter = Chapter::where('chapter_id', '=', $chapter_id)->first();

                // chapter existing check
                if(!empty($chapter))
                {
                    $chapter_id     = $chapter->chapter_id;
                    $chapter_nid    = $chapter->chapter_nid;
                    $ebook_volume_id = $chapter->ebook_volume_id;
                    $ebook_id     	= $chapter->ebook_id;

					$chapter_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $chapter_id, "c");
					if ($chapter_access[0]->total_count > 0)
					{
						$DownloadAccess = true;
						if ($chapter_access[0]->access_type == 1) 
						{
							$content_download_type = 'F';	
						}
						else
						{
							$content_download_type = 'FO';
						}
					}

					//check ebook volume level content access
					if (!$DownloadAccess) {
						$ebook_access = ContentAccess::CheckOpenFreeAcccessWithType("ebook_access", $ebook_volume_id, "v");
						
						if ($ebook_access[0]->total_count > 0) {
							$DownloadAccess        = true;
							$free                  = true;
							if ($chapter_access[0]->access_type == 1) 
							{
								$content_download_type = 'F';	
							}
							else
							{
								$content_download_type = 'FO';
							}
						}
					}

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

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

					if (!$DownloadAccess) 
					{
						// Check User Access Ebook Volume Level 
						$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])) 
						{
			                $parama['user_access_id']=$ua_volume_lvl[0]->user_access_id;
			                $user_access_info = UserAccess::GetUserAccess($parama);   
			                
			                $view_option                 = $user_access_info->view_option;
							$user_access_id         	 = $ua_volume_lvl[0]->user_access_id;
							$content_download_type       = $ua_volume_lvl[0]->content_download_type;
							$access_base_text            = $ua_volume_lvl[0]->access_base_text;
							$restricted_user_access_key  = $ua_volume_lvl[0]->restricted_user_access_key;
							$restricted_user_access_type = $ua_volume_lvl[0]->restricted_user_access_type;
							$type 						 = $ua_volume_lvl[0]->type;
                            
                            if($view_option == 0)
                            {
                                $DownloadAccess = $ua_volume_lvl[0]->volume_id;
                            }

						}
					}
					
					if (!$DownloadAccess) 
					{
						// Check User Access Chapter Level 
						$p_article['chapter_id'] = $chapter_id;
						$p_article['user_id'] = session()->get('user_id');
						$p_article['ip_address'] = $request->ip();
			            $p_article['disease_access'] = "chapter";

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

						$ua_chapter_lvl = UserAccess::GetAllContentUserAccess($p_article,array($access=>true));

						if (!empty($ua_chapter_lvl[0])) 
						{
			                $param['user_access_id']=$ua_chapter_lvl[0]->user_access_id;
			                $user_access_info = UserAccess::GetUserAccess($param);   
			                
			                $view_option                 = $user_access_info->view_option;
							$user_access_id         	 = $ua_chapter_lvl[0]->user_access_id;
							$content_download_type       = $ua_chapter_lvl[0]->content_download_type;
							$access_base_text            = $ua_chapter_lvl[0]->access_base_text;
							$restricted_user_access_key  = $ua_chapter_lvl[0]->restricted_user_access_key;
							$restricted_user_access_type = $ua_chapter_lvl[0]->restricted_user_access_type;
							$type 						 = $ua_chapter_lvl[0]->type;

                            if($view_option == 0)
                            {
                                $DownloadAccess = $ua_chapter_lvl[0]->chapter_id;
                            }
						}
					}
                }
                    if(!$DownloadAccess)  {

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

                    }

                if($DownloadAccess)
                {

		            $chapter_gap=Chapter::ChapterDownloadGap($user_id,$chapter_id,$SecondsGap);            
		            if($chapter_gap->rcd > 0)
		              {  
		              	$last_session_userid = $request->session()->getId()."-".microtime(true);
		             	session(['last_session_userid' => $last_session_userid]);
		                DB::select("update download_count_chapter set timestamp=".time().", session_id='".session()->get('last_session_userid')."' where id='".$chapter_gap->id."'");

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

                    //Session::flash('message', "Success");
					if($user_id > 0  && isset($chapter->chapter_id))
					{
			            $download_file_type=1;
			            $investigation_type = 2;

						$this->setUserDownloadSession($request,$user_id);
						$add_download_count = array(
							'user_id'               => $user_id,
							'ebook_id'              => $chapter->ebook_id,
							'chapter_id'            => $chapter->chapter_id,
							'timestamp'             => time(), 
							'ip_address'            => $request->ip(),
							'content_download_type' => $content_download_type,
							'is_agree'              => 1,
							'download_file_type'    => $download_file_type,
							'session_id'            => session()->get('last_session_userid')
						);
						Chapter::AddChapterDownload($add_download_count);

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

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

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