<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendEmail;

class SettingsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function __construct(){
        $this->middleware('auth');
    }

    /**

    MAIN PAGE
    
    **/

    public function index(Request $request)
    {

        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }

        $added_by = Auth::user()->id;

        ##data for reports
        try{
        $reports_status = DB::table('reports_enabled')
        ->select('year','quarters','updated_at','id')
        ->where('added_by',$added_by)
        ->paginate(25, ['*'], 'status');
        //->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }


        ##data for emails
        try{
           $email_types =  DB::table('email_types')->select('email_type','id')->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }

        ##already added email content
        try{
           $email_content =  DB::table('email_content')
                            ->select('email_content.id','email_content.email_title','email_content.email_content','email_content.email_type','email_types.email_type as type_name','email_content.updated_at')
                            ->leftJoin('email_types', function ($join) {
                                $join->on('email_content.email_type', '=', 'email_types.id');
                            })
                            ->where('email_content.added_by',$added_by)
                            ->where('email_content.email_type',"!=",2)
                            ->paginate(25, ['*'], 'content');
        }catch(\Exception $e){
            return $e->getMessage();
        }


        ##data for sending email tab

        try{
            $email_send_data = DB::table('email_content')->select('id','email_title')->where('added_by',$added_by)->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }


        try{
            $contributors = DB::table('users')
            ->select('users.id','users.name','users.email')
            ->leftJoin('assign_contributors', function ($join) {
                $join->on('users.id', '=', 'assign_contributors.contributor_id');
            })
            ->leftJoin('book_details', function ($join) {
                $join->on('assign_contributors.book_id', '=', 'book_details.id');
            })
            ->where('users.added_by',$added_by)
            ->where('users.merged_contributor','!=',1)
            ->where('assign_contributors.id','!=','')
            ->where('users.email','!=',null)
            ->where('users.email','!=','')
            ->where('book_details.merged_book','!=',1)
            ->orderby('users.name','asc')
            ->distinct()
            ->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }

        #email history
        try{
            $email_history = DB::table('email_history')
            ->select('email_content.email_title','email_content.email_content','email_types.email_type','email_history.created_at','email_history.id','email_history.contributor_id')
            ->leftJoin('email_content', function ($join) {
                $join->on('email_history.email_content', '=', 'email_content.id');
            })
            ->leftJoin('email_types', function ($join) {
                $join->on('email_content.email_type', '=', 'email_types.id');
            })
            ->where('email_history.added_by',$added_by)
            ->where('email_history.enable_view','!=',0)
            ->orderby('email_history.created_at','desc')
            ->paginate(25, ['*'], 'history');
        }catch(\Exception $e){
            return $e->getMessage();
        }


        ##book details : FOR DISABLED BOOK
        try{
            $bookdata = DB::table('book_details')
            ->select('book_details.id','book_details.book_title','book_details.merged_book','book_details.disabled_book','book_details.disabled_date')
            ->where('book_details.added_by',$added_by)
            ->where(function($q) use ($request ){
                if(isset($_GET['searched_val'])) {
                    $q->orWhere('book_title', 'like', '%'.$_GET['searched_val'].'%');
                    $q->orWhere('isbn_code', 'like', '%'.$_GET['searched_val'].'%');
                    $q->orWhere('isbn_code2', 'like', '%'.$_GET['searched_val'].'%');
                    $q->orWhere('isbn_code3', 'like', '%'.$_GET['searched_val'].'%');
                }
            })
            ->where(function ($query) {
                $query->where('book_details.merged_book','!=',1)
                    ->orWhereNull('book_details.merged_book');
            })
            ->orderby('book_details.disabled_date','desc')
            ->orderby('book_title','asc')
            ->paginate(25, ['*'], 'book');
        }catch(\Exception $e){
            return $e->getMessage(); 
        }
        if(isset($_GET['searched_val'])){
            #appending search
            $bookdata->appends(['searched_val' =>$_GET['searched_val']]);
            if (count($bookdata) == 0) { //if no records found
                if(isset($_GET['searched_val'])){
                $searched_item3 =  $_GET['searched_val'];
                $nothingfound_book = "We can't find any item matching your search";
                return redirect('settings#enable_books')->with(compact('nothingfound_book', 'searched_item3','platformsession'));
                }
            }
        }
        return view('settings',compact('reports_status','email_types','email_content','email_send_data','contributors','email_history','bookdata'));
    } #index status ends here


    /**
    
    DELETE REPORT STATUS
    
    **/

    public function delete_status(Request $request)
    {
        
        #if delete report record is cliicked
        if(isset($request->del_id)){
            #check if id is not empty
            if(empty($request->del_id)){

                $request->session()->flash('myerror', 'The status id does not exists.');
                return redirect('settings')->with(compact('myerror'));
            }

            #check if id exists in the db
            try{
                $check_id = DB::table('reports_enabled')->select('year')->where('id',$request->del_id)->get()->toArray();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            #return error message
            if(empty($check_id)){

                $request->session()->flash('myerror', 'The status id does not exists.');
                return redirect('settings')->with(compact('myerror'));

                return redirect('settings')->with(compact('myerror', 'The status id does not exists.'));
            }

            #process to delete is here
            try{
               $del_id = DB::table('reports_enabled')->where('id',$request->del_id)->delete();
               
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if($del_id == 1){
                $request->session()->flash('mysuccess', 'Report Status deleted Successfully.');
                return redirect('settings')->with(compact('mysuccess'));
            }
        }

        #to remove the email history from the list
        if(isset($request->del_id_history)){

            if(empty($request->del_id_history)){
                $request->session()->flash('myerror', 'The history id does not exists.');
                return redirect('settings')->with(compact('mysuccess'));
            }

            #check id in the db
            try{
            $check_id = DB::table('email_history')->select('email_content')->where('id',$request->del_id_history)->get();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if($check_id->isEmpty()){
                $request->session()->flash('myerror', 'The history id does not exists.');
                return redirect('settings#send_emails')->with(compact('myerror'));
            }

            #update the database
            $update_history = ['enable_view' => 0];

            try{
                $update_check = DB::table('email_history')->where('id',$request->del_id_history)->update($update_history);
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if($update_check == 1){
                $request->session()->flash('mysuccess', 'Email history removed Successfully.');
                return redirect('settings#send_emails')->with(compact('mysuccess'));
            }
            //print_r($update_check);die;
        }

    }#delete_status ends here

    /**

    OPEN POP-UP FOR UPDATE

    **/

    public function update_status_pop(Request $request)
    {
        $id = $request->status_id;
        $popup_type = $request->popup_type;
        $added_by = Auth::user()->id;

        #check if id is not empty
        if(!isset($request->status_id) || empty($request->status_id)){
            return response()->json(array(
                'msg'=> 'Please provide the status id.',
                'success'=>0,
            ));
        }

        ##modal for report status
        if($popup_type == 'report_status'){
            #check if id exists or not
            try{
                $check_id = DB::table('reports_enabled')->select('year')->where('id',$id)->get()->toArray();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if(empty($check_id)){
                return response()->json(array(
                    'msg'=> 'Status id does not exists.',
                    'success'=>0,
                ));
            }

            #get the data
            try{
                $data = DB::table('reports_enabled')->select('year','quarters')->where('added_by', $added_by)->where('id', $id)->first();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            $selected_qtrs = explode(',', $data->quarters);
            
           
               
            if($data->year == date('Y')){

                #getting current date quarter
                $current = floor((date('n') - 1) / 3);
                $current_year = date('Y');
                $year = date('y');
                $quarters = array();
                $q = "";
                $mysql_qty = "";

                for ($i = 0; $i < 5; $i++){
                    $q = (($current+$i)%4) + 1;
                }

                for($v = 1; $v <= $q; $v++){
                    $all_qtrs[] = $v;
                }
                
            }else{
                $all_qtrs = [1,2,3,4];
            }

            $un_selected = array_diff($all_qtrs, $selected_qtrs);
            
            $html = '<div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><img src="images/cross.png" /></button><h4 class="modal-title">Update Reports Status</h4></div><form action="'.url('/update_status').'" id="update_status_exist" method="POST"> 
            <div class="modal-body"><table class="contributor_assign_table append__contri_table" style="width:100%"><tbody><tr><th>Year</th><th>Quarters</th></tr><tr><td> <div class="input_container"><input type="number" value="'.$data->year.'" disabled></div></td><td class="append_qtr"><select id="enable_qtrs" multiple="multiple" name="qtrs[]">';
                 foreach($selected_qtrs as $qtr){

                   $html .='<option value="'.$qtr.'" selected="selected">'.$qtr.'</option>';
                }

                foreach($un_selected as $qtr){
                    $html .='<option value="'.$qtr.'">'.$qtr.'</option>';
                }  
            $html .= '</select></td></tr></tbody></table><input type="hidden" name="up_year" value="'.$data->year.'" ><input type="hidden" name="status_id" value="'.$id.'" ></div><div class="modal-footer"><input class="popup_btn " type="submit" name="up_st_submit" value="Update"></div></form>';   

            if(!empty($html)){
                return response()->json(array(
                    'msg'=> 'Status exists.',
                    'success'=>1,
                    'html'=>$html,
                ));
            }
        }


        ##modal for email content
        if($popup_type == 'email_content'){
            //print_r($request->all()); die;
            #check if id exists or not
            try{
                $check_id = DB::table('email_content')->select('email_title')->where('id',$id)->get()->toArray();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if(empty($check_id)){
                return response()->json(array(
                    'msg'=> 'Status id does not exists.',
                    'success'=>0,
                ));
            }

            #get the data
            try{
               $email_content =  DB::table('email_content')
                                ->select('email_content.id','email_content.email_title','email_content.email_content','email_content.email_type','email_types.email_type as type_name','email_types.id as type_id')
                                ->leftJoin('email_types', function ($join) {
                                    $join->on('email_content.email_type', '=', 'email_types.id');
                                })
                                ->where('email_content.added_by',$added_by)
                                ->where('email_content.id',$id)
                                ->first();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            #get all the email types
            try{
                $email_types = DB::table('email_types')->select('id as type_ids','email_type')->get();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            $html = '';
            $html .= '<div class="modal-header"><button type="button" class="close" data-dismiss="modal"><img src="images/cross.png" /></button><h4 class="modal-title">Edit email content</h4></div><form action="'.url('/update_content').'" id="add_email_content" method="POST" ><div class="modal-body"><div class="label_field"><label>Email Type</label><div class="input_container"><select name="email_type" id="email_type" required>';
            foreach( $email_types as $types){
                if($email_content->type_id == $types->type_ids){

                    $html .= '<option value="'.$types->type_ids.'" selected>'.$types->email_type.'</option>';
                }else{
                    $html .= '<option value="'.$types->type_ids.'">'.$types->email_type.'</option>';
                }
            }

            $content = preg_replace('/<br\s?\/?>/ius', "\n", str_replace("\n","",str_replace("\r","", htmlspecialchars_decode($email_content->email_content))));
            
            $html .= '</select></div></div><div class="label_field"><label>Subject</label><div class="input_container"><input type="text" name="email_title" class="e_title" value="'.$email_content->email_title.'" required></div></div><div class="label_field"><label>Email Content</label><div class="input_container">Keywords : <input type="button" value="creator name" class="new_text_btn"  data-keyword="@creator_name" id="text_'.$email_content->id.'" ><textarea contenteditable name="email_content" class="email_content_txt" id="text_'.$email_content->id.'" required>'.($content).'</textarea></div></div></div><div class="modal-footer"><input type="submit" value="Save Content" class="save_form_edit_book"></div></div><input type="hidden" name="content_id" value="'.$email_content->id.'" ></form>';

            if(!empty($html)){
                return response()->json(array(
                    'msg'=> 'Status exists.',
                    'success'=>1,
                    'html'=>$html,
                ));
            }
        }

        ##pop-up to view email sent
        if($popup_type == 'view_email'){

            #check if id exists or not
            try{
                $check_id = DB::table('email_history')->select('email_content')->where('id',$id)->get()->toArray();
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if(empty($check_id)){
                return response()->json(array(
                    'msg'=> 'History id does not exists.',
                    'success'=>0,
                ));
            }

            #get the content
            try{
                $email_history = DB::table('email_history')
                ->select('email_content.email_title','email_content.email_content','email_types.email_type','email_history.created_at','email_history.id','email_history.contributor_id')
                ->leftJoin('email_content', function ($join) {
                    $join->on('email_history.email_content', '=', 'email_content.id');
                })
                ->leftJoin('email_types', function ($join) {
                    $join->on('email_content.email_type', '=', 'email_types.id');
                })
               
                ->where('email_history.id',$id)
                ->orderby('email_history.created_at','asc')
                ->first();
            }catch(\Exception $e){
                return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                ));
            }



            if (strpos($email_history->contributor_id, ',') !== false) {
                #contributor names
                $contri_id = explode(",",$email_history->contributor_id);
            }else{
                $contri_id[] = $email_history->contributor_id;
            }

            

            #GET contributors name
            try{
                $contributors = DB::table('users')->wherein('id',$contri_id)->pluck('name')->toArray();
            }catch(\Exception $e){
                return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                ));
            }

            $contributors = implode(',', $contributors);

            #add some space here!!
            if (strpos($contributors, ',') !== false) {
                $contributors = str_replace(",",' , ',$contributors);
            }else{
                $contributors = $contributors;
            }

            
            if (strlen($contributors) <= 50) {
                $contri_html = $contributors;
            }else if (strlen($contributors) >  50) {
                $length_emails = strlen($contributors);
                $contri_html = substr($contributors, 0, 50);
                $contri_html .= "<span class='show_emails_span'>".substr($contributors, 50,$length_emails)."</span> <span id='show' class='blue_link'>Show More</span>";
                
            }


            #create html
            $html = '';
            $html .= '<div class="modal-header"><button type="button" class="close" data-dismiss="modal"><img src="images/cross.png" /></button><h4 class="modal-title">Email Sent</h4></div>';
            $html .= '<div class="modal-body contri_table"><table class="listing"><tr><th><div class="contri_info"><h5>Sent :</h5></div></th><td><div class="contri_info"><h5> <span class="addexpense_book">'.date_format(date_create($email_history->created_at),"d M, Y").'</span></h5></div></td></tr><tr><th><div class="contri_info"><h5>Subject : </h5></div></th><td><div class="contri_info"><h5><span class="addexpense_book">'.$email_history->email_title.'</span></h5></div></td></tr><tr><th>To : </th><td>'.$contri_html.'</td></tr><tr><th>
            Email Type : </th><td>'.$email_history->email_type.'</td></tr><tr><th>
            Content : </th><td>'.$email_history->email_content.'</td></tr></table></div>';
            
            $html .= '<div class="modal-footer"><input type="button" data-dismiss="modal" value="Okay" class="save_form_edit_book"></div></div>';

            if(!empty($html)){
                return response()->json(array(
                    'msg'=> 'Status exists.',
                    'success'=>1,
                    'html'=>$html,
                ));
            }
        }

    }#update_status_pop ends here

    
    /**

    UPDATE THE REPORT STATUS HERE

    **/

 
    public function update_status(Request $request)
    {

        if(empty($request->qtrs)){
            $quarters = array();
        }else{
            $quarters = implode(',', $request->qtrs);
        }
        
        $year = $request->up_year;
        $added_by = Auth::user()->id;




        #means update the value
        if(isset($request->status_id) && !empty($quarters)){
            try{
                $update_val = DB::table('reports_enabled')->where('id', $request->status_id)->update(['quarters'=>$quarters]);
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if($update_val == 1){

                $request->session()->flash('mysuccess', 'All Changes are saved.');
                return redirect('settings')->with(compact('mysuccess'));
            }
            if($update_val == 0){

                $request->session()->flash('myerror', 'No changes were done.');
                return redirect('settings')->with(compact('myerror'));
            }
        }

        #means delete the entry
        else if(isset($request->status_id) && empty($quarters)){
            #process to delete is here
            /*try{
               $del_id = DB::table('reports_enabled')->where('id',$request->status_id)->delete();
               
            }catch(\Exception $e){
                return $e->getMessage();
            }

            if($del_id == 1){
                $request->session()->flash('mysuccess', 'Report Status removed Successfully.');
                return redirect('settings')->with(compact('mysuccess'));
            }*/

            $request->session()->flash('myerror', 'Please select quarter');
            return redirect('settings')->with(compact('myerror'));
            
        }

        #means new entry
        if(!isset($request->status_id)){

            #check if already exists with the year
            try{
                 $check_qtrs = DB::table("reports_enabled")->where("year",$year)->where("added_by",$added_by)->value('id');
            }catch(\Exception $e){
                return $e->getMessage();
            }



            if(!empty($check_qtrs)){ #means update

                

                #get the quarter that are already inserted 
                try{
                    $fetch_qu = DB::table('reports_enabled')->where('id',$check_qtrs)->value('quarters');
                }catch(\Exception $e){
                    return $e->getMessage();
                }

                #convert the selected quarter into array
                $quarters = explode(',', $quarters);

                #convert the fetched quarters into array
                $quarters_arr =  explode(',', $fetch_qu);

                #merged the selected and feteched array
                $quarters_arr = array_merge($quarters, $quarters_arr) ;

                #make 'em unique
                $quarters_arr = array_unique($quarters_arr);

                #make a string out of it
                $quarters_insert = implode(',', $quarters_arr);

                #insert
                try{
                    $inserted_into = DB::table('reports_enabled')->where('id',$check_qtrs)->update(['quarters'=>$quarters_insert]);
                }catch(\Exception $e){
                    return $e->getMessage();
                }

                

            }else{ #means entirelt new

                $insert_var = ['year'=>$request->up_year, 'quarters'=>implode(',', $request->qtrs),'added_by'=>$added_by];

                try{
                    $inserted_into = DB::table('reports_enabled')->insert($insert_var);
                }catch(\Exception $e){
                   return $e->getMessage();
                }
            }
            $request->session()->flash('mysuccess', 'New Status added Successfully');
            return redirect('settings')->with(compact('mysuccess'));
        }

    }#update_status ends here


    /**

    OPEN POP-UP FOR UPDATE

    **/
 
    public function save_email_content(Request $request){

        $added_by = Auth::user()->id;

        $email_types = $request->email_type;
        $email_title = $request->email_title;
        $email_content = nl2br(htmlentities($request->email_content, ENT_QUOTES, 'UTF-8'));

        $insert_content = 
        [
        'email_type'=>$email_types,
        'email_title'=>trim($email_title),
        'email_content'=>trim($email_content),
        'added_by'=>$added_by,
        ];
        
        try{
            $insert_id =  DB::table('email_content')->insert($insert_content);
        }catch(\Exception $e){
            return $e->getMessage();
        }

        if($insert_id == 1){
            $request->session()->flash('mysuccess', 'Content added Successfully');
            return redirect('settings#manage_emails')->with(compact('mysuccess'));
        }

    }#save_email_content ends here

    /**
    
    DELETE EMAIL CONTENT

    **/

    public function delete_content(Request $request)
    {
       
        #check if id is not empty
        if(empty($request->del_id)){

            $request->session()->flash('myerror', 'The status id does not exists.');
            return redirect('settings')->with(compact('mysuccess'));
        }

        #check if id exists in the db
        try{
            $check_id = DB::table('email_content')->select('email_type')->where('id',$request->del_id)->get()->toArray();
        }catch(\Exception $e){
            return $e->getMessage();
        }

        #return error message
        if(empty($check_id)){

            $request->session()->flash('myerror', 'The status id does not exists.');
            return redirect('settings')->with(compact('mysuccess'));

            return redirect('settings')->with(compact('myerror', 'The status id does not exists.'));
        }

        #process to delete is here
        try{
           $del_id = DB::table('email_content')->where('id',$request->del_id)->delete();
           
        }catch(\Exception $e){
            return $e->getMessage();
        }

        if($del_id == 1){
            $request->session()->flash('mysuccess', 'Email Content deleted Successfully.');
            return redirect('settings#manage_emails')->with(compact('mysuccess'));
        }

    }#delete_status ends here

    /**
        
    UPDATE EMAIL CONTENT
    
    **/

    public function update_content(Request $request){

        $email_content = nl2br(htmlentities($request->email_content, ENT_QUOTES, 'UTF-8'));
        $email_title = $request->email_title;
        $email_type = $request->email_type;
        $update_array = [
        'email_type'=>$email_type,
        'email_title'=>trim($email_title),
        'email_content'=>trim($email_content),
        ];

        
        try{
            $update_val = DB::table('email_content')->where('id',$request->content_id)->update($update_array);
        }catch(\Exception $e){
            return $e->getMessage();
        }
        


        if($update_val == 1){
            $request->session()->flash('mysuccess', 'Email content updated Successfully.');
            return redirect('settings#manage_emails')->with(compact('mysuccess'));
        }
        if($update_val == 0){
            $request->session()->flash('myerror', 'No changes were done.');
            return redirect('settings#manage_emails')->with(compact('myerror'));
        }
    }

    /**
    
    SEND EMAIL

    **/
    public function send_email(Request $request){

        if(!isset($request->recipient)){
            return response()->json(array(
                'msg'=> 'Please select the recipient.',
                'success'=>0,
            ));
        }
        if(empty($request->email_template)){
            return response()->json(array(
                'msg'=> 'Please provide the template id.',
                'success'=>0,
            ));
        }

        $added_by = Auth::user()->id;

        #check the id and get the content
        $content_id = $request->email_template;

        try{
          $content =   DB::table('email_content','email_title')->select('email_content','email_title')->where('id',$content_id)->first();
        }catch(\Exception $e){
            return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
            ));
        }

        //echo "<pre>";print_r($content);die;

        #get emails and usernames
        $error_count= 0;
        try{    
            $users = DB::table('users')->select('email','name')->wherein('id',$request->recipient)->get();

        }catch(\Exception $e){
            return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
            ));
        }

        #inserting the content and contributor name
        foreach($users as $data){

            $content_email['subject'] = $content->email_title;
            #check if keyword exists and replace it with contributor's name 
            if (strpos($content->email_content, '@creator_name') !== false) {
                
                $content_email['content'] = str_replace("@creator_name",$data->name,$content->email_content);
            }else{
                $content_email['content'] = $content->email_content;
            }

            /*try{
              $mail = Mail::to($data->email)->send(new SendEmail($content_email));

            }catch(\Exception $e){
                return response()->json(array(
                'msg'=> $e->getMessage().' '.$e->getLine(),
                'success'=>0,
                ));
            }*/

            if (Mail::failures()) {
                // return response showing failed emails
                if($error_count >= 1){
                    return response()->json(array(
                    'msg'=> 'some error occured while sending mails.',
                    'success'=>0,
                    ));
                    break;
                }
                $error_count++;
            }

        }

        #saving data in the table : email history
        $email_history['contributor_id'] = implode(",",$request->recipient);
        $email_history['email_content'] = $content_id;

        try{
            $insert_history = DB::table('email_history')->insert(
                ['contributor_id'=>$email_history['contributor_id'],
                'email_content'=>$email_history['email_content'],
                'added_by'=>$added_by
                ]);
        }catch(\Exception $e){
            return response()->json(array(
            'msg'=> $e->getMessage().' '.$e->getLine(),
            'success'=>0,
            ));
        }


        return response()->json(array(
        'msg'=> 'Mail sent Successfully.',
        'success'=>1,
        ));

    }#send_email ends here


    /**
    
    Save Disabled or Enabled books

    **/
    public function disabled_books(Request $request){
        if(!isset($request->book_id) || empty($request->book_id)){
            return response()->json(array(
            'msg'=> 'Please provide book id.',
            'success'=>0,
            'updated_at'=>"-",
            ));
        }
        ## if checked means : enable the book, uncheck means : disable the book
        ##in db : 0=>enable and 1=>disabled book

        #update the disabled id into the db
        #Added by
        $added_by = Auth::user()->id;
        #book id
        $book_id = $request->book_id;
        #status of the book : 1 => remove nd enable book, 0 => disabled book and insert
        $check_status = $request->check_status;
        #0 : means update to disable the book into db
        if($check_status==0){ 
            #check if already exists in db
            try{
                $check_id = DB::table('book_details')->select('id')->where('id',$book_id)->where('disabled_book','=',1)->first();
            }catch(\Exception $e){
                return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
                'updated_at'=>"-",
                ));
            }
            if(!empty($check_id)){
                return response()->json(array(
                'msg'=> 'Book already disabled.',
                'success'=>0,
                'updated_at'=>"-",
                ));
            }else{
                #insert into the table
                try{
                    $update_id = DB::table('book_details')->where('id',$book_id)->update(['disabled_book'=>1, 'disabled_date'=>date("Y-m-d")]);
                }catch(\Exception $e){
                    return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                    ));
                }
                if($update_id != 0){ #means id inserted
                     return response()->json(array(
                    'msg'=> 'Book disabled.',
                    'success'=>1,
                    'update_at'=> date("d M, Y"),
                    ));
                }else{
                     return response()->json(array(
                    'msg'=> 'Some issue occured.',
                    'success'=>0,
                    'update_at'=> '-'
                    ));
                }
            }
        } #if condition ends here
        #1 : means to enable the book into db : enable book
        if($check_status==1){
            #get id from table
            try{
                $enable_id = DB::table('book_details')->where('id',$book_id)->where('added_by',$added_by)->update(['disabled_book'=>0,'disabled_date'=>NULL]);
            }catch(\Exception $e){
                return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
                'update_at'=> '-'
                ));
            }
            if($enable_id!=0){
                 return response()->json(array(
                'msg'=> 'Book Enabled.',
                'success'=>1,
                'update_at'=> '-'
                ));
            }else{
                 return response()->json(array(
                'msg'=> 'Some issue occured.',
                'success'=>0,
                'update_at'=> '-'
                ));
            }
        } #if condition ends here
    }#disabled_books ends here
}#clas ends here