<?php

namespace App\Http\Controllers;

use App\Models\Chapter;
use App\Models\Disease;
use App\Models\Ebook;
use App\Models\EbookVolume;
use App\Models\Journal;
use App\Models\Log;
use App\Models\Meta;
use App\Models\Node;
use App\Models\Subject;
use App\User;
use Auth;
use DB;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

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   = Subject::Subjects();
        $disease   = Disease::DiseaseParent();
        $publisher = Journal::Publisher();

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

    /**
     * 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 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();

        $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;
        }

        $subject   = Subject::Subjects();
        $disease   = Disease::DiseaseParent();
        $publisher = Journal::Publisher();

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

    /**
     * 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 Journal 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 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();
    }
}

