<?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
     */

    private $access_key;
    public function __construct(){
        $this->middleware('auth');
        $this->access_key = env('EMAIL_LIVE_VERIFICATION');
    }

    /**

    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','email_content.from_setting')
                            ->leftJoin('email_types', function ($join) {
                                $join->on('email_content.email_type', '=', 'email_types.id');
                            })
                            ->where('email_content.added_by',$added_by)
                            ->where('email_content.from_setting',"!=",0)
                            ->paginate(25, ['*'], 'content');
        }catch(\Exception $e){
            return $e->getMessage();
        }


        ##data for sending email tab

        try{
            $email_send_data = DB::table('email_types')->select('email_types.id as type_id','email_types.email_type as type_name')->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','disabled_books.book_id as disabled_Book','disabled_books.updated_at as updated_disabled')
            ->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');
            })
            ->leftJoin('disabled_books', function ($join) {
            $join->on('book_details.id', '=', 'disabled_books.book_id');
            })
            ->orderby('disabled_Book','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'));
                }
            }
        }

        #for container icons : get book container
        try{
            $book_details_containers = DB::table('book_vol_containers')
            ->select('book_main_id','contained_book_id','contained_book.book_title as contained_title','container_book.book_title as container_title','contained_book.merged_book','container_book.merged_book')
            ->where('book_vol_containers.added_by',$added_by)
            ->leftJoin('book_details as contained_book', function ($join) {
            $join->on('book_vol_containers.contained_book_id', '=', 'contained_book.id');
            })
            ->leftJoin('book_details as container_book', function ($join) {
            $join->on('book_vol_containers.book_main_id', '=', 'container_book.id');
            })
            ->where(function ($query) {
            $query->where('contained_book.merged_book','!=',1)
            ->orWhereNull('contained_book.merged_book');
            })
            ->where(function ($query) {
            $query->where('container_book.merged_book','!=',1)
            ->orWhereNull('container_book.merged_book');
            })
            ->get();
        }catch(\Exception $e){
            return $e->getMessage().' Line no' .$e->getLine();
        }

        $book_container_ids = array();
        $book_containers_titles = array();
        $book_contained_ids = array();
        $book_main_container_title = array();
        foreach($book_details_containers as $item){
            $item = get_object_vars($item);
            #main id
            $book_container_ids[]=$item['book_main_id']; 

            #contained sub ids
            $book_contained_ids[]=$item['contained_book_id']; 

            #container main book
            $book_main_container_title[$item['contained_book_id']][]=$item['container_title'];

            #containeritems titles
            $book_containers_titles[$item['book_main_id']][]=$item['contained_title'];
        }
        $book_container_ids = array_unique($book_container_ids);

        return view('settings',compact('reports_status','email_types','email_content','email_send_data','contributors','email_history','bookdata','book_container_ids','book_containers_titles','book_contained_ids','book_main_container_title'));
    } #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'){


            #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" class="email_type" required>';
            $keyword_html = "";
            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>';
                }
                
                if($email_content->type_id == 1){
                    $keyword_html ='<input type="button" value="creator name" id="edit_text_btn" id="edit_text" data-keyword="@creator_name" class="new_text_btn">
                        <input type="button" value="email" class="new_text_btn" id="edit_emailid" data-keyword="@creator_email" style="display: none">
                        <input type="button" value="password" class="new_text_btn" id="edit_pswd" data-keyword="@creator_password" style="display: none">
                        <input type="button" value="link" class="new_text_btn" id="edit_link" data-keyword="@login_link" style="display: none">'; 
                }elseif($email_content->type_id == 2){
                    $keyword_html ='<input type="button" value="creator name" class="new_text_btn" id="edit_text" data-keyword="@creator_name">
                        <input type="button" value="email" class="new_text_btn" id="edit_emailid" data-keyword="@creator_email">
                        <input type="button" value="password" class="new_text_btn" id="edit_pswd" data-keyword="@creator_password">
                        <input type="button" value="link" class="new_text_btn" id="edit_link" data-keyword="@login_link">';
                }elseif($email_content->type_id == 3){
                    $keyword_html ='<input type="button" value="creator name" class="new_text_btn" id="edit_text" data-keyword="@creator_name">
                        <input type="button" value="email" class="new_text_btn" id="edit_emailid" data-keyword="@creator_email" style="display: none">
                        <input type="button" value="password" class="new_text_btn" id="edit_pswd" data-keyword="@creator_password" style="display: none">
                        <input type="button" value="link" class="new_text_btn" id="edit_link" data-keyword="@login_link">';
                }
            }

            $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 : '.$keyword_html.'<textarea contenteditable name="email_content" class="email_content_txt" id="new_text_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'));
        }
    }

    /**
    GET CONTENT LIST
    **/
    public function get_content_list(Request $request){

        $email_type = $request['email_type'];
        if(empty($email_type)){
            return response()->json(array(
                'msg'=> 'Please send the email type',
                'success'=>0,
            ));
        }
        $added_by = Auth::user()->id;
        try{
            $email_send_data = DB::table('email_content')
            ->leftJoin('email_types', function ($join) {
                $join->on('email_content.email_type', '=', 'email_types.id');
            })
            ->select('email_content.id','email_content.email_title')
            ->where('added_by',$added_by)
            ->where('email_types.id',$email_type)
            ->where('email_content.from_setting','!=',0)
            ->get();
        }catch(\Exception $e){
            return response()->json(array(
                'msg'=>$e->getMessage(),
                'success'=>0,
            ));
        }

        if($email_send_data->isEmpty()){
            return response()->json(array(
                'msg'=>"Please add email template.",
                'success'=>2,
            ));
        }

        #template content
        $template_type = '';
        foreach($email_send_data as $e){
            $template_type .= '<option value='.$e->id.' >'.$e->email_title.'</option>';
        }

        #contributors list
        if($email_type == 1){
            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 response()->json(array(
                'msg'=>$e->getMessage(),
                'success'=>0,
                ));
            }
        }elseif($email_type == 2){
            try{
                $contributors = DB::table('users')
                ->select('users.id','users.name','users.email')
                ->where('users.added_by',$added_by)
                ->where('users.merged_contributor','!=',1)
                ->where('users.email','!=',null)
                ->where('users.email','!=','')
                ->where('users.email_sent','!=',1)
                ->orderby('users.name','asc')
                ->distinct()
                ->get();
            }catch(\Exception $e){
               return response()->json(array(
                'msg'=>$e->getMessage(),
                'success'=>0,
                ));
            }
        }else{
            try{
                $contributors = DB::table('users')
                ->select('users.id','users.name','users.email')
                ->where('users.added_by',$added_by)
                ->where('users.merged_contributor','!=',1)
                ->where('users.email','!=',null)
                ->where('users.email','!=','')
                ->orderby('users.name','asc')
                ->distinct()
                ->get();
            }catch(\Exception $e){
               return response()->json(array(
                'msg'=>$e->getMessage(),
                'success'=>0,
                ));
            }
        }

        #contributor content
        $contributors_list = '';
        foreach($contributors as $e){
            $contributors_list .= '<option value='.$e->id.' >'.$e->name.'</option>';
        }

        if(!empty($contributors_list) && !empty($template_type)){
            return response()->json(array(
            'template_list'=>$template_type,
            'contri_list'=>$contributors_list,
            'success'=>1,
            ));
        }elseif(empty($contributors_list) && !empty($template_type)){
            if($email_type == 1){
                return response()->json(array(
                'msg'=>'Please assign contributors to books.',
                'success'=>0,
                ));
            }elseif ($email_type == 2) {
                return response()->json(array(
                'msg'=>'All Contributors are sent welcome emails.',
                'success'=>0,
                ));
            }
            
        }
    }


    /**
    SEND EMAIL

    **/
    public function send_email(Request $request){
        
        if(!isset($request->recipient)){
            return response()->json(array(
                'msg'=> 'Please select the recipient.',
                'success'=>2,
            ));
        }
        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','id')->wherein('id',$request->recipient)->get();
        }catch(\Exception $e){
            return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
            ));
        }

        #getting the from email of the publisher
        try{
            $from_email_arr = DB::table('emal_configuration')->select('email_id','email_name')->where('publisher_id',$added_by)->get()->toArray();
        }catch(\Exception $e){
            return response()->json(array( 'error'=> $e->getMessageBag()->toArray(),'success'=>0));
        }
        $from_email_arr = json_decode(json_encode($from_email_arr), true);
        $from_email = $from_email_arr[0]['email_id'];
        $from_name = $from_email_arr[0]['email_name'];

        #collecting the ids
        $emails_collection = json_decode(json_encode($users));
        $emails_arr = array();
        $not_email_sent = array();
        
        foreach ($emails_collection as $key => $value) {
            $emails_arr[$value->id] = $value->email; 
        }
        ##VALIDATINNG EMAIL

        #collect invalid email ids
        $invalid_ids = array();

        #set API Access Key
        foreach($emails_arr as $id => $emails){

            #Initialize CURL:
            $ch = curl_init('http://apilayer.net/api/check?access_key='.$this->access_key.'&email='.$emails.'');  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            #Store the data:
            $json = curl_exec($ch);
            curl_close($ch);

            #Decode JSON response:
            $validationResult = json_decode($json, true);
            if(!isset($validationResult['format_valid']) && !isset($validationResult['smtp_check'])){
                return response()->json(array(
                'msg'=> $validationResult['error']['info'],
                'success'=>0,
                ));
                break;
            }

            #collecting the invalid email ids
            if ($validationResult['format_valid'] && $validationResult['smtp_check']) {
                continue;
            }else{
                $invalid_ids['emails'][$id] =  $emails; #collection of invalid email
                $invalid_ids['id'][] =  $id;
                //$invalid_ids[$id] =  $emails; #collection of invalid email
            }
           /* if (strpos($emails, 'gmail.com') === false) {#temp code
                continue;
            }else{
                $invalid_ids['emails'][$id] =  $emails; #collection of invalid email
                $invalid_ids['id'][] =  $id;
            }*/
        }

        $mail_send_to = array();
        $mail_not_sent = array();

        #inserting the content and contributor name
        foreach($users as $key=> $data){
            if(isset($invalid_ids) && !empty($invalid_ids)){
                if(array_key_exists($data->id,$invalid_ids['emails'])){continue;}
            }
            
            $e_subject = $content->email_title;

            if($request->email_type_send == 1) #if report email
            {
                #check if keyword exists and replace it with contributor's name 
                if (strpos($content->email_content, '@creator_name') !== false) {
                    $e_content = str_replace("@creator_name",$data->name,$content->email_content);
                }else{
                    $e_content = $content->email_content;
                }

            }elseif($request->email_type_send == 2){ #if welcome email
                #create password 
                $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                $password_new = substr( str_shuffle( $chars ), 0, 11 );
                $newpasswordhashed = Hash::make($password_new);
                #update password
                try{
                    $update_pswd = DB::table('users')->where('id',$data->id)->update(['password'=>$newpasswordhashed]);
                }catch(\Exception $e){
                    return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                    ));
                }

                #update into the content
                if($update_pswd == 1){
                    if (strpos($content->email_content, '@creator_name') !== false) {
                        $e_content = str_replace("@creator_name",$data->name,$content->email_content);
                    }else{
                        $e_content = $content->email_content;
                    }

                    if (strpos($e_content, '@creator_email') !== false) {
                        $e_content = str_replace("@creator_email",$data->email,$e_content);
                    }else{
                        $e_content = $content->email_content;
                    }

                    if (strpos($e_content, '@creator_password') !== false) {
                        $e_content = str_replace("@creator_password",$password_new,$e_content);
                    }else{
                        $e_content = $content->email_content;
                    }

                    if (strpos($e_content, '@login_link') !== false) {
                        $e_content = str_replace("@login_link",URL::to('/')."/login?clogin=1",$e_content);
                    }else{
                        $e_content = $content->email_content;
                    }
                }
            }elseif($request->email_type_send == 3){
                if (strpos($content->email_content, '@creator_name') !== false) {
                        $e_content = str_replace("@creator_name",$data->name,$content->email_content);
                }else{
                    $e_content = $content->email_content;
                }

                if (strpos($e_content, '@creator_email') !== false) {
                    $e_content = str_replace("@creator_email",$data->email,$e_content);
                }else{
                    $e_content = $content->email_content;
                }

                if (strpos($e_content, '@creator_password') !== false) {
                    $e_content = str_replace("@creator_password",$password_new,$e_content);
                }else{
                    $e_content = $content->email_content;
                }

                if (strpos($e_content, '@login_link') !== false) {
                    $e_content = str_replace("@login_link",URL::to('/')."/login?clogin=1",$e_content);
                }else{
                    $e_content = $content->email_content;
                }
            }

            //by nishant 12 dec 2018
            $e_content = $e_content."<br><br><b>Thanks & Regards</b><br>Joe Nozemack<br>Oni Press, Inc.<br>1319 SE MLK Jr. Blvd., Suite 240<br>Portland, OR 97214<br>503-233-1377 x3002<br><img src=".url('/images/email/logo.png').">";
            $e_content='<span style="font-size:14px;">'.$e_content.'</span>';

            $recipients = $data->email;

            try{
                $mail = Mail::raw([], function($message) use($recipients,$e_content,$from_email, $from_name,$e_subject) {
                $message->replyTo($from_email, $from_name);
                $message->to($recipients);
                $message->subject($e_subject);
                $message->setBody($e_content);
                $message->setContentType('text/html');
                });
                $mail_send_to[] = $data->id;
                DB::table('users')->where('id',$data->id)->update(['email_sent'=>1]);
            }catch(\Exception $e){
                $mail_error = $e->getMessage();
                $mail_not_sent[] = $data->id;
                DB::table('users')->where('id',$data->id)->update(['email_sent'=>0]);
            }
            //$mail_send_to[] = $data->id; #remove when emails are enabled
            if (Mail::failures()) {
                try{
                $update_contri = DB::table('users')->where('id',$data->id)->update(['email_sent'=>0]);
                }catch(\Exception $e){
                    return response()->json(array('msg'=> $e->getMessage(),'success'=>0));
                }
                #return response showing failed emails
                if($error_count >= 1){
                    $mail_not_sent[] = $data->id;
                    return response()->json(array(
                    'msg'=> 'some error occured while sending mails.',
                    'success'=>0,
                    ));
                    break;
                }
                $error_count++;
            }
        }
        
        $mail_receivers = array_diff($mail_send_to, $mail_not_sent);

        $invalid_emails = array();
        if(!empty($mail_not_sent)){
            $invalid_emails = array_merge($invalid_ids['id'],$mail_not_sent);
        }else{
            if(isset($invalid_ids) && !empty($invalid_ids)){
                $invalid_emails = $invalid_ids['id'];
            }
        }
        //$invalid_emails = $invalid_ids['id'];#remove this on valid email
        $invalid_emails = array_unique($invalid_emails);

        ##send invalid email id to publisher
        if(!empty($invalid_emails)){
            $invalid_html = 'Dear '.$from_name.' ,<br>Email could not be delivered to the following contributors. <ol>';
            foreach ($invalid_emails as $value) {
                $invalid_html .= '<li>'.$emails_arr[$value].'</li>';
            }
            $invalid_html .= '</ol> Make sure you have entered valid email ids. ';
            try{
                $mail = Mail::raw([], function($message) use($invalid_html,$from_email, $from_name) {
                    $message->to($from_email);
                    $message->subject('Address not found');
                    $message->setBody($invalid_html);
                    $message->setContentType('text/html');
                });
            }catch(\Exception $e){
                return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
                ));
            }
        }
        
        #saving data in the table : email history
        $email_history['contributor_id'] = implode(",",$mail_receivers);
        $email_history['email_content'] = $content_id;

        if(!empty($mail_receivers)){
            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,
            ));
        }else{
            if(isset($mail_error)){
                return response()->json(array(
                'msg'=> $mail_error,
                'success'=>0,
                ));    
            }else{
                return response()->json(array(
                'msg'=> 'Mail could not be sent.',
                '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

        #insert 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 insert into db
        if($check_status==0){ 
            #check if already exists in db
            try{
                $check_id = DB::table('disabled_books')->select('id')->where('book_id',$book_id)->where('added_by',$added_by)->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{
                    $insert_id = DB::table('disabled_books')->insertGetId(['book_id'=>$book_id,'added_by'=>$added_by]);
                }catch(\Exception $e){
                    return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                    ));
                }
                try{
                    $updated_at = DB::table('disabled_books')->where('id',$insert_id)->value('updated_at');
                }catch(\Exception $e){
                    return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                    'updated_at'=>$updated_at,
                    ));
                }
                if($insert_id != 0){ #means id inserted
                     return response()->json(array(
                    'msg'=> 'Book disabled.',
                    'success'=>1,
                    'update_at'=> date("d M, Y", strtotime($updated_at)),
                    ));
                }else{
                     return response()->json(array(
                    'msg'=> 'Some issue occured.',
                    'success'=>0,
                    'update_at'=> '-'
                    ));
                }
            }
        } #if condition ends here

        #1 : means delete into db : enable book
        if($check_status==1){ 
            #get id from table
            try{
                $record_id = DB::table('disabled_books')->where('book_id',$book_id)->where('added_by',$added_by)->value('id');
            }catch(\Exception $e){
                return response()->json(array(
                'msg'=> $e->getMessage(),
                'success'=>0,
                'update_at'=> '-'
                ));
            }
            if(empty($record_id)){ #book not found,
                 return response()->json(array(
                'msg'=> 'Book already enabled.',
                'success'=>0,
                'update_at'=> '-'
                ));
            }else{
                try{
                $delete_id = DB::table('disabled_books')->where('id',$record_id)->delete();
                }catch(\Exception $e){
                    return response()->json(array(
                    'msg'=> $e->getMessage(),
                    'success'=>0,
                    'update_at'=> '-'
                    ));
                }
            }
            if($delete_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
