<?php

namespace App\Http\Controllers;

use App\Models\Chapter;
use App\Models\Disease;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\SDGProgramme;
use App\Models\Journal;
use App\Models\Log;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Subject;
use App\Models\Author;
use App\Models\Indexing;
use App\Models\Country;
use App\User;
use Auth;
use DB;
use File;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

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

    public function index(Request $request)
    {

        $editPermission   = false;
        $deletePermission = false;

        $search = $request->get('search');
        if (isset($search) && $search != "") {
            $ebook = Ebook::GetEbooks("", $search);
        } else {
            $ebook = Ebook::GetEbooks();
        }

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

        return view('admin.ebook.ebook', with([
            'ebook' => $ebook,
         'editPermission' => $editPermission,
            'deletePermission' => $deletePermission
        ]));
    }

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


        $disease   = Disease::DiseaseParent();
        $publisher = Journal::Publisher();
		$sdg_list  = SDGProgramme::getAllActiveSDG();

        return view('admin.ebook.addebook', with([
            'subject' => $arr,
         'disease' => $disease,
            'publisher' => $publisher,
			'sdg_list' => $sdg_list
        ]));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //--------------Add Ebook Validation------------------
        $validator = Validator::make($request->all(), [
            'subject_id' => 'required',
            'title'      => 'required',
        ]);

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

            try {
// try transaction start here for data integrity
                DB::beginTransaction();
                $file_name=null;
                //---------------------Inert into node table---------------
                $add_node = array(
                    'type' => 'ebook',
                    'title'                  => $request->input('title'),
                    'created'                => time()
                );

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

                //----------------------Upload eBook image-------------------------------
                $ebook_image_path = config('constants.admin.root_path') . 'E-books/BEN/';
                if ($request->hasfile('image_file_name')) {
                    $image_file = $request->file('image_file_name');
                    $file_name  = $image_file->getClientOriginalName();
                    if (!is_dir($ebook_image_path)) {
                        mkdir($ebook_image_path, 0755, true);
                    }
                    $image_file->move($ebook_image_path, $file_name);
                }

                //---------------------Inert into ebook table--------
                $add_ebook = array(
                    'image_file_name' => $file_name,
                    'nid'             => $node_id,
                    'publisher_id'    => $request->input('publisher_id'),
                    'title'           => $request->input('title'),
                    'left_panel'      => $request->input('left_panel'),
                    'right_panel'     => $request->input('right_panel'),
                    'created'         => time(),
                    'created_by'      => Auth::user()->id
                );

                $ebook_id = Ebook::Add($add_ebook);
                //-------------------Inert into Subject Ebook table---------------

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

                for ($c = 0; $c < count($subject_id); $c++) {
                    $add_ebook_subject[] = array(
                        'subject_id' => $subject_id[$c],
                        'ebook_id'   => $ebook_id
                    );
                }
                $subject = Subject::AddSubjectEbook($add_ebook_subject);

                //-------------------Inert into Ebook Sustainable Development Goals table---------------
                $sdg_id = $request->input('sdgs_id');
                if (!empty($sdg_id)) {
                    for ($d = 0; $d < count($sdg_id); $d++) {
                        $add_ebook_sdg[] = array(
                            'sdgs_id'          => $sdg_id[$d],
                            'ebook_id'         => $ebook_id,
                            'created_by'       =>  Auth::user()->id,
                            'created_on'       => time(),
                        );
                    }

                    $sdg_list = SDGProgramme::AddSDGEbook($add_ebook_sdg);
                }

                //-------------------Inert into Disease Ebook table---------------
                /*$disease_id = $request->input('disease_id');
                if (!empty($disease_id)) {
                    for ($b = 0; $b < count($disease_id); $b++) {
                        $add_ebook_disease[] = array('disease_id' => $disease_id[$b],
                            'ebook_id'                                => $ebook_id);
                    }
                    $disease = Disease::AddDiseaseEbook($add_ebook_disease);
                }*/
                //-------------------Inert into Node Meta table---------------

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

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

                //-----------------------------Insert into log table-----------------------------------
                $log     = array_merge($add_node_meta, $add_ebook);
                $add_log = array(
                    'content_id'      => $ebook_id,
                    'content_type_id' => config('constants.log_content_types.Ebook'),
                    '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/ebook');
            }
            return redirect()->route('ebook.index')->with('success', 'Ebook has been added.');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        echo "hello";
        // return view('admin.show',compact('journal'));
    }

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

        $selected_ebook = Ebook::GetEbooks($id);
        
        $selected_meta = Meta::NodeMeta($selected_ebook->nid);

        $selected_subject = Subject::SubjectEbook($selected_ebook->ebook_id, 'ebook_id');
        foreach ($selected_subject as $key => $value) {
            $ebooksubject[] = $value->subject_id;
        }

        $selected_disease = Disease::DiseaseEbook($selected_ebook->ebook_id, 'ebook_id');
        foreach ($selected_disease as $key => $value) {
            $ebookdisease[] = $value->disease_id;
        }

        $selected_sdgs = SDGProgramme::SDGEbook($selected_ebook->ebook_id, 'ebook_id');
        foreach ($selected_sdgs as $key => $value) {
            $ebooksdg[] = $value->sdgs_id;
        }

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


        $disease   = Disease::DiseaseParent();
        $publisher = Journal::Publisher();
        $sdg_list  = SDGProgramme::getAllActiveSDG();

        return view('admin.ebook.addebook', with([
            'user' => $user,
            'subject' => $arr,
             'disease' => $disease,
              'publisher' => $publisher,
               'selected_ebook' => $selected_ebook,
                'selected_meta' => $selected_meta,
                 'ebooksubject' => $ebooksubject,
            'ebookdisease' => $ebookdisease,
            'ebooksdg' => $ebooksdg,
            'sdg_list' => $sdg_list
        ]));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        //-------------- Ebook Validation------------------
        $validator = Validator::make($request->all(), [
            'subject_id' => 'required',
            'title'      => 'required',

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

            try {
// try transaction start here for data integrity
                DB::beginTransaction();
                //---------------------Update Ebook table--------------------
                $ebook_id  = $request->input('ebook_id');
                $ebook_nid = $request->input('ebook_nid');
                
                $ebook_obj = Ebook::GetEbookById($ebook_id)[0];                
                $file_name   = $ebook_obj->image_file_name;

                //----------------------Upload eBook image-------------------------------
                $ebook_image_path = config('constants.admin.root_path') . 'E-books/BEN/';
                if ($request->hasfile('image_file_name')) {
                    $image_file = $request->file('image_file_name');
                    $file_name  = $image_file->getClientOriginalName();                    
                    if (!is_dir($ebook_image_path)) {
                        mkdir($ebook_image_path, 0755, true);
                    }
                    $image_file->move($ebook_image_path, $file_name);
                }
                

                $update_ebook = array(
                    'ebook_id' => $ebook_id,
                    'ebook_nid'                      => $ebook_nid,
                    'image_file_name'                => $file_name,
                    'publisher_id'                   => $request->input('publisher_id'),
                    'title'                          => $request->input('title'),
                    'left_panel'                     => $request->input('left_panel'),
                    'right_panel'                    => $request->input('right_panel'),
                    'updated_by'                     => Auth::user()->id


                );

               
                Ebook::EbookUpdate($update_ebook);
                //-------------------Insert into Disease Ebook table---------------

                /*Disease::DeleteDiseaseEbook($ebook_id);
                $disease_id = $request->input('disease_id');

                if (!empty($disease_id)) {
                    for ($b = 0; $b < count($disease_id); $b++) {
                        $add_ebook_disease[] = array('disease_id' => $disease_id[$b],
                            'ebook_id'                                => $ebook_id);
                    }
                    $disease = Disease::AddDiseaseEbook($add_ebook_disease);
                }*/
                //-------------------Inert into Subject Ebook table---------------

                Subject::DeleteSubjectEbook($ebook_id);

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

                for ($c = 0; $c < count($subject_id); $c++) {
                    $add_ebook_subject[] = array('subject_id' => $subject_id[$c], 'ebook_id' => $ebook_id);
                }
                $subject = Subject::AddSubjectEbook($add_ebook_subject);

                //-------------------Inert into Ebook Sustainable Development Goals table---------------

                SDGProgramme::DeleteIndexingEbook($ebook_id);
                $sdg_id = $request->input('sdgs_id');
                if (!empty($sdg_id)) {
                    for ($e = 0; $e < count($sdg_id); $e++) {
                        $add_ebook_sdg[] = array(
                            'sdgs_id'          => $sdg_id[$e],
                            'ebook_id'         => $ebook_id,
                            'created_by'       => Auth::user()->id,
                            'created_on'       => time(),
                        );
                    }

                    $sdg_list = SDGProgramme::AddSDGEbook($add_ebook_sdg);
                }

                //-------------------Inert into Node Meta table---------------
                Meta::DeleteMeta($ebook_nid);

                $add_node_meta = array(
                    'nid' => $ebook_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);

                //-----------------------------Insert into log table-----------------------------------
                $log     = array_merge($add_node_meta, $update_ebook);
                $add_log = array(
                    'content_id'      => $ebook_id,
                    'content_type_id' => config('constants.log_content_types.Ebook'),
                    '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/ebook');
            }

            return redirect()->route('ebook.index')->with('success', 'Ebook has been updated.');
        }
    }

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

        $chapter_list      = Chapter::where('ebook_id', $id)->first();
        $ebook_volume_list = EbookVolume::where('ebook_id', $id)->first();

        if ($chapter_list || $ebook_volume_list) {
            return redirect()->route('ebook.index')->with('error', 'Ebook Child Table Record Already Exist');
        } else {
            try {
// try transaction start here for data integrity

                DB::beginTransaction();
                $nid = $request->input('id');
                Subject::DeleteSubjectEbook($id);
                Disease::DeleteDiseaseEbook($id);
                Node::DeleteNode($nid);
                Meta::DeleteMeta($nid);
                Ebook::DeleteEbook($id);
                //-------------------------------------------------------------------------------------
                DB::commit();
            } catch (Exception $e) {

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

            return redirect()->route('ebook.index')->with('success', 'Ebook delete successfully.');
        }
    }

    public function DeleteEbookFile(Request $request,$ebook_id, $file_type)
    {
        $user = Auth::user();
        //-----------------------------Insert into log table-----------------------------------
        $ebook = Ebook::where('ebook_id', $ebook_id)->first();
        $log     = (array) $ebook;
        $add_log = array(
            'content_id'      => $ebook_id,
            'content_type_id' => config('constants.log_content_types.Ebook'),
            'action'          => config('constants.log_action_types.delete_file'),
            'log_data'        => json_encode($log),
            'created_dated'   => time(),
            'created_by'      => Auth::user()->id,
            'ip'              => ip2long($request->ip()),
        );
        $log = Log::AddLog($add_log);
        //--------------------------------------------------------------
        if($file_type == "image_file_name")
        {
           $filename=config('constants.admin.root_path').'E-books/BEN/'.$ebook->image_file_name;

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

            Ebook::where('ebook_id', $ebook_id)->update($update_ebook);
            }
        }

        return redirect()->back();
    }

    public function DownloadBookCatalog()
    {
        // Get data from Ebook model
        $book = Ebook::GetBookCatalog();
    
        // Create a new Spreadsheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
    
        // Set headers
        $headers = [
            "Full Title (eBook)", "Discipline 1", "Discipline 2", "eISBN", "Print ISBN (Hardback/Hardcover)",
            "Print ISBN (Paperback/Softcover)", "Status (Pub)", "Type", "eISSN", "ISSN", "Series Title", "Volume",
            "Editor", "Author", "Co-Editor", "Publication Year", "Currency", "E-book Price (Single User / Non-Library Access)",
            "Library Price (Multi-user Price)", "Print-on-Demand Price", "PDF+POD Price", "No of Pages", "Publisher",
            "Description", "Textbook", "Reference", "Handbook", "Atlas", "SDG", "DOI", "Indexed In",
            "Shortlink", "Eurekaselect url", "BSP Link", "BSP Sample Link"
        ];
        $sheet->fromArray([$headers], NULL, 'A1');
    
        $row = 2; // Start from the second row
    
        foreach ($book as $catalogs) {
            
            $eisbn = str_replace('-', '', $catalogs->eisbn);
            $isbn  = str_replace('-', '', $catalogs->isbn);

            if ($catalogs->ebook_type == 2) {
                $sheet->setCellValue('A' . $row, str_replace(',', ' ', strip_tags($catalogs->title)) . " Volume " . $catalogs->volume_name);
            } elseif (!empty($catalogs->ebook_subtitle)) {
                $sheet->setCellValue('A' . $row, str_replace(',', ' ', strip_tags($catalogs->title)) . " " . str_replace(',', ' ', strip_tags($catalogs->ebook_subtitle)));
            } else {
                $sheet->setCellValue('A' . $row, str_replace(',', ' ', strip_tags($catalogs->title)));
            }

            $subject = Subject::GetSubjectParentbyEbookId($catalogs->ebook_id);
    
            if (!empty($subject->parent_title) && !empty($subject->subject_title)) {
                $sheet->setCellValue('B' . $row, $subject->parent_title);
                $sheet->setCellValue('C' . $row, $subject->subject_title);
            } elseif (!empty($subject->parent_title) && empty($subject->subject_title)) {
                $sheet->setCellValue('B' . $row, $subject->parent_title);
                $sheet->setCellValue('C' . $row, '');
            } elseif (empty($subject->parent_title) && !empty($subject->subject_title)) {
                $sheet->setCellValue('B' . $row, $subject->subject_title);
                $sheet->setCellValue('C' . $row, '');
            } else {
                $sheet->setCellValue('B' . $row, '');
                $sheet->setCellValue('C' . $row, '');
            }
    
           // Set the cell values without scientific notation
            $sheet->setCellValueExplicit('D' . $row, $eisbn, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            $sheet->setCellValueExplicit('E' . $row, $isbn, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
			
            $sheet->setCellValue('F' . $row, '');  // Placeholder for Print ISBN
    
            if ($catalogs->published == 1) {
                $sheet->setCellValue('G' . $row, 'Published');
            } else {
                $sheet->setCellValue('G' . $row, 'Not Published');
            }
    
            if ($catalogs->content_type_access_id == null) {
                $sheet->setCellValue('H' . $row, 'Purchase');
            } elseif ($catalogs->content_type_access_id == 2) {
                $sheet->setCellValue('H' . $row, 'Open Access');
            }
    
            $sheet->setCellValue('I' . $row, $catalogs->eissn);
            $sheet->setCellValue('J' . $row, $catalogs->issn);
			
            if ($catalogs->ebook_type == 2) {
                $sheet->setCellValue('K' . $row, str_replace(',', ' ', strip_tags($catalogs->ebook_subtitle)));
            } else {
                $sheet->setCellValue('K' . $row, '');
            }
			
            $sheet->setCellValue('L' . $row, $catalogs->volume_name);
    
            $result_authors = Author::GetBookAuthorbyEbookVolumeId($catalogs->ebook_volume_id);
    
            $sheet->setCellValue('M' . $row, $result_authors->editor);
            $sheet->setCellValue('N' . $row, $result_authors->author);
            $sheet->setCellValue('O' . $row, $result_authors->co_editor);
    
            $timestamp = $catalogs->publication_date;
            $carbonDate = Carbon::createFromTimestamp($timestamp);
            $year = $carbonDate->year;
            $sheet->setCellValue('P' . $row, $year);
    
            $sheet->setCellValue('Q' . $row, 'USD');
            if ($catalogs->ebook_status == 2 || $catalogs->ebook_status == 3) {
                $sheet->setCellValue('R' . $row, 'TBA');
                $sheet->setCellValue('S' . $row, 'TBA');
                $sheet->setCellValue('T' . $row, 'TBA');
                $sheet->setCellValue('U' . $row, 'TBA');
            } elseif ($catalogs->content_type_access_id == 2) {
                $sheet->setCellValue('R' . $row, 'Open Access');
                $sheet->setCellValue('S' . $row, 'Open Access');
                $sheet->setCellValue('T' . $row, $catalogs->ebook_price_pod);
                $sheet->setCellValue('U' . $row, 'Open Access');
            } else {
                $sheet->setCellValue('R' . $row, $catalogs->ebook_price);
                $sheet->setCellValue('S' . $row, $catalogs->ebook_price * 4);
                $sheet->setCellValue('T' . $row, $catalogs->ebook_price_pod);
                $sheet->setCellValue('U' . $row, $catalogs->ebook_price_podandpdf);
            }

            $page_count = Chapter::GetTotalPagesbyEbookVolumeId($catalogs->ebook_volume_id);
            $sheet->setCellValue('V' . $row, round($page_count));
    
            $sheet->setCellValue('W' . $row, 'Bentham Science Publishers');
    
            $introduction = htmlspecialchars($catalogs->introduction, ENT_QUOTES);
            $introduction = str_replace(',', ' ', $introduction);
            $sheet->setCellValue('X' . $row, $introduction);
    
            $sheet->setCellValue('Y' . $row, '');  // Placeholder for Textbook
            $sheet->setCellValue('Z' . $row, ''); // Placeholder for Reference
            $sheet->setCellValue('AA' . $row, ''); // Placeholder for Handbook
            $sheet->setCellValue('AB' . $row, ''); // Placeholder for Atlas
    
            $ebook_sdg = SDGProgramme::SDGEbook($catalogs->ebook_id, 'ebook_id');
    
            if (!empty($ebook_sdg)) {
                $sheet->setCellValue('AC' . $row, 'True');
            } else {
                $sheet->setCellValue('AC' . $row, 'False');
            }
    
            $sheet->setCellValue('AD' . $row, $catalogs->doi);
    
            $ebook_indexing = Indexing::GetIndexingTitlebyEbookVolumeId($catalogs->ebook_volume_id);
    
            if (!empty($ebook_indexing)) {
                $sheet->setCellValue('AE' . $row, $ebook_indexing->indexing_title);
            } else {
                $sheet->setCellValue('AE' . $row, '');
            }
    
            $sheet->setCellValue('AF' . $row, ''); // Placeholder for Shortlink
            $sheet->setCellValue('AG' . $row, 'https://www.eurekaselect.com/ebook_volume/' . $catalogs->ebook_volume_id);
            $sheet->setCellValue('AH' . $row, 'https://benthambooks.com/book/' . $eisbn);
            $sheet->setCellValue('AI' . $row, 'https://benthambooks.com/sample/' . $eisbn . '/1');
    
            $row++;
        }
		
		// Date cell
        $row++;
        $lastRow = $row;
        $sheet->mergeCells('A' . $lastRow . ':AI' . $lastRow);
        $sheet->setCellValue('A' . $lastRow, 'Download Date: ' . Carbon::now()->toDateString());
        $sheet->getStyle('A' . $lastRow . ':AI' . $lastRow)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('A' . $lastRow . ':AI' . $lastRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A0EC95');
        $sheet->getStyle('A' . $lastRow . ':AI' . $lastRow)->getFont()->setBold(true)->setSize(14);
    
        // Create the Excel file
        $writer = new Xlsx($spreadsheet);
        $filename = "eBookCatalog.xlsx";
    
        // Set headers for download
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
    
        // Save the file to output
        $writer->save('php://output');
        exit;
    }

    public function BookTrialRequest(Request $request)
    {
        if ($request->method() == 'POST') {

            try {
                DB::beginTransaction();

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

                $book_trial_request = array(
                    'institution_name'      => $request->input('institution_name'),
                    'institution_country'   => $request->input('institution_country'),
                    'first_name'            => $request->input('first_name'),
                    'last_name'             => $request->input('last_name'),
                    'email'                 => $request->input('email'),
                    'comments'              => $request->input('comments'),
                    'created_at'            => date("Y-m-d h:i:s", time()),
                    'status'                => 'A',
                    'ip'                    => ip2long($request->ip()),
                );
                $trial_request_id = Ebook::AddBookTrialRequest($book_trial_request);
                if (isset(Auth::user()->id)) {
                    $login_id = Auth::user()->id;
                } else {
                    $login_id = 0;
                }

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

                DB::commit();
                if ($trial_request_id > 0) {

                    $book_trial_request['journal_title'] = 'Trial Request for EBook';

                    $to   = 'faizan@benthamscience.net';
                    $from = 'support@benthamscience.net';
                    $cc   = 'azhar@benthamscience.net';
                    $bcc  = 'taimur@benthamscience.net';

                    $subject = "Trial Request for EBook";

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

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

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

            return view('includes.book_trial_requests', ['country' => $country]);
        }
    }
}
