<?php

namespace App\Http\Controllers;

use App\User;
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\Mail;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Mail\WelcomeUser;
use App\Mail\EditContributor;
use Excel;

class HomeController extends Controller{

    /**
    * Create a new controller instance.
    *
    * @return void
    */

    private $access_key;

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

    /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Http\Response
    */

    public function index(Request $request){   

        #if user a contributor then redirect to dashboard
        if(\Session::get('login_type') == 2){
            return redirect()->route('dashboard');
        }

        #forget the platform session
        \Session::forget('platformsession');
        
        #value from query string of the url
        if(!isset($_GET['_order'])){
            $orderby = "asc";
        }else{
            $orderby = $_GET['_order'];
        }

        #number of items per page
        if(!isset($_GET['_perlist'])){
            $itemby = "25";
        }else{
            $itemby = $_GET['_perlist'];
        }

        #publisher id
        $id = Auth::user()->id;

        #query : code updated on 29 may 2018 : check backup for issues
        try{
            $contributorss = DB::table('users')
            ->select('users.id', 'users.state', 'users.country', 'users.city','users.email', 'users.name', 'users.phone_number','users.login_type','users.added_by','users.stage_name','users.merged_contributor', 'country.country','state.state','city.city','assign_contributors.book_id','book_details.id as book_ids','book_details.merged_book as merged_book','users.email_sent')
            ->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');
            })
            //->from($userdet)
            ->leftJoin('country', function ($join) {
                $join->on('users.country', '=', 'country.id');
            })
            ->leftJoin('state', function ($join) {
                $join->on('users.state', '=', 'state.id');
            })
            ->leftJoin('city', function ($join) {
                $join->on('users.city', '=', 'city.id');
            })
            ->where('users.login_type', 2)
            ->where('users.added_by', $id)
            ->where(function ($query) {
                $query->where('users.merged_contributor','!=',1)
                    ->orWhereNull('users.merged_contributor');
            })
            #list of no_book assigned starts16:2
            ->where(function($q) use ($request) {
                if (isset($_GET['_filter'])){
                    $q->whereNull('book_details.id');
                }
            })
            ->orderBy('name', $orderby)
            ->where(function($q) use ($request) {
                if (isset($_GET['searched_val'])) {
                    $q->orWhere('email', 'like', '%'.$_GET['searched_val'].'%');

                    $q->orWhere('name', 'like', '%'.$_GET['searched_val'].'%');

                    $q->orWhere('phone_number', 'like', '%'.$_GET['searched_val'].'%'); 
                    $q->orWhere('middle_name', 'like', '%'.$_GET['searched_val'].'%');
                    //$q->orWhere('book_title', 'like', '%'.$_GET['searched_val'].'%');
                }    
            })
            ->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }

        #collect into array - one contributor can have multiple books
        $contributorslist = array();
        foreach ($contributorss as $item) {
            $item = get_object_vars($item);
            $contributorslist[$item['id']]['user_details']['id']= $item['id'];
            $contributorslist[$item['id']]['user_details']['name']= $item['name'];
            $contributorslist[$item['id']]['user_details']['email']= $item['email'];
            $contributorslist[$item['id']]['user_details']['phone_number']= $item['phone_number'];
            $contributorslist[$item['id']]['user_details']['stage_name']= $item['stage_name'];
            $contributorslist[$item['id']]['user_details']['email_sent']= $item['email_sent'];
            if($item['merged_book']==1){
                continue;
            }else{
                $contributorslist[$item['id']]['user_details']['book_count'][]=$item['book_id'];
            }
        }

        ##paginate according to the contributor instead of books
        #Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
 
        #Create a new Laravel collection from the array data
        $itemCollection = collect($contributorslist);
        
        #Define how many items we want to be visible in each page
        $perPage = $itemby;
 
        #Slice the collection to get the items to display in current page
        $currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
         
        ##redirection if the current url has no data - starts
        #current url with parameters
        $current_url = $request->fullUrl();

        #if the user click on last page and changes the list per page to large no and no record is found then redirect it to first page
        if((empty($currentPageItems)) && (strpos($current_url, 'page') !== false)){
            #current url without page
            $current_url_no_page = str_replace('page='.$currentPage, '', $current_url); 
            #redirecting to that url
            return redirect()->away($current_url_no_page); 
        }

        ##redirection if the current url has no data -  ends

        #Create our paginator and pass it to the view
        $contributorslist = new LengthAwarePaginator($currentPageItems , count($itemCollection), $perPage);

        #set url path for generted links
        $contributorslist->setPath($request->url());

        #appending search
        if(isset($_GET['searched_val'])) {
            $contributorslist->appends(['searched_val' => $_GET['searched_val']]);
            $contributorslist1 = $contributorslist->toArray();
            if(Empty($contributorslist1['data'])){
                if($_GET['searched_val']){
                    $searched_item =  $_GET['searched_val'];
                }else{
                    $searched_item =  '';
                }
                $myerrorr = "We can't find any item matching your search";
                return redirect('home')->with(compact('myerrorr', 'searched_item'));
            }
        }
        return view('home' ,compact('contributorss','contributorslist'));
    }/* end of controller action*/


    /**
    For search and contributor csv upload using one action for multiple form submit
    **/


    public function homemultipleviews(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #publisher id
        $id = Auth::user()->id; 

        /**
        Add contributor csv
        **/

        if ($request->has('csv')){#if csv form is being submitted
            #validating the file uploaded
            $validator = Validator::make($request->all(), ['csv_file'=>'required']);
            if($validator->fails()){
                return redirect('/home')
                    ->withInput()
                    ->withErrors($validator);
            }
            #checking if file uploaded is csv or not
            $myextension = $request->csv_file->getClientOriginalExtension();
            $csvarray = array("csv");
            if(!in_array($myextension, $csvarray)){
                return redirect('home')->with("error","Please upload correct format");
            }
            #create unique csv id in csv_records table
            $csv_token = "contributor_details_".date('Y-m-d H:i:s'); #unique token
            #inserting in db
            try{
                $csv_data = DB::table('csv_records')->insert([
                'csv_token'=>$csv_token,
                ]);
            }catch(\Exception $e){
                return $e->getMessage()."  Line no ".$e->getLine();
            }
            #getting id from csv_records
            if($csv_data == 1){
                try{
                    $csv_id = DB::table('csv_records')->where('csv_token',$csv_token)->value('id');
                }catch(\Exception $e){
                    return $e->getMessage()."Line no ".$e->getLine() ;
                }
            }    
            if($csv_id){#if id is available
                if (($handle = fopen ( $request->csv_file, 'r' )) !== FALSE) {
                    fgetcsv($handle, 0, ","); #abandon first record
                    $emailcount = 0; #get count of names already existing in db
                    $values_to_update = array(); #store the arrays with values
                    try{
                        while (($data = fgetcsv ( $handle, 0, ',' )) !== FALSE ) {
                            #verify the format of the csv
                            if(isset($data[0]) && isset($data[1]) && isset($data[2]) && isset($data[3]) && isset($data[4]) && isset($data[5]) && isset($data[6]) && isset($data[7]) && isset($data[8]) && isset($data[9]) && isset($data[10]) && isset($data[11]) && isset($data[12]) && isset($data[13]) && isset($data[14]) && isset($data[15]) && isset($data[16]) && isset($data[17]) && isset($data[18])){
                                if(!strtotime(trim($data[0])) && !is_numeric(trim($data[0])) && !empty(trim($data[0]))){$column_00 = true;}
                                if(!strtotime(trim($data[1])) && !is_numeric(trim($data[1])) && !empty(trim($data[1]))){$column_01 = true;}
                                if((!strtotime(trim($data[2])) && !is_numeric(trim($data[2]))) || empty(trim($data[2]))){$column_02 = true;}
                                if (filter_var(trim($data[3]), FILTER_VALIDATE_EMAIL)) {$column_03 = true;}
                                #skip 4
                                if (strtotime(trim($data[5]))|| empty(trim($data[5]))) {$column_05 = true;}
                                #skip6,7,8,9,10
                                if(preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/", trim($data[11])) || empty(trim($data[11]))){
                                    $column_11 = true;
                                }
                            }
                            if(!isset($column_00) || !isset($column_01) || !isset($column_02) || !isset($column_03) || !isset($column_05) || !isset($column_11)){
                                return redirect()->back()->with("error", "Invalid Format uploaded. Please check the  sample csv for the same.");
                            }
                            #storing names in variables
                            $last_name = $data[0];//last name of the contributor
                            $first_name = $data[1];//first name of the contributor
                            $middle_name = $data[2];//middle name of the contributor
                            $email =  $data[3];//email of the contributor
                            $pswd = $data[4];//pswd of the contributor
                            $dob = $data[5];//dob of the contributor
                            $street_address = $data[6];
                            $city = $data[7];
                            $state = $data[8];
                            $zip = $data[9];
                            $country = $data[10];
                            $phone_number = $data[11];
                            $doc = $data[12]; //date of contract
                            $fb = $data[13]; 
                            $twitter = $data[14]; 
                            $insta = $data[15]; 
                            $bio = $data[16]; 
                            $image = $data[17]; 
                            $w9form = $data[18]; 
                            #converting the dates
                            if(empty($dob)){
                                $birth_date="";
                            }else{
                                $birth_date = date("Y-m-d", strtotime($dob));
                            }
                            if(empty($doc)){
                                $contract_date="";
                            }else{
                                $contract_date = date("Y-m-d", strtotime($doc));
                            }
                            #checking if the name already exists table
                            try{
                                $checkname = DB::table('users')
                                ->where('name', '=',trim($first_name)." ".trim($last_name))
                                ->where('added_by',$id)
                                ->first();
                            }catch (\Exception $e) {
                                return $e->getMessage();
                            }

                            ###checking country
                            #checking if country id exists 
                            $countryname = $country; #name of the country from csv
                            if($countryname != ""){
                                try{
                                    $countryvalue = DB::table('country')->where('country', $countryname)->exists();
                                }catch (\Exception $e) {
                                    return $e->getMessage()."Line no_c ".$e->getLine();
                                }
                                if($countryvalue == 0) {
                                    #if country does not exist, add new value and fetch its id
                                    $countryinsert = array(array('country'=>$countryname),);
                                    try{
                                        DB::table('country')->insert($countryinsert);
                                    }catch (\Exception $e) {
                                        return $e->getMessage()."Line no_d ".$e->getLine();
                                    }
                                    #now get the countru id that is being added recently
                                    try{
                                        $countryid = DB::table('country')
                                            ->select('id')   
                                            ->where('country',$countryname)  
                                            ->get(); 
                                    }catch (\Exception $e) {
                                        return $e->getMessage()."Line no_e ".$e->getLine();
                                    }
                                }else{
                                #if country name exists
                                    #get its id
                                    try{
                                        $countryid = DB::table('country')
                                                ->select('id')   
                                                ->where('country',$countryname)  
                                                ->get(); 
                                    }catch (\Exception $e) {
                                        return $e->getMessage()."Line no _f".$e->getLine();
                                    }
                                }
                                #fetching particular id value from array
                                $newcountid = array();
                                foreach($countryid as $newcountid){
                                    $newcountid = get_object_vars($newcountid);
                                    $newcountid =  $newcountid['id'];
                                }
                            }else{
                                #if country is not avail make its id empty
                                $newcountid = "";
                            }

                            ###checking state
                            $statename = $state;
                            if($statename != ""){ ##if state is given
                                #check if state is available in db
                                try{
                                    $statevalue = DB::table('state')->where('state', $statename)->exists();
                                }catch (\Exception $e) {
                                    return $e->getMessage()."Line no_g ".$e->getLine();
                                }
                                #if state does not exists then add state
                                if ($statevalue == 0) { 
                                    #insert only when country_id is available
                                    if(!empty($newcountid)){
                                        $stateinsert =  array(array('state'=>$statename, 'country_id'=>$newcountid),);
                                        try{
                                            DB::table('state')->insert($stateinsert);
                                            $stateid = DB::table('state')
                                                    ->select('id')   
                                                    ->where('state',$statename)  
                                                    ->get();
                                        }catch (\Exception $e) {
                                            return $e->getMessage()."Line no_h ".$e->getLine();
                                        }
                                    }else{ 
                                        #if country id not available then add nothing
                                        $stateid = array();
                                    }
                                }else{
                                    #if exist in db, get the id of the state
                                    try{
                                        $stateid = DB::table('state')
                                            ->select('id')   
                                            ->where('state',$statename)  
                                            ->get();  
                                    }catch (\Exception $e) {
                                       return $e->getMessage()."Line no_i ".$e->getLine();
                                    }
                                }
                                ##getting id from array
                                $newstateid = array();
                                if(!empty($stateid)){
                                    foreach($stateid as $newstateid){
                                        $newstateid = get_object_vars($newstateid);
                                        $newstateid =  $newstateid['id'];
                                    }  
                                }
                            }else{
                                #if state not in csv, then newstateid is empty
                                $newstateid = "";
                            }
                            
                            ### checking city
                            #checking city exits
                            $cityname = $city;
                            if($cityname != ""){
                                #check if id is available in db or not
                                try{
                                    $cityvalue = DB::table('city')->where('city', $cityname)->exists();
                                }catch (\Exception $e) {
                                    return $e->getMessage()."Line no_h ".$e->getLine();
                                }
                                #if state does not exists then add state
                                if ($cityvalue == 0) { 
                                    #insert only when state_id is available
                                    if(!empty($newstateid)){
                                        $cityinsert =   array(array('city'=>$cityname, 'state_id'=>$newstateid),);
                                        try{
                                            DB::table('city')->insert($cityinsert);
                                            $cityid = DB::table('city')
                                            ->select('id')   
                                            ->where('city',$cityname)  
                                            ->get(); 
                                        }catch (\Exception $e) {
                                            return $e->getMessage()."Line no_i ".$e->getLine();
                                        }
                                    }else{ 
                                        #if state id not available then add nothing
                                        $cityid = array();
                                    }
                                }else{ #if exist, get the id of the city
                                    try{
                                        $cityid = DB::table('city')
                                            ->select('id')   
                                            ->where('city',$cityname)  
                                            ->get(); 
                                    }catch (\Exception $e) {
                                        return $e->getMessage()."Line no_j ".$e->getLine();
                                    }
                                }
                                $newcityid = array();
                                if(!empty($cityid)){
                                    foreach($cityid as $newcityid){
                                        $newcityid = get_object_vars($newcityid);
                                        $newcityid =  $newcityid['id'];
                                    }
                                }
                            }else{
                                $newcityid = "";
                            }

                            ###csv insertion goes here
                            if (is_null($checkname)){ //if name is new*/
                                $csv_data = new User();
                                $csv_data->name = trim($first_name)." ".trim($last_name);
                                $csv_data->last_name = $last_name;
                                $csv_data->first_name = $first_name;
                                $csv_data->middle_name = $middle_name;
                                $csv_data->email = $email;
                                $csv_data->password = $pswd;
                                $csv_data->birth_date = $birth_date;
                                $csv_data->postcode = $zip;
                                $csv_data->contract_date = $contract_date;
                                $csv_data->phone_number = $phone_number;
                                $csv_data->facebook_link = $fb;
                                $csv_data->twitter_link = $twitter;
                                $csv_data->instagram_link = $insta;
                                $csv_data->bio = $bio;
                                $csv_data->profile_image  = $image;
                                $csv_data->w9_form  = $w9form;
                                $csv_data->address  = $street_address;
                                #if country , state & city avaialble 
                                if(!empty($newcountid) && !empty($newstateid) && !empty($newcityid)){ 
                                    $csv_data->country =  $newcountid;   
                                    $csv_data->state = $newstateid; 
                                    $csv_data->city = $newcityid;
                                }elseif(empty($newcountid) && !empty($newstateid) && !empty($newcityid)){
                                #if state and city available
                                    $csv_data->state = $newstateid; 
                                    $csv_data->city = $newcityid;
                                }elseif(!empty($newcountid) && empty($newstateid) && !empty($newcityid)){
                                #if country and city available
                                    $csv_data->country = $newcountid; 
                                    $csv_data->city = $newcityid;
                                }elseif(!empty($newcountid) && !empty($newstateid) && empty($newcityid)){
                                #if country and state available
                                    $csv_data->country = $newcountid; 
                                    $csv_data->state = $newstateid;
                                }elseif(empty($newcountid) && empty($newstateid) && !empty($newcityid)){
                                #if only city availablw
                                    $csv_data->added_by = $id; 
                                    $csv_data->city = $newcityid;
                                }elseif(!empty($newcountid) && empty($newstateid) && empty($newcityid)){
                                #if only country available
                                    $csv_data->country = $newcountid;
                                }elseif(empty($newcountid) && !empty($newstateid) && empty($newcityid)){
                                #if only state available    
                                    $csv_data->state = $newstateid; 
                                }
                                $csv_data->login_type = 2;
                                $csv_data->added_by = $id;
                                $csv_data->profile_img_type = 3;
                                $csv_data->csv_id = $csv_id;
                                $csv_data->save(); 
                            }else{
                                #if the contributor is existing, then update that contributor
                                $emailcount++;
                                #get the id of contributor
                                try{
                                    $users_id = DB::table('users')
                                    ->where('name',trim($first_name)." ".trim($last_name))
                                    ->where('added_by',$id)
                                    ->value('id');
                                }catch(\Exception $e){
                                    return $e->getMessage()." Line no (csv upload )".$e->getLine(); 
                                }
                                #store the update array in the array 
                                if(!empty($first_name)){
                                    $values_to_update =   ['first_name'=> $first_name];
                                }
                                if(!empty($last_name)){
                                    $values_to_update +=   ['last_name'=> $last_name];
                                }
                                if(!empty($middle_name)){
                                    $values_to_update +=   ['middle_name'=> $middle_name];
                                }
                                if(!empty($email)){
                                    $values_to_update +=   ['email'=> $email];
                                }
                                if(!empty($pswd)){
                                    $values_to_update +=   ['password'=> $pswd];
                                }
                                if(!empty($dob)){
                                    $birth_date = date("Y-m-d", strtotime($dob));
                                    $values_to_update +=   ['birth_date'=> $birth_date];
                                }
                                if(!empty($zip)){
                                    $values_to_update +=   ['postcode'=> $zip];
                                }
                                if(!empty($doc)){
                                    $contract_date = date("Y-m-d", strtotime($doc));
                                    $values_to_update += ['contract_date'=> $contract_date];
                                }
                                if(!empty($phone_number)){
                                    $values_to_update +=   ['phone_number'=> $phone_number];
                                }
                                if(!empty($fb)){
                                    $values_to_update +=   ['facebook_link'=> $fb];
                                }
                                if(!empty($twitter)){
                                    $values_to_update +=   ['twitter_link'=> $twitter];
                                }
                                if(!empty($insta)){
                                    $values_to_update +=   ['instagram_link'=> $insta];
                                }
                                if(!empty($bio)){
                                    $values_to_update +=   ['bio'=> $bio];
                                }
                                if(!empty($image)){
                                    $values_to_update +=  ['profile_image'=> $image,'profile_img_type'=> 3];
                                }
                                if(!empty($w9form)){
                                    $values_to_update +=   ['w9_form'=> $w9form];
                                }
                                if(!empty($street_address)){
                                    $values_to_update +=   ['address'=> $street_address];
                                }
                                if(!empty($newcountid)){
                                    $values_to_update +=   ['country'=> $newcountid];
                                }
                                if(!empty($newstateid)){
                                    $values_to_update +=   ['state'=> $newstateid];
                                }
                                if(!empty($newcityid)){
                                    $values_to_update +=   ['city'=> $newcityid];
                                }
                                if(!empty($first_name) || !empty($last_name)){
                                    $values_to_update +=   ['name'=> trim($first_name)." ".trim($last_name),];
                                }
                                #creating 0 to enable contributor add their own password
                                $values_to_update +=   ['pswd_check'=> 0,];
                                try{
                                    $update_users = DB::table('users')
                                                ->where('id', $users_id)
                                                ->where('added_by',$id)
                                                ->update($values_to_update);
                                }catch (\Exception $e) {
                                  return $e->getMessage()." line number csv updation  :".$e->getLine(); 
                                }
                            }#if loop closed - skip empty rowss
                        }#while loop closed
                    }catch (\Exception $e) {
                      return redirect()->route('home')->with("error",$e->getMessage()." line number:".$e->getLine()); 
                    }
                    fclose ( $handle );
                    /* uncomment this when email count is to be shown*/
                    if($emailcount > 1){
                        return redirect()->route('home')->with("message", $emailcount." contributors details Updated Successfully");
                    }
                    if($emailcount == 1){
                        return redirect()->route('home')->with("message", $emailcount." contributor's details Updated Successfully");
                    }
                    return redirect()->route('home')->with("message","CSV Details Added Successfully");
                }else{
                    return redirect()->route('home')->with("error","Please Upload again");
                }
            }/* csv_record insertion*/
        } /* csv condition ends*/

        /**
        Delete the contributor
        **/
        
        if ($request->has('deletecontributor')) {
            try{
                $contributor = User::where('id', '=', $request->contributor_id)->first(); #if id exists in table 
            }catch(\Exception $e){
                return $e->getMessage();
            }
            if ($contributor === null) { #id does not exist in table
                return response()->json(array(
                'msg'=> 'Contributor does not exist',
                'success'=>0,
                ));
            }else{
                try{
                    $deletecontributor = DB::table('users')->where('id',$request->contributor_id )->delete();
                }catch(\Exception $e){
                    return $e->getMessage();
                }
                if($deletecontributor == 1){
                    return response()->json(array(
                    'msg'=> 'Contributor Deleted Successfully',
                    'success'=>1,
                    ));
                }else{
                    return response()->json(array(    
                    'msg'=> 'Some Error occurred',
                    'success'=>0,
                    ));
                }
            }
        } /* ends delete contributor */
    } /* ends homemultipleviews function */

    /**
    Account setting load view
    **/

    public function account_setting_view(Request $request){       
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #publisher id
        $id = Auth::user()->id;
        #loading user's info
        try{
            $users =  DB::select('select * from users where id = :id', ['id' => $id]);
        }catch (\Exception $e) {
            throw $this->createNotFoundException('The user does not exist');
        }
        return view('account_setting', ['users' => $users]);
    }

    /**
    Account Setting functionality
    **/

    public function account_setting(Request $request){   
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #get password
        $password = Auth::user()->password; //from the db
        #request
        $data = $request->all();
        #user's id
        $id = Auth::user()->id;
        #validations for the fields
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'middle_name' => 'nullable|max:255',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1024',
            'username' => 'required|unique:users,username,'.$id,
            'email'  =>  'required|email|unique:users,email,'.$id,
            'password' => 'nullable|min:6',
            'password_confirmation' => 'nullable|min:3|same:password|required_with:password',
            ]);
        #returning errors to view in ajax
        if ($validator->fails()) {
            return response()->json(array('error'=> $validator->getMessageBag()->toArray(),'success'=>0,));
        }
        #if image is being set 
        if ($request->hasFile('image')) {
            //image is being edited
            $profile_img_type = 1;
            if($request->file('image')->isValid()) {
                try {
                    $profile_img = time().'.'.$request->image->getClientOriginalExtension();
                    $request->image->move(public_path('/profilepic'), $profile_img);
                } catch (\Exception $e) {
                    throw $this->createNotFoundException('Image not saved');
                }
            }
        }

        #if no image then get image from the database
        if (! $request->hasFile('image')) {
            #image
            $profile_img = Auth::user()->profile_image;
            #image type
            $profile_img_type = Auth::user()->profile_img_type;
        }

        #from the form
        $oldpassword = $request->oldpassword; 
        $newpassword = $request->password;
        $newpasswordconfirm = $request->password_confirmation;
        #if old password, new pws and confirm pswd is not empty then make password format for the new password to store it into db
        if(($oldpassword != "") && ($newpassword != "") && ($newpasswordconfirm != "")){
            if(Hash::check($oldpassword,$password)){
                $newpasswordhashed = Hash::make($newpassword);
                try{
                    $id = DB::table('users')->where('id', $id)->update([
                    'last_name' => $data['last_name'],
                    'first_name' => $data['first_name'],
                    'middle_name' => $data['middle_name'],
                    'username' => $data['username'],
                    'email' => $data['email'],
                    'password' => $newpasswordhashed,
                    'profile_image' => $profile_img,
                    'profile_img_type' => $profile_img_type,
                    'name'=>$data['first_name']." ".$data['middle_name']." ".$data['last_name'],
                    ]);  
                }catch (\Exception $e) {
                        return redirect()->route('account_setting')->with("error",$e->getMessage()."Line no_k ".$e->getLine());
                }
                return redirect()->route('account_setting')->with("message","Account Details and Password Updated Successfully");
            }else{
                return response()->json(array('error'=> 'password incorrect','success'=>'old_password_error',));
            }
        }else{
            #else update the rest of the data
            try{
                $id = DB::table('users')->where('id', $id)->update([
                    'last_name' => $data['last_name'],
                    'first_name' => $data['first_name'],
                    'middle_name' => $data['middle_name'],
                    'username' => $data['username'],
                    'email' => $data['email'],
                    'profile_image' => $profile_img,
                    'profile_img_type' => $profile_img_type,
                    'name'=>$data['first_name']." ".$data['middle_name']." ".$data['last_name'],
                ]);
            }catch (\Exception $e) {
                return redirect()->route('account_setting')->with("error",$e->getMessage()."Line no_l ".$e->getLine());
            }
            return redirect()->route('account_setting')->with("message","Account Details Updated Successfully");
        }
    }/** account edit page function - ends **/


    /**
    to get the list of countries for adding contributors
    **/

    public function add_contributor_view(Request $request){  
         // echo "iam here".$this->access_key; die;
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #load page view
        try{
            $countries = DB::table('country')->orderby('country','asc')->get(); 
        }catch(\Exception $e){
            return $e->getMessage()."Line no_m".$e->getLine();
        }
       return view('add_contributor', ['countries' => $countries]);
    }

     /**
    Add contributor functionality
    **/
    public function add_contributor(Request $request){

        #set API Access Key
        $access_key = $this->access_key;       

        #request data
        $data = $request->all();

        #publisher's id
        $id = Auth::user()->id;

        #date of birth
        $date1 = $request->DOB;

        #contract date
        $contract_date1 = $request->contract_date;

        #if date is empty, make the var empty 
        if(empty($date1)){
            $dob="";
        }else{
            $dob = date("Y-m-d", strtotime($date1));
        }
        #if date is empty, make the var empty
        if(empty($contract_date1)){
            $contract_date="";
        }else{
            $contract_date = date("Y-m-d", strtotime($contract_date1));
        }
        #getting the from email of the publisher
        try{
            $from_email_arr = DB::table('emal_configuration')->select('email_id','email_name')->where('publisher_id',$id)->get()->toArray();
        }catch(\Exception $e){
            return response()->json(array( 'error'=> $validator->getMessageBag()->toArray(),'success'=>0));
        }

        if(!empty($from_email_arr)){
            $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'];
        }

        #validate the data
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'middle_name' => 'nullable|max:255',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1024',
            'w9form' => 'mimes:doc,docx,pdf',
            //'email'  =>  'required|email|unique:users',
            'email'  =>  'nullable|email|unique:users',
            'password' => 'nullable',
            'DOB'=>'nullable',
            'contract_date' =>'nullable',
            'country' =>'nullable|not_in:0',
            'city' =>'nullable|not_in:0',
            'state' =>'nullable|not_in:0',
            'postal_code' => 'nullable|max:255',
            'phone_number'=> 'nullable|numeric',
            'contract_date'=>'nullable',
            'address' => 'nullable|max:255',
            'facebook' =>'max:255',
            'twitter' =>'max:255',
            'instagram' =>'max:255',
            'bio' =>'nullable|min:30|max:255',
            'stage_name'=>'nullable|max:255',
        ]);

        #validation sending error back
        if ($validator->fails()) {
            return response()->json(array( 'error'=> $validator->getMessageBag()->toArray(),'success'=>0));
        }else{
            ##welcome email content
            if((empty($data['c_email']) || empty($data['e_title']) || empty($data['email_content'])) && !empty($data['email'])){#if the welcome email content is empty
                if($data['configuration'] == 0){ #if configuration email is pending
                    return response()->json(array( 'error'=> 'configuration emails','success'=>3));
                    die;
                }elseif($data['configuration'] == 1){ #if configuration email is entered validate the email being entered

                    ##checking if email is valid or not.
                    #set email address
                    $email_address = $data['email'];
                    #Initialize CURL:
                    $ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.'');
                    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(
                            'success'=>5,
                            'error'=>$validationResult['error']['info'],
                        )); 
                    }
                    if ($validationResult['format_valid'] && $validationResult['smtp_check']) {
                        return response()->json(array( 'error'=> 'email pop-up 1','success'=>2));
                    }else{
                        return response()->json(array( 'error'=> 'Invalid email','success'=>5));
                    }
                }elseif($data['configuration'] == 2){ #when do it later is clicked
                    ##checking if email is valid or not.
                    #set email address
                    $email_address = $data['email'];
                    #Initialize CURL:
                    $ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.''); 
                    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(
                            'success'=>5,
                            'error'=>$validationResult['error']['info'],
                        )); 
                    }
                    if ($validationResult['format_valid'] && $validationResult['smtp_check']) {}else{return response()->json(array( 'error'=> 'Invalid email','success'=>5));
                    }
                }
            }elseif((!empty($data['c_email']) || !empty($data['e_title']) || !empty($data['email_content'])) && !empty($data['email'])){ ##if email content is aDDED BUT email is chnaged so we need to check the email is valid or not

                if($data['configuration'] == 0){
                    return response()->json(array( 'error'=> 'configuration emails','success'=>3));
                    die;
                }elseif($data['configuration'] == 1){

                    ##checking if email is valid or not.
                    #set email address
                    $email_address = $data['email'];
                    #Initialize CURL:
                    $ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.''); 
                    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(
                            'success'=>5,
                            'error'=>$validationResult['error']['info'],
                        )); 
                    }
                    if ($validationResult['format_valid'] && $validationResult['smtp_check']) {}else{return response()->json(array( 'error'=> 'Invalid email','success'=>5));
                    }
                }
            }

            #add contributor session- ends

            #if image is sent
            if ($request->hasFile('image')) {
                #check valid image or not
                if($request->file('image')->isValid()) {
                    try {
                        $profile_img = time().'.'.$request->image->getClientOriginalExtension();
                        $request->image->move(public_path('/profilepic'), $profile_img);
                    } catch (\Exception $e) {
                        throw $this->createNotFoundException('Image not saved');
                    }
                }
            }

            #if form is added
            if ($request->hasFile('w9form')) {
                #check valid form or not
                if($request->file('w9form')->isValid()){
                    try{
                        $w9form = time().'.'.$request->w9form->getClientOriginalExtension();
                        $request->w9form->move(public_path('/w9form'), $w9form);
                    }catch (\Exception $e) {
                        throw $this->createNotFoundException('Form not saved');
                    }
                }
            }

            #if no image then get image from profile_image
            if (! $request->hasFile('image')) {
                $profile_img = $request->profile_image;
            }

            #if no image then get value from w9form
            if (! $request->hasFile('w9form')) {
                $w9form = $request->w9form;
            }

            #cryting the password
            if(!empty($data['password'])){
                $password = bcrypt($data['password']);
            }else{
                $password = NULL;
            }

            #make login type 2 i.e. contributor type
            $logintype = "2";
            try{
                $add_contributor = User::create([
                    'name' => $data['first_name']." ".$data['last_name'],    
                    'first_name' => $data['first_name'],
                    'last_name' => $data['last_name'],
                    'middle_name' => $data['middle_name'],
                    'email' => $data['email'],
                    'password'=> $password,
                    'birth_date' => $dob,
                    'postcode' => $data['postal_code'],
                    'phone_number' => $data['phone_number'],
                    'contract_date'=> $contract_date,
                    'address' =>$data['address'],
                    'profile_image' => $profile_img,
                    'w9_form'=> $w9form,
                    'facebook_link' => $data['facebook'],
                    'twitter_link' => $data['twitter'],
                    'instagram_link' => $data['instagram'],
                    'bio' => $data['bio'],
                    'login_type' => $logintype,
                    'country' => $data['country'],
                    'city' => $data['city'],
                    'state' => $data['state'],
                    'remember_token' => $data['_token'],
                    'added_by' => $data['added_by'],
                    'stage_name' => $data['stage_name'],
                    'profile_img_type'=> $data['profile_img_type'],
                    'pswd_check'=>0,
                ]);
            }catch (\Exception $e) {
                return $e->getMessage();
            }
                
            if(!empty($add_contributor) && !empty($data['email'])){
                #add contributor session- start
                session_start();
                $_SESSION["url_val"] = "message";

                if($data['configuration'] == 1){
                    $recipient = $data['c_email'];
                    $subject_email = $data['e_title'];
                    $content_email = htmlspecialchars_decode(htmlentities($data['email_content']));

                    //by nishant 12 dec 2018
                    $content_email = $content_email."<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').">";
                     
                    
                    $content_email= '<span style="font-size:14px;">'.$content_email.'</span>';                       

                    #for sending email
                    if(!empty($data['email'])){
                        if($data['password'] != ""){
                            //$this->index_mail(); #from basecontroller : setting for email 
                            try{
                                $post = array('from' => $from_email,
                                'fromName' => $from_name,
                                'apikey' => env('SENDMAIL_TOKEN'),
                                'subject' => $subject_email,
                                'to' => $recipient,
                                'bodyHtml' => $content_email,
                                'bodyText' => 'Text Body',
                                'isTransactional' => false);
                                $ch = curl_init();
                                curl_setopt_array($ch, array(
                                    CURLOPT_URL => env('SENDMAIL_API_URL'),
                                    CURLOPT_POST => true,
                                    CURLOPT_POSTFIELDS => $post,
                                    CURLOPT_RETURNTRANSFER => true,
                                    CURLOPT_HEADER => false,
                                    CURLOPT_SSL_VERIFYPEER => false
                                ));
                                $result=curl_exec ($ch);
                                curl_close ($ch);

                            $mail = Mail::raw([], function($message) use($recipient,$subject_email,$content_email,$from_email, $from_name) {
                                $message->replyTo($from_email, $from_name);
                                $message->to($recipient);
                                $message->subject($subject_email);
                                $message->setBody($content_email, 'text/html');
                            });
                            DB::table('users')->where('id',$add_contributor->id)->update(['email_sent'=>1]);
                            }catch(\Exception $e){
                                ##if error occured delete the newly created contributor
                                $del_contri = DB::table('users')->where('id',$add_contributor->id)->delete();
                                if($del_contri == 1){
                                    unset($_SESSION["url_val"]);
                                    return response()->json(array( 'error'=>$e->getMessage(),'success'=>4));
                                }
                            }
                        }
                    }
                    #for sending email

                    $added_by = Auth::user()->id;

                    #inserting into the database
                    $email_content_arr = [
                        'email_type'=>2,
                        'added_by'=>$added_by,
                        'email_title'=>$subject_email,
                        'email_content'=>$data['email_content'],
                        'from_setting'=>0,
                    ];

                    #insert into the db
                    try{
                        $insert_content = DB::Table('email_content')->insertGetId($email_content_arr);
                    }catch(\Exception $e){
                        return response()->json(array( 'error'=>$e->getMessage(),'success'=>0));
                    }

                    if($insert_content == "" || $insert_content == '0' || $insert_content == null){
                        unset($_SESSION["url_val"]);
                        return response()->json(array( 'error'=>'email content not added','success'=>0));
                        
                    }

                    #insert into the history

                    #get contributor id newly created
                    $contributor_id  = $add_contributor->id;

                    if($contributor_id == "" || $contributor_id == '0' || $contributor_id == null){
                        unset($_SESSION["url_val"]);
                        return response()->json(array( 'error'=>'Contributor id not found','success'=>0));
                    }
                    
                    $history_insert_arr = [
                        'contributor_id'=> $add_contributor->id,
                        'email_content'=>$insert_content,
                        'added_by'=>$added_by,
                        'enable_view'=>1,
                    ];

                    try{
                        $history_insert = DB::Table('email_history')->insertGetId($history_insert_arr);
                    }catch(\Exception $e){
                        return response()->json(array( 'error'=>$e->getMessage(),'success'=>0));
                    }

                    if($history_insert == "" || $history_insert == '0' || $history_insert == null){
                        return response()->json(array( 'error'=>'Contributor id not found','success'=>0));
                    }else{
                        return response()->json(array(
                            'msg'=> 'Account Details Updated Successfully',
                            'success'=>1,
                        ));
                   }
                }else{
                    return response()->json(array(
                        'msg'=> 'Account Details Updated Successfully.',
                        'success'=>1,
                    ));
                }
            }elseif(empty($add_contributor)){
                unset($_SESSION["url_val"]);
                return response()->json(array(
                    'msg'=> 'Some error occured',
                    'success'=>0,
                ));
                
            }elseif(!empty($add_contributor) && empty($data['email'])){
                #add contributor session- start
                session_start();
                $_SESSION["url_val"] = "message";

                return response()->json(array(
                    'msg'=> 'Account Details Updated Successfully',
                    'success'=>1,
                ));
            }
        }
    }/** ends add contributor function**/


    /**
    To get states in add contributor page
    **/

    public function getStateList(Request $request){  
        #request of country
        $country_id = $request->country_id;
        #get the state associated with that country
        try{
            $states_db = DB::table("state")
                    ->where('country_id', $country_id)->orderby('state','asc')
                    ->pluck("state","id");  
        }catch (\Exception $e) {
            return $e->getMessage()."Line no_o".$e->getLine();
        }

        $states = array();
        foreach($states_db as $s_id => $s_name){
            #adding a space to prevent sorting of states by id in jason
            $states[" ".$s_id] =$s_name;  #converting id > int to string
        }
        return response()->json($states);
    }


    /**

    To get cities in add contributor page

    **/

    public function getCityList(Request $request){
        #request of state_id
        #get the state associated with that country
        try{
            $cities_db = DB::table("city")
                    ->where("state_id",$request->state_id)
                    ->orderby("city","asc")
                   ->pluck("city","id");
        }catch (\Exception $e) {
            return $e->getMessage()."Line no_p".$e->getLine();
        }
        $cities = array();
        foreach($cities_db as $c_id => $c_name){
            #adding a space to prevent sorting of cities by id in jason
            $cities[" ".$c_id] =$c_name;  #converting id > int to string
        }
        return response()->json($cities);
    }


    /**
    Edit contributor view - load data in form
    **/


    public function edit_contributor_view(Request $request, $id){ 
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }        
        #load the countries in the drop from where the request of cities and state is being sent
        try{
            $countries = DB::table('country')->orderby('country','asc')->get(); 
        }catch(\Exception $e){
            return $e->getMessage()."Line no_q".$e->getLine();
        }
        #load the contributor's data from id
        try{
            $contributors = DB::table('users')
            ->select('users.id','users.password','users.last_name', 'users.first_name', 'users.middle_name', 'users.profile_image', 'users.w9_form', 'users.username', 'users.birth_date', 'users.country', 'users.state', 'users.city', 'users.postcode', 'users.phone_number','users.contract_date','users.address', 'users.facebook_link', 'users.twitter_link', 'users.instagram_link', 'users.bio', 'users.login_type','users.added_by', 'users.social_login', 'users.profile_img_type', 'users.instagram_id','users.balance', 'users.stage_name', 'users.contributor_comment', 'users.csv_id','users.merged_contributor','country.country as cval','state.state as sval','city.city as cityval','users.email')
            ->leftJoin('country', function ($join) {
                $join->on('users.country', '=', 'country.id');
                })
            ->leftJoin('state', function ($join) {
                $join->on('users.state', '=', 'state.id');
                })
            ->leftJoin('city', function ($join) {
                $join->on('users.city', '=', 'city.id');
            })
            ->where('users.id',$id)
            ->get(); 
        }catch(\Exception $e){
            return $e->getMessage()."Line no_r".$e->getLine(); 
        }
        #to show the list of states and cities
        $country_id = 0;
        $state_id = 0;
        #get the country id and state id and collect the states and cities corresponding to them in arrays and show the list on edit contributor page
        foreach($contributors as $contri){
            $contri = get_object_vars($contri);
            $country_id = $contri['country'];
            $state_id = $contri['state'];
        }
        #states 
        try{
            $states = DB::table('state')->select('state','id')->where('country_id',$country_id)->orderby('state','asc')->get();

        }catch(\Exception $e){
            return $e->getMessage()."Line states ".$e->getLine(); 
        }
        #cities
        try{
            $cities = DB::table('city')->select('city','id')->where('state_id',$state_id)->orderby('city','asc')->get();

        }catch(\Exception $e){
            return $e->getMessage()."Line cities ".$e->getLine(); 
        }
        return view('edit_contributor',compact('contributors','countries','states','cities'));
         
    } /* ends edit load contributor function */


     /**
    Edit contributor 
    **/

    public function edit_contributor(Request $request, $id){  
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #added by publisher's id
        $added_by = Auth::user()->id;
        
        #get all data
        $data = $request->all(); 
        #getting password from sent in hidden field
        $dbpassword = $request->dbpassword; 
        
        #checking if id sent, exists in table or not
        try{
            $checkid = User::where('id', '=', $id)->first(); 
        }catch(\Exception $e){
             return $e->getMessage()."Line no_s".$e->getLine(); 
        }

        #id does not exist
        if ($checkid === null) {
            return redirect('edit_contributor')->with("error","Looks like there is a problem. Please try again later");
        }

        #changing date format
        $date1 = $request->DOB;
        
        if(empty($date1)){
            $dob="";
        }else{
            $dob = date("Y-m-d", strtotime($date1));
        }

        #changing date format
        $contract_date1 = $request->contract_date;

        #if date is empty , make the variable empty 
        if(empty($contract_date1)){
            $contract_date = "";
        }else{
            $contract_date = date("Y-m-d", strtotime($contract_date1));
        }

        #validating
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'middle_name' => 'nullable|max:255',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1024',
            'w9form' => 'mimes:doc,docx,pdf',
            'email'  =>  'nullable|email|unique:users,email,'.$id,
            //'email'  =>  'nullable|email|unique:users,email,'.$id.',id,added_by,'.$added_by,
            //'email'  =>  'nullable|email',
            'DOB'=>'nullable',
            'contract_date' =>'nullable',
            'postal_code' => 'nullable|max:255',
            'phone_number'=> 'nullable',
            'contract_date'=>'nullable',
            'address' => 'nullable|max:255',
            'facebook' =>'max:255',
            'twitter' =>'max:255',
            'instagram' =>'max:255',
            'bio' =>'nullable|min:30|max:255',
            'country' =>'nullable|not_in:0',
            'city' =>'nullable|not_in:0',
            'state' =>'nullable|not_in:0',
            //'password' => 'nullable|min:6',
            'stage_name'=>'nullable|max:255',
        ]); 
        
        #returning errors back to view
        if ($validator->fails()) {
            return response()->json(array( 'error'=> $validator->getMessageBag()->toArray(),'success'=>0,));
        }  

        ##Email validate code start 
        $email_address = $data['email'];
        #Initialize CURL:
        $ch = curl_init('http://apilayer.net/api/check?access_key='.$this->access_key.'&email='.$email_address.'');  
        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( 'error'=> $validationResult['error']['info'],'success'=>3)); die;
        }
        if($validationResult['format_valid'] && !$validationResult['smtp_check']) {
            return response()->json(array( 'error'=> 'Invalid email','success'=>2)); die;     
        }
        #if image is being added
        if ($request->hasFile('image')) {
            if($request->file('image')->isValid()) {
                try {
                    $profile_img = time().'.'.$request->image->getClientOriginalExtension();
                    $request->image->move(public_path('/profilepic'), $profile_img);
                } catch (\Exception $e) {
                    throw $this->createNotFoundException('Image not saved');
                }
                $profile_img_type = 1;
            }
        }

        #if no image
        if (! $request->hasFile('image')) {
            if($request->profile_img_type == 1){

                #get old value from db sent in hidden field
                if ($request->has('db_image')) {    
                    $profile_img = $request->db_image;
                }else{
                    #no old value;no image saved in db;no new added > set var empty
                    $profile_img = "";
                }
                $profile_img_type = 1; #image uploaded manually
            }
            if($request->profile_img_type == 3){

                #get old value from db sent in hidden field
                if ($request->has('db_image')) {    
                    $profile_img = $request->db_image;
                }else{
                #no old value;no image saved in db;no new added > set var empty
                    $profile_img = "";
                }
                $profile_img_type = 3; #uploaded from csv
            }            
        }
        
        #if w9 form is being added
        if ($request->hasFile('w9form')) {
            if($request->file('w9form')->isValid()) {
                try {
                    $w9form = time().'.'.$request->w9form->getClientOriginalExtension();
                    $request->w9form->move(public_path('/w9form'), $w9form);
                } catch (\Exception $e) {
                    throw $this->createNotFoundException('Form not saved');
                }
            }
        }

        #if no w9form
        if (! $request->hasFile('w9form')) {
            #get old value from db sent in hidden field
            if ($request->has('db_w9form')) {   
                $w9form = $request->db_w9form;
            }else{
                #no old value;no form saved in db;no new added > set var empty
                $w9form = "";
            }
        }

        #if pwd is not changed
        if(($request->password)==""){
            $passwordgenerated = $dbpassword;
            $sendpassword = ""; #variable to check if password is changed
        }else{
            #if password is changed
            $passwordgenerated = bcrypt($request->password);
            $sendpassword = $request->password; #contains pswd to mail the contributor
        }
        #update data
        try{
            $updatecontri = DB::table('users')->where('id', $id)->update([
                'name' => $data['first_name']." ".$data['last_name'],    
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'middle_name' => $data['middle_name'],
                'email' => $data['email'],
                'password'=> $passwordgenerated,
                'birth_date' => $dob,
                'postcode' => $data['postal_code'],
                'phone_number' => $data['phone_number'],
                'contract_date'=> $contract_date,
                'address' =>$data['address'],
                'profile_image' => $profile_img,
                'w9_form'=> $w9form,
                'facebook_link' => $data['facebook'],
                'twitter_link' => $data['twitter'],
                'instagram_link' => $data['instagram'],
                'bio' => $data['bio'],
                'country' => $data['country'],
                //'city' => $data['city'],
                'city' => $data['city_name'],
                 //'state' => $data['state'],
                'state' => $data['state_name'],
                'remember_token' => $data['_token'],
                'added_by' => $data['added_by'],
                'stage_name'=>$data['stage_name'],
                'profile_img_type'=>$profile_img_type,
                //'updated_at'=>date("Y-m-d H:i:s")
            ]);  
        }catch (\Exception $e) {
            return $e->getMessage()." ".$e->getLine().$e->getFile();
        }

        #if changes are saved
        if($updatecontri == 1){
            /*for sending email only when contributor password is changed*/
            /*if(!empty($data['email'])){
                if($sendpassword != ""){ 
                    try{
                        $user = array('user_email'=>$data['email'], "user_password" =>$sendpassword);

                        $mail = Mail::to($data['email'])->send(new EditContributor($user));
                    }catch(\Exception $e){
                        return $e->getMessage()." >> Email Error<< ".$e->getLine();
                    }
                }
            }*/
                
            /*for sending email */
            return back()->with("message","Contributor Details Updated Successfully");
        }

        #if no changes were done in the form
        if($updatecontri == 0){
            return back()->with("message","Contributor Details Updated Successfully");
        }

        #if changes are not saved
        if(! $updatecontri){
            return back()->with("error","Contributor details not updated");
        }
    }/*Edit contributor Action end */


    /**
    Excel Sheet generation 
    **/

    public function get_export(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #id of the contributor
        $id = Auth::user()->id;
        #get the contributors and their given percentage along with books and roles
        try{
            $userdet = DB::raw("(select yearly_book_totals.totals,yearly_book_totals.year,bookdet.id,bookdet.assign_id,bookdet.book_title,bookdet.author_name,bookdet.contributor_id,bookdet.book_id,bookdet.role_id,bookdet.contributor_role,bookdet.percentage,bookdet.added_by from (select book_details.added_by,book_details.book_title,book_details.author_name,book_details.id,contri.book_id,contri.contributor_id ,contri.id as assign_id ,contri.role_id,contri.contributor_role,contri.percentage,contri.assigned_id from book_details left join (select assign_contributors.book_id,assign_contributors.contributor_id ,assign_contributors.id ,assign_contributors.percentage,assign_contributors.role_id,assign_contributors.id as assigned_id, contributor_roles.contributor_role from assign_contributors left join contributor_roles on assign_contributors.role_id = contributor_roles.id) as contri on book_details.id = contri.book_id ) as bookdet left join  yearly_book_totals on yearly_book_totals.amount_id = bookdet.assign_id ) as book_detail");
                $bookdetails = DB::table('book_detail')
                            ->select('users.name','book_detail.contributor_role','book_detail.book_title','book_detail.percentage')
                            ->from($userdet)
                            ->leftJoin('users', function ($join) {
                                $join->on('book_detail.contributor_id', '=', 'users.id');
                                })
                            ->where('book_detail.assign_id', '<>', '', 'and') //is not null
                            ->where('book_detail.added_by', $id)
                            ->where(function ($query) {
                                $query->where('users.merged_contributor','!=',1)
                                    ->orWhereNull('users.merged_contributor');
                            })
                            ->orderby('users.name', 'asc')
                            ->get();
                        
        }catch(\Exception $e){
            return $e->getMessage();
        }
        $bookdetails = $bookdetails->toArray();
        #creating heading of excel
        $b_details = array();
        $b_details[] = ['CONTRIBUTOR NAME', 'ROLES','BOOK TITLE','PERCENTAGE (%)'];
        foreach($bookdetails as $bd){
            $bd = get_object_vars($bd);
            $b_details[] = $bd;
        }
        #code to create excel
        return Excel::create('contributor_roles_'.date("m/d/Y"), function($excel) use ($b_details) {
            $excel->setTitle('Books/Percentage');
            $excel->setDescription('Percentage details');
            $excel->sheet('mySheet', function($sheet) use ($b_details){
                $sheet->fromArray($b_details, null, 'A1', false, false);
            });
        })->download('xls');
        return redirect('home');
    }/*Excel Sheet ends*/

    /* 
    Function for contributors info #modals
    */

    public function contributors_info(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #contributor's id
        $dataid=$_POST['id'];   
        #publisher id
        $id = Auth::user()->id;
        #get info of the contributor
        try{
            $contributorss = DB::table('users')
            ->select('users.name','users.last_name', 'users.id', 'users.email', 'users.first_name', 'users.middle_name', 'users.profile_image', 'users.w9_form','users.username', 'users.birth_date', 'users.country','users.state', 'users.city', 'users.postcode', 'users.phone_number', 'users.contract_date', 'users.address', 'users.facebook_link', 'users.twitter_link', 'users.instagram_link', 'users.bio', 'users.login_type', 'users.added_by', 'users.profile_img_type', 'users.instagram_id', 'users.stage_name','users.merged_contributor', 'country.country','state.state','city.city')
            ->leftJoin('country', function ($join) {
                $join->on('users.country', '=', 'country.id');
                })
            ->leftJoin('state', function ($join) {
                $join->on('users.state', '=', 'state.id');
                })
            ->leftJoin('city', function ($join) {
                $join->on('users.city', '=', 'city.id');
                })
            ->where('login_type', 2)
            ->where('added_by', $id)
            ->where(function ($query) {
                $query->where('users.merged_contributor','!=',1)
                    ->orWhereNull('users.merged_contributor');
            })
            ->where('users.id', $dataid)->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }
        
        #collect into array - one contributor can have multiple books
        $contributorslist = array();
        foreach($contributorss as $item){
            $item = get_object_vars($item);
            $contributorslist[$item['id']]['user_details']['id']= $item['id'];
            $contributorslist[$item['id']]['user_details']['name']= $item['name'];
            $contributorslist[$item['id']]['user_details']['email']= $item['email'];
            $contributorslist[$item['id']]['user_details']['last_name']= $item['last_name'];
            $contributorslist[$item['id']]['user_details']['first_name']= $item['first_name'];
            $contributorslist[$item['id']]['user_details']['middle_name']= $item['middle_name'];
            $contributorslist[$item['id']]['user_details']['profile_image']= $item['profile_image'];
            $contributorslist[$item['id']]['user_details']['w9_form']= $item['w9_form'];
            $contributorslist[$item['id']]['user_details']['username']= $item['username'];
            $contributorslist[$item['id']]['user_details']['birth_date']= $item['birth_date'];
            $contributorslist[$item['id']]['user_details']['country']= $item['country'];
            $contributorslist[$item['id']]['user_details']['state']= $item['state'];
            $contributorslist[$item['id']]['user_details']['city']= $item['city'];
            $contributorslist[$item['id']]['user_details']['postcode']= $item['postcode'];
            $contributorslist[$item['id']]['user_details']['phone_number']= $item['phone_number'];
            $contributorslist[$item['id']]['user_details']['contract_date']= $item['contract_date'];
            $contributorslist[$item['id']]['user_details']['address']= $item['address'];
            $contributorslist[$item['id']]['user_details']['facebook_link']= $item['facebook_link'];
            $contributorslist[$item['id']]['user_details']['twitter_link']= $item['twitter_link'];
            $contributorslist[$item['id']]['user_details']['instagram_link']= $item['instagram_link'];
            $contributorslist[$item['id']]['user_details']['bio']= $item['bio'];
            $contributorslist[$item['id']]['user_details']['login_type']= $item['login_type'];
            $contributorslist[$item['id']]['user_details']['added_by']= $item['added_by'];
            $contributorslist[$item['id']]['user_details']['stage_name']= $item['stage_name'];
            $contributorslist[$item['id']]['user_details']['profile_img_type']= $item['profile_img_type'];
            
        }
        #collect the values that need in popup.
        foreach($contributorslist as $key=>$value){
            #name
            $name = $value['user_details']['name'].'<img src="images/confirm.png"/>';
            #email
            if((empty($value['user_details']['email'])) ){
                $email = '<i class="fa fa-envelope fa-class" aria-hidden="true"></i>-';
            }else{
                $email = '<i class="fa fa-envelope fa-class" aria-hidden="true"></i>'.$value['user_details']['email'];
            }
            #Birth date
            if((empty($value["user_details"]["birth_date"])) ||  ($value["user_details"]["birth_date"] == '0000-00-00')){
                $birth_date = '<i class="fa fa-birthday-cake fa-class" aria-hidden="true"></i>-';
            }else{
                $birth_date = '<i class="fa fa-birthday-cake fa-class" aria-hidden="true"></i>'.$value['user_details']['birth_date'];
            }
            #Bio
            if(!empty($value['user_details']['bio'])){
                $bio = '<i aria-hidden="true" class="fa fa-quote-left fa-class"></i>'.$value['user_details']['bio'];
            }else{
                $bio = "<i aria-hidden='true' class='fa fa-quote-left fa-class'></i>This is bio of the contributor which is being added by the publisher. Please add the updated and bio related to the contributor's profile";
            }
            #Address
            $address = $value['user_details']['address'];
            #City
            if(!($value['user_details']['city'])){
                $city = 'No Record Found';
            }else{
                $city = $value['user_details']['city'];
            }
            #country
            if(!($value['user_details']['country'])){
                $country = 'No Record Found';
            }else{
                $country = $value['user_details']['country'];
            }
            #state
            if(!( $value["user_details"]["state"] )){
                $state = 'No Record Found';
            }else{
                $state = $value["user_details"]["state"];
            }
            #postcode
            if(empty($value['user_details']['postcode'])){
                $postcode = '-';
            }else{
                $postcode = $value['user_details']['postcode'];
            }
            #phone number
            if(empty($value["user_details"]["phone_number"])){
                $phone_number = '-';
            }else{
                $phone_number = $value["user_details"]["phone_number"];
            }
            #Date of contract
            if((empty($value["user_details"]["contract_date"])) || ($value["user_details"]["contract_date"] == '0000-00-00')){
                $contract_date = '-';
            }else{
                $contract_date = $value["user_details"]["contract_date"] ;
            }
            #W9 form
            if(!($value["user_details"]["w9_form"])){
                $w9form_status = '<div class="conts_detail"><span class="cont_title">W9 Form</span><span class="cont_desc">Pending<img src="images/pending.png"/></span></div>';
            }else{
                $w9form_status = '<div class="conts_detail"><span class="cont_title">W9 Form</span><span class="cont_desc">Verified<img src="images/confirm.png"/></span></div>';
            }
            #profile pic ans Social share
            if(!empty($value["user_details"]["profile_image"])){
                if($value["user_details"]["profile_img_type"] == 1){
                    $profile_pic = '<img id="book_preview" class="cont_profile_image contprofileimage" src="'.url('/profilepic/').'/'. $value['user_details']['profile_image'].'"><div class="share"><div class="share_btn"><img src="images/share.png"/></div><ul class="share_social"><li><a href="'.$value['user_details']['facebook_link'].'" target="_blank"><img src="images/fb.png"/></a></li><li><a href="'.$value['user_details']['twitter_link'].'" target="_blank"><img src="images/tw.png"/></a></li><li><a href="'.$value['user_details']['instagram_link'].'" target="_blank"><img src="images/insta.png"/></a></li></ul></div>';
                }
                if($value["user_details"]["profile_img_type"] == 3){
                    $profile_pic = '<img id="book_preview" class="cont_profile_image contprofileimage" src="'.$value['user_details']['profile_image'].'"><div class="share"><div class="share_btn"><img src="images/share.png"/></div><ul class="share_social"><li><a href="'.$value['user_details']['facebook_link'].'" target="_blank"><img src="images/fb.png"/></a></li><li><a href="'.$value['user_details']['twitter_link'].'" target="_blank"><img src="images/tw.png"/></a></li><li><a href="'.$value['user_details']['instagram_link'].'" target="_blank"><img src="images/insta.png"/></a></li></ul></div>';
                }
            }else{
                $profile_pic = '<span id="book_preview" class="cont_profile_image contprofileimage" style="background-image:url(images/profile_cover.png);"></span><div class="share"><div class="share_btn"><img src="images/share.png"/></div><ul class="share_social"><li><a href="'.$value['user_details']['facebook_link'].'" target="_blank"><img src="images/fb.png"/></a></li><li><a href="'.$value['user_details']['twitter_link'].'" target="_blank"><img src="images/tw.png"/></a></li><li><a href="'.$value['user_details']['instagram_link'].'" target="_blank"><img src="images/insta.png"/></a></li></ul></div>';
            }
        }
        #loading on click
        echo json_encode(array('success'=>1,'name'=>$name,'email'=>$email,'birth_date'=>$birth_date,'bio'=>$bio,'address'=>$address,'city'=>$city,'country'=>$country,'state'=>$state,'postcode'=>$postcode,'phone_number'=>$phone_number,'contract_date'=>$contract_date,'w9form_status'=>$w9form_status,'profile_pic'=>$profile_pic));
        exit;
    } /*load contri's info funtion ends here*/
    

    /**
    function for listing of books  #modals #R
    **/

    public function contributors_books(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #data
        $data = $_POST;
        #contributor's id
        $contri_id = $data['contri_id'];
        #publisher id
        $id = Auth::user()->id;
        #query
        try{
            $userdet = DB::raw("(select userdet.role_id, userdet.merged_contributor ,userdet.added_by,userdet.login_type,userdet.id,userdet.name,userdet.book_id,book_details.book_title,book_details.merged_book,book_details.out_of_print from (select users.added_by,users.merged_contributor,users.login_type,users.id,users.name, assign_contributors.book_id ,assign_contributors.role_id  from users LEFT JOIN assign_contributors on users.id = assign_contributors.contributor_id ) as userdet LEFT JOIN book_details on userdet.book_id = book_details.id) as alldetails");
            $contributorss = DB::table('alldetails')
            ->select('alldetails.id','alldetails.name','alldetails.book_id','alldetails.book_title','contributor_roles.contributor_role','alldetails.out_of_print')
            ->from($userdet)
            ->leftJoin('contributor_roles', function ($join) {
                $join->on('alldetails.role_id', '=', 'contributor_roles.id');
            })
            ->where('login_type', 2)
            ->where('added_by', $id)
            ->where(function ($query) {
                $query->where('alldetails.merged_contributor','!=',1)
                    ->orWhereNull('alldetails.merged_contributor');
            })
            ->where(function ($query) {
                $query->where('alldetails.merged_book','!=',1)
                    ->orWhereNull('alldetails.merged_book');
            })
            ->where('alldetails.id', $contri_id)
            ->distinct('alldetails.book_id')
            ->orderby('alldetails.book_title','asc')
            ->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }
        #collect into array - one contributor can have multiple books
        $contriname = array();
        $contributorslist = array();
        $bookids = array();
        foreach($contributorss as $key=>$item){
            $item = get_object_vars($item);
            $contributorslist['book_details'][$item['book_id']]['book_id']= $item['book_id'];
            $contributorslist['book_details'][$item['book_id']]['book_title']=$item['book_title'];
            $contributorslist['book_details'][$item['book_id']]['roles'][]=$item['contributor_role'];
            $contriname = $item['name'];//Contributor name
            $bookids[] = $item['book_id'];
            $contributorslist['book_details'][$item['book_id']]['out_of_print']=$item['out_of_print'];
        }
        #Check Container ids
        try{
            $check_container = DB::table('book_vol_containers')
            ->select('book_main_id','contained_book_id')
            ->leftJoin('book_details', function ($join) {
                $join->on('book_vol_containers.book_main_id', '=', 'book_details.id');
            })
            ->leftJoin('book_details as contained', function ($join) {
                $join->on('book_vol_containers.contained_book_id', '=', 'contained.id');
            })
            ->where(function ($query) {
                $query->where('book_details.merged_book','!=',1)
                    ->orWhereNull('book_details.merged_book');
            })
            ->where(function ($query) {
                $query->where('contained.merged_book','!=',1)
                    ->orWhereNull('contained.merged_book');
            })
            ->wherein('contained_book_id',$bookids)
            ->wherein('book_main_id',$bookids)
            ->get()->toArray();
        }catch(\Exception $e){
            return $e->getMessage();
        }
        $unsorted_container_list = array();
        foreach($check_container as $item){
            $item = get_object_vars($item);
            if(in_array($item['book_main_id'],$bookids) && in_array($item['contained_book_id'],$bookids)){
                $unsorted_container_list[$item['book_main_id']][] = $item['contained_book_id'];
            }else{
                $unsorted_container_list[$item['book_main_id']][] = '';
            }
        }
        #sort out the array
        $container_list = array();
        foreach($unsorted_container_list as $main => $ids){
            rsort($ids);
            $container_list[$main]=$ids;
        }
        #collecting container and simple books
        $final_array = array();
        foreach($contributorslist['book_details'] as $b_ids => $value){
            if(!empty($container_list)){
                foreach($container_list as $main_id => $data){
                    if(in_array($b_ids, $data) && !empty($data)){
                        #contained title
                        $final_array['container_collection'][$main_id]['contained_array'][$b_ids]['book_title']=$contributorslist['book_details'][$b_ids]['book_title'];
                        $final_array['container_collection'][$main_id]['contained_array'][$b_ids]['roles']=$contributorslist['book_details'][$b_ids]['roles'];
                        #out of print
                        $final_array['container_collection'][$main_id]['contained_array'][$b_ids]['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];
                    }
                    if(empty($data[0])){
                        #collection of containers with no contained items
                        $final_array['simple_array'][$main_id]['book_title']=$contributorslist['book_details'][$main_id]['book_title'];
                        $final_array['simple_array'][$main_id]['roles']=$contributorslist['book_details'][$main_id]['roles'];
                        #out of print
                        $final_array['simple_array'][$main_id]['out_of_print']=$contributorslist['book_details'][$main_id]['out_of_print'];
                    }
                }
                #check if there is a container
                if(array_key_exists($b_ids, $container_list)){
                    #make the main array
                    if(!empty($container_list[$b_ids][0])){
                        $final_array['container_collection'][$b_ids]['main_array']['roles']=$contributorslist['book_details'][$b_ids]['roles'];
                        $final_array['container_collection'][$b_ids]['main_array']['main_title']=$contributorslist['book_details'][$b_ids]['book_title'];

                        #out of print
                        $final_array['container_collection'][$b_ids]['main_array']['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];
                        $final_array['container_collection'][$b_ids]['main_array']['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];
                    }
                }
                #created an array of container plus contained items
                $container_contained  = array();
                foreach($container_list as $main_id => $data){
                    $container_contained[] = $main_id;
                    foreach($data as $ids){
                        $container_contained[] = $ids;
                    }
                }
                if(!in_array($b_ids,  $container_contained)){
                    $final_array['simple_array'][$b_ids]['book_title']=$contributorslist['book_details'][$b_ids]['book_title'];

                    $final_array['simple_array'][$b_ids]['roles']=$contributorslist['book_details'][$b_ids]['roles'];
                    #out of print
                    $final_array['simple_array'][$b_ids]['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];

                    $final_array['simple_array'][$b_ids]['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];
                }
            }else{
                #if there is no container items
                $final_array['simple_array'][$b_ids]['book_title']=$contributorslist['book_details'][$b_ids]['book_title'];

                $final_array['simple_array'][$b_ids]['roles']=$contributorslist['book_details'][$b_ids]['roles'];
                #out of print
                $final_array['simple_array'][$b_ids]['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];

                $final_array['simple_array'][$b_ids]['out_of_print']=$contributorslist['book_details'][$b_ids]['out_of_print'];
            }
        }
        $contriName =  '<h5>Contributor Name : <span class="book_name_more">'.$contriname.'</span></h5>';
        $add_html = '';
        $add_html .= '<div id="accordion">';
        if(!empty($final_array['simple_array'])){
            $add_html .= '<h3>Simple books<span class="manage_class"></span></h3><div><div class="contri_table"><table id="amount_table"><tr><th>S.No</th><th>Book Name</th><th>Role</th></tr>';

            $i = 1;
            foreach($final_array['simple_array'] as $key=>$item){
                #adding icon for out of print
                if($item['out_of_print'] != 0){
                    $out_icon = '<span aria-hidden="true" data-toggle="tooltip" data-placement="top" data-title="Out of Print" data-original-title="" title=""><img src="images/out_print.png" width="20"></span>';
                }else{
                     $out_icon = '';
                }
                ##removing '#' and & from link - starts 
                $link =  $item['book_title'];
                if (strpos($link, '#') !== false && strpos($link, '&') !== false) {
                   $link =  str_replace("#", "%23", $link);
                   $link =  str_replace("&", "%26", $link);
                }
                elseif(strpos($link, '#') !== false && strpos($link, '&') === false ) {
                    $link =  str_replace("#", "%23", $link);
                }elseif(strpos($link, '&') !== false  && strpos($link,  '#') === false ){
                   $link =  str_replace("&", "%26", $link);
                }
                ##removing '#' and & from link - ends
                #Give limit to title and add tooltip to display full name.
                $total_length = strlen($item['book_title']);
                if($total_length > 35){
                    $booktitl = substr($item['book_title'], 0, 35);
                    $add_html .= '<tr class="main_tr"><td>'.$i.'.</td><td><a class="blue_link" href="'.url('/').'/booklist?searched_val='.$link.'" target="_blank" data-toggle="tooltip" data-title="'.$item['book_title'].'" data-html="true">'.$booktitl.' . . . </a>'.$out_icon.'</td><td>'.implode(' , ',$item['roles']).'</td><tr>';
                }else{
                    $add_html .= '<tr class="main_tr"><td>'.$i.'. </td><td><a class="blue_link" href="'.url('/').'/booklist?searched_val='.$link.'" target="_blank">'.$item['book_title'].'</a>'.$out_icon.'</td><td>'.implode(' , ',$item['roles']).'</td></tr>';
                }
                $i++;
            }
            $add_html .= '</table></div></div>';
        }

        if(!empty($final_array['container_collection'])){
            $add_html .= '<h3>Container books<span class="manage_class"></span></h3><div class="contri_table"><div>';
            foreach($final_array['container_collection'] as $keys=>$items){
                #adding icon for out of print
                if($items['main_array']['out_of_print'] != 0){
                    $out_icon = '<span aria-hidden="true" data-toggle="tooltip" data-placement="top" data-title="Out of Print" data-original-title="" title=""><img src="images/out_print.png" width="20"></span>';
                }else{
                     $out_icon = '';
                }
                ##removing '#' and & from link - starts 
                $link =  $items['main_array']['main_title'];
                if (strpos($link, '#') !== false && strpos($link, '&') !== false) {
                   $link =  str_replace("#", "%23", $link);
                   $link =  str_replace("&", "%26", $link);
                }
                elseif(strpos($link, '#') !== false && strpos($link, '&') === false ) {
                    $link =  str_replace("#", "%23", $link);
                }elseif(strpos($link, '&') !== false  && strpos($link,  '#') === false ){
                   $link =  str_replace("&", "%26", $link);
                }
                ##removing '#' and & from link - ends
                $add_html .= '<div class="newbg_style"><h5 class="main_book"><b>Container book </b>: <a class="blue_link" href="'.url('/').'/booklist?searched_val='.$link.'" target="_blank">'.$items['main_array']['main_title'].'</a>'.$out_icon.'</h5><h5 class="main_role"><b>Role</b> : '.implode(' , ',$items['main_array']['roles']).'</h5><div class="digital_sample_download_'.$keys.' container_click" data-id="'.$keys.'"><i id="digital_csv_i_'.$keys.'" class="fa fa-caret-down red_link" aria-hidden="true"></i><span class="digital_csv_span red_link">Contained Items</span><ul  class="digital_sample_'.$keys.'" style="display:none"><li><table id="amount_table"><tr><th>S.No</th><th>Contained Book Name</th><th>Role</th></tr>';
                $i = 1;
                foreach($items['contained_array'] as $cid=>$value){
                    #adding icon for out of print
                    if($value['out_of_print'] != 0){
                        $out_icon = '<span aria-hidden="true" data-toggle="tooltip" data-placement="top" data-title="Out of Print" data-original-title="" title=""><img src="images/out_print.png" width="20"></span>';
                    }else{
                         $out_icon = '';
                    }
                    ##removing '#' and & from link - starts 
                    $link =  $value['book_title'];
                    if (strpos($link, '#') !== false && strpos($link, '&') !== false) {
                       $link =  str_replace("#", "%23", $link);
                       $link =  str_replace("&", "%26", $link);
                    }
                    elseif(strpos($link, '#') !== false && strpos($link, '&') === false ) {
                        $link =  str_replace("#", "%23", $link);
                    }elseif(strpos($link, '&') !== false  && strpos($link,  '#') === false ){
                       $link =  str_replace("&", "%26", $link);
                    }
                    ##removing '#' and & from link - ends
                    #Give limit to title and add tooltip to display full name.
                    $total_length = strlen($value['book_title']);
                    if($total_length > 35){
                        $booktitl = substr($value['book_title'], 0, 35);
                        $add_html .= '<tr class="main_tr"><td>'.$i.'.</td><td><a class="blue_link" href="'.url('/').'/booklist?searched_val='.$link.'" target="_blank" data-toggle="tooltip" data-title="'.$value['book_title'].'" data-html="true">'.$booktitl.' . . . </a>'.$out_icon.'</td><td>'.implode(' , ',$value['roles']).'</td><tr>';
                    }else{
                        $add_html .= '<tr class="main_tr"><td>'.$i.'.</td><td><a class="blue_link" href="'.url('/').'/booklist?searched_val='.$link.'" target="_blank">'.$value['book_title'].'</a>'.$out_icon.'</td><td>'.implode(' , ',$value['roles']).'</td><tr>';
                    }
                    $i++;
                }
                $add_html .= '</table></li></ul></div></div>';
            }
            $add_html .= '</div></div>';
        }
        echo json_encode(array('success'=>1,'add_html'=>$add_html,'contriname'=>$contriName));
        exit;
    }/*end of list of books function*/
    
    /** 
    Function to delete contributor #modal #R
    **/

    public function deletecontributor(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }        
        #data
        $data = $_POST;
        #contributor's id
        $contri_id = $data['contri_id'];
        #publisher id
        $id = Auth::user()->id;
        #query
        try{
            $contributorss = DB::table('users')
            ->select('users.id','users.name','users.login_type','users.added_by')
            ->where('login_type', 2)
            ->where('added_by', $id)
            ->where(function ($query) {
                $query->where('users.merged_contributor','!=',1)
                    ->orWhereNull('users.merged_contributor');
            })
            ->where('users.id', $contri_id)
            ->get();
        }catch(\Exception $e){
            return $e->getMessage();
        }
        #converting to array
        $contributorss = json_decode(json_encode($contributorss),true);
        #collecting the data
        $contid = $contributorss[0]['id'];
        $name = $contributorss[0]['name'];
        echo json_encode(array('success'=>1,'contid'=>$contid,'name'=>$name));
        exit;
    }/* end of delete contributor function*/

    /**
    Merge contributor pop-up #prabh
    **/

    public function merge_contributor_popup(Request $request, $id){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }        
        #logged in user
        $id = Auth::user()->id;
        #get name of main contributor
        try{
            $main_name = DB::Table('users')->where('id',$request->id)->value('name');
        }catch(\Exception $e){
            return $e->getMessage()." merge contri error1 ";
        }
        $main_name_html = '<h5>Contributor: <span class="book_name_more">'.$main_name.'</span></h5>';
        #get other contributors
        try{
            $get_contri = DB::Table('users')
            ->select('id','name')
            ->where('id','!=',$request->id)
            ->where('added_by',$id)
            ->orderby('name','asc')
            ->where(function ($query) {
                $query->where('merged_contributor','!=',1)
                    ->orWhereNull('merged_contributor');
            })
            ->get()
            ->toArray();
        }catch(\Exception $e){
            return $e->getMessage()." merge contri error2 ";
        }
        $list_of_contri = '';
        foreach($get_contri as $item){
        $list_of_contri .= '<li><input type="checkbox" name="merged_contri" value='.$item->id.' id="'.$item->id.'" /><label for="'.$item->id.'">'.$item->name.'</label></li>';
        }
        echo json_encode([
            'success'=>1,
            'list_of_contri'=>$list_of_contri,
            'main_name'=>$main_name_html,
            'main_id'=>$request->id,
        ]);
        exit;
    } ## merge_contributor_popup ends here

    /**
    Save merged contributor
    **/

    public function save_merged_contributor(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }        
        #logged in user
        $id = Auth::user()->id;
        #request array   
        $data = json_decode($request['data'],true);
        $main_array = reset($data);
        #for inserting into the merge_contrib table
        $insert_merge_contri = array();
        foreach( $main_array['sub_ids'] as $ids){
            $insert_merge_contri[] = ['main_contri'=>$main_array['main_id'], 'sub_contri'=>$ids];
        }
        #check if sub id exists in the assign contributor, then get the books and ids
        try{
            $check_sub_id1 = DB::Table('assign_contributors')->select('book_id','role_id','percentage')->wherein('contributor_id',$main_array['sub_ids'])->get();
        }catch(\Exception $e){
            return $e->getMessage()." save_merged_contributor error1 ";
        }
        $check_sub_id1 = json_decode(json_encode($check_sub_id1), true);
        #checking advances
        try{
            $check_adv_id = DB::Table('amount_details')->select('assigned_id','contributor_id','amount','quarter','year')->wherein('contributor_id',$main_array['sub_ids'])->get();
        }catch(\Exception $e){
            return $e->getMessage()." save_merged_contributor error1 ";
        }
        $check_adv_id = json_decode(json_encode($check_adv_id), true);
        #if there is some advance added : 
        $check_sub_id2 = $check_sub_id1;
        $checking_combination = array(); #for checking combination in db
        foreach($check_sub_id1 as $key => $item){
            $check_sub_id2[$key]['contributor_id'] = $main_array['main_id'] ;
            #for checking combination in db
            $checking_combination[$key]['contributor_id'] = $main_array['main_id'] ;
            $checking_combination[$key]['book_id'] = $item['book_id'] ;
            $checking_combination[$key]['role_id'] = $item['role_id'] ;
        }
        #if books found from sub ids assign it to the main id
        if(!empty($check_sub_id1)){
            #check if combination already existing
            foreach($checking_combination as $item){
                try{
                    $check_combination_vals[] = DB::Table('assign_contributors')->select('book_id','role_id','contributor_id')->where($item)->get()->toArray();
                }catch(\Exception $e){
                    return $e->getMessage()." -> save_merged_contributor error4"; 
                }
            }
            $check_combination_vals =json_decode(json_encode($check_combination_vals), true);
            $check_combination = array();
            foreach($check_combination_vals as $item){
                foreach ($item as $values){
                    $check_combination[] = $values;
                }
            }            
            $check_sub_id2 = array_map("unserialize", array_unique(array_map("serialize", $check_sub_id2)));
            #Difference   of $check_sub_id2 and $check_combination for remove the same data.
            $item12 = array();
            if(empty($check_combination)){
                $final_insertion = array();
                foreach($check_sub_id2 as $key => $item){
                    unset($item['percentage']);
                    $item12[] =  $item;
                }
                $item12 = array_values(array_map("unserialize", array_unique(array_map("serialize", $item12))));
                foreach($check_sub_id2  as $key => $item){
                    if(array_key_exists($key, $item12)){
                        if(!in_array($item12[$key], $check_combination)){
                        $final_insertion[$key] = $item12[$key];
                        $final_insertion[$key]['percentage'] = $check_sub_id2[$key]['percentage'];
                        }
                    }
                }
            }else{
                $final_insertion = array();
                foreach($check_sub_id2 as $key => $item){
                    unset($item['percentage']);
                    if(!in_array($item, $check_combination)){
                        $final_insertion[$key] = $item;
                        $final_insertion[$key]['percentage'] = $check_sub_id2[$key]['percentage'];
                    }
                }
            } 
           
            #insert into assign contributors the filtered array
            try{
                $insert_in_assign = DB::Table('assign_contributors')->insert($final_insertion);
            }catch(\Exception $e){
                return $e->getMessage()." -> save_merged_contributor error2";
            }
            
            #if successfully added, assign an id to the contributors that they will not be visible in list
            if($insert_in_assign == 1){
                try{
                    $update_key = DB::table('users')->wherein('id',$main_array['sub_ids'])->update(['merged_contributor' => 1]);
                }catch(\Exception $e){
                    return $e->getMessage()." -> save_merged_contributor error3";
                }

                #insert into merge_contributor table
                try{
                    $insert_merge_table = DB::Table('merged_contributors')->insert($insert_merge_contri);
                }catch(\Exception $e){
                    return $e->getMessage()." -> save_merged_contributor error5";
                }
                if($insert_merge_table ==1){
                    echo json_encode([
                        'success'=>1,
                        'succes_message'=>'Contributors merged successfully',
                    ]);
                    exit;
                }else{
                    echo json_encode([
                        'success'=>2,
                        'succes_message'=>'Some error occurred',
                    ]);
                    exit;
                }
            }else{
                echo json_encode([
                    'success'=>0,
                    'succes_message'=>'Some error occurred',
                ]);
            }
        }else{
            #means the sub ids dont have any books assigned
            #update key
            try{
                $update_key = DB::table('users')->wherein('id',$main_array['sub_ids'])->update(['merged_contributor' => 1]);
            }catch(\Exception $e){
                return $e->getMessage()." -> save_merged_contributor error3";
            }

            #insert into merge contri
            try{
                $insert_merge_table = DB::Table('merged_contributors')->insert($insert_merge_contri);
            }catch(\Exception $e){
                return $e->getMessage()." -> save_merged_contributor error5";
            }
            if($insert_merge_table ==1){
                echo json_encode([
                    'success'=>1,
                    'succes_message'=>'Contributors merged successfully',
                ]);
                exit;
            }else{
                echo json_encode([
                    'success'=>2,
                    'succes_message'=>'Some error occurred',
                ]);
                exit;
            }
        }
    }##save_merged_contributor


    /**
    save_credentials  for email confirgurations
    **/

    public function save_credentials(Request $request){
        
        #publisher's id
        $id = Auth::user()->id;
        #set email address
        $email_address = $request->email_from;
        #Initialize CURL:
        $ch = curl_init('http://apilayer.net/api/check?access_key='.$this->access_key.'&email='.$email_address.'');  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        #Store the data:
        $json = curl_exec($ch);
        curl_close($ch);
        #Decode JSON response:
        $validationResult = json_decode($json, true);
        
        #when newly added
        if($request->form_type == 0 && $request->del_check == 0){

            #collecting the details
            $email = $request->email_from;
            $name = $request->name_email;

            if(!isset($validationResult['format_valid']) && !isset($validationResult['smtp_check'])){
               return response()->json(array( 'success'=>0,'succes_message'=>$validationResult['error']['info'] )); 
            }
            
            if ($validationResult['format_valid'] && $validationResult['smtp_check']) {
                $insert_arr = ['publisher_id'=>$id,'email_id'=>$email,'email_name'=>$name];
                try{
                    $insert_q = DB::table('emal_configuration')->insert($insert_arr);
                }catch(\Exception $e){
                    return response()->json(array(
                        'success'=>0,
                       'succes_message'=>$e->getMessage(),
                    ));
                }
                
                if($insert_q == 1){
                   return response()->json(array(
                        'success'=>1,
                        'succes_message'=>'Details Added Successfully',
                    ));
                }else{
                    return response()->json(array(
                        'success'=>0,
                      'succes_message'=>'Some error occured',
                    ));
                }
            }else{
                return response()->json(array(
                   'success'=>2,
                   'succes_message'=>'Please enter valid email id',
                ));
                die;
            }
        }

        #when record is updated
        if($request->form_type == 1 && $request->del_check == 0){
            #collecting the details
            $email = $request->email_from;
            $name = $request->name_email;
            $update_arr = ['email_id'=>$email,'email_name'=>$name];

            if(!isset($validationResult['format_valid']) && !isset($validationResult['smtp_check'])){
               return response()->json(array( 'success'=>0,'succes_message'=>$validationResult['error']['info'], )); 
            }
            if ($validationResult['format_valid'] && $validationResult['smtp_check']){
                try{
                    $update_q = DB::table('emal_configuration')->where('publisher_id',$id)->update($update_arr);
                }catch(\Exception $e){
                   return response()->json(array(
                        'success'=>0,
                       'succes_message'=>$e->getMessage(),
                    ));
                }
                if($update_q == 1){
                    return response()->json(array(
                        'success'=>1,
                       'succes_message'=>'Details Updated successfully',
                    ));
                }elseif($update_q == 0){
                    return response()->json(array(
                        'success'=>0,
                       'succes_message'=>'No changes were done',
                    ));
                }else{
                    return response()->json(array(
                        'success'=>0,
                       'succes_message'=>'Some error occured',
                    ));
                }
            }else{
                return response()->json(array( 'success'=>2,'succes_message'=>'Please enter valid email id',));
            }
        }

        #if delete request is sent
        if($request->form_type == 1 && $request->del_check == 1){
            #delete the record
            try{
                $del_q = DB::table('emal_configuration')->where('publisher_id',$id)->delete();
            }catch(\Exception $e){

                return response()->json(array(
                    'success'=>0,
                   'succes_message'=>$e->getMessage(),

                ));
            }

            if($del_q == 1){
                return response()->json(array(
                   'success'=>1,
                   'succes_message'=>'Details deleted successfully',
                   'del_message'=>$del_q,
                ));
            }else{
                return response()->json(array(
                   'success'=>0,
                   'succes_message'=>'Some error occured',
                   'del_message'=>$del_q,
                ));
            }
        }
    }#save_credentials

    /**
    check missing first name and last name of contributors -> Now no use of this function , we used this as testing of any code.
    **/

    public function check_names(Request $request){
        #redirect to home if user not a contributor
        if(\Session::get('login_type') != 1){
            return redirect()->route('dashboard');
        }
        #logged in user
        $id = Auth::user()->id;
        #select contributors which are assigned multiple times to same book

        // try{
        //     $contri = DB::table('assign_contributors')
        //                 ->select('assign_contributors.contributor_id','assign_contributors.book_id','users.name','book_details.book_title')
        //                 ->selectRaw('count(book_id) as occurences')
        //                 ->leftJoin('users', function ($join) {
        //                     $join->on('assign_contributors.contributor_id', '=', 'users.id');
        //                 })
        //                 ->leftJoin('book_details', function ($join) {
        //                     $join->on('assign_contributors.book_id', '=', 'book_details.id');
        //                 })
        //                 ->groupby('assign_contributors.book_id','assign_contributors.contributor_id')
        //                 //->havingRaw('count(assign_contributors.book_id) > 1')
        //                 ->having('occurences', '>', 1)
        //                 ->where(function ($query) {
        //                     $query->where('users.merged_contributor','!=',1)
        //                         ->orWhereNull('users.merged_contributor');
        //                 })
        //                 ->where(function ($query) {
        //                     $query->where('book_details.merged_book','!=',1)
        //                         ->orWhereNull('book_details.merged_book');
        //                 })
        //                 ->where('users.added_by',$id)
        //                 ->get();

        // }catch(\Exception $e){
        //     return $e->getMessage();
        // }
        
        // print'<pre>';print_r($contri);die;

        // try{
        //     $check_books =  DB::Select("select `book_vol_containers`.id from `book_vol_containers` left join book_details on book_details.id = book_vol_containers.book_main_id where book_details.merged_book = 1 order BY `book_main_id` asc");
        // }catch(\Exception $e){
        //     $e->getMessage();
        // }

        // $ids = array();
        // foreach($check_books as $item){
        //     $item = get_object_vars($item);
        //     $ids[]=$item['id'];
        // }

        
        // try{

        //     $deletecontributor = DB::table('book_vol_containers')->wherein('id',$ids )->delete();

        // }catch(\Exception $e){
        //     return $e->getMessage();
        // }
       
        // "<pre>";print_r($deletecontributor);
        die;
        
       //  try{

       //      $check_books =  DB::Select("select dupes.book_main_id as  inner_container,dupes.contained_book_id as  inner_contained , book_vol_containers.added_by, book_vol_containers.book_main_id, book_vol_containers.contained_book_id,book_vol_containers.book_title from book_vol_containers INNER JOIN (select added_by , book_main_id, contained_book_id from book_vol_containers where added_by='".$id."') dupes on book_vol_containers.book_main_id = dupes.contained_book_id where book_vol_containers.added_by='".$id."'");


       //  }catch(\Exception $e){
       //      return $e->getMessage();
       //  }
       // // print'<pre>';print_r($check_books);die;

       //  $data = array();
       //  foreach($check_books as $item){
       //      $item = get_object_vars($item);
       //     //echo "<pre>";print_r($item);
       //      try{
       //          $update = DB::table('book_vol_containers')
       //          ->where('book_main_id',$item['book_main_id'])
       //          ->update(['book_main_id'=>$item['inner_container']]);
       //      }catch(\Exception $e){
       //          return $e->getMessage();
       //      }
       //  }

       //  //print_r($update);
       //  //$update == 1 if update the container in table

       //  echo "<pre>";print_r($update);

       //  die;

        /* Update books with black_friday in it */
        #parameters to check
        /*$values_array = ['isbn_code','asin_code','comixology_code','google_gg_key','itune_code','upc','qb_classes','diamond_item_code'];
        
        foreach($values_array as $data){

            try{
                $repeating_data[$data] = DB::select("select book_details.id, book_details.merged_book,book_details.book_title, book_details.asin_code,book_details.itune_code,book_details.comixology_code,book_details.google_gg_key,book_details.isbn_code,book_details.upc,book_details.qb_classes, book_details.diamond_item_code FROM book_details INNER JOIN (SELECT added_by,merged_book,book_title,comixology_code,asin_code,itune_code,diamond_item_code,google_gg_key,isbn_code,upc,qb_classes  FROM book_details  where added_by=".$id." GROUP BY ".$data." HAVING count(".$data.") > 1  ) dupes ON book_details.".$data." = dupes.".$data." where book_details.added_by=".$id." and book_details.".$data."<>'' ORDER BY book_details.".$data);
                
            }catch(\Exception $e){
                return $e->getMessage()." Line ".$e->getLine();
            }
           
        }#end foreach
        
        $repeating_array = array(); #array used to store data
        $repeating_data = json_decode(json_encode($repeating_data), true);

        foreach($repeating_data as $key => $item){
            $c = 0;
            foreach($item as $d){
                $c++;
                if(stripos($d['book_title'], 'BLACK FRIDAY') ){
                    unset($d['merged_book']);
                    $repeating_array[] = $d;
                }
            }
        }

        #unique arrays
        $repeating_array = array_unique($repeating_array, SORT_REGULAR);

        ///print'<pre>';print_r($repeating_array);die;

        foreach( $repeating_array as $d ){
            try{
                DB::table('book_details')
                            ->where('id', $d['id'])
                            ->where('added_by',$id)
                            ->update(['asin_code'=>NULL,
                                    'itune_code'=>NULL,
                                    'comixology_code'=>NULL,
                                    'google_gg_key'=>NULL,
                                    'isbn_code'=>NULL,
                                    'upc'=>NULL,
                                    'qb_classes'=>NULL,
                                    'diamond_item_code'=>NULL]);

            }catch (\Exception $e) {
              return $e->getMessage()." line number csv updation  :".$e->getLine(); 
            }
        }
        

        print'<pre>';print_r('all empty');die;*/
        

        /*try{
            $main_books = DB::table('merged_books')
                        ->select('main_book','sub_book','book_title as main_book_title','isbn_code as main_book_isbn')
                        ->leftJoin('book_details', function ($join) {
                            $join->on('merged_books.main_book', '=', 'book_details.id');
                        })
                        ->where('added_by',$id)
                        //->groupby('isbn_code')
                        ->distinct('isbn_code')
                        ->get();

        }catch(\Exception $e){
            return redirect()->route('check_names')->with("error",$e->getMessage()."Line no_a ".$e->getLine()); 
        }

        //print'<pre>';print_r($main_books);die;

        try{
            $sub_books = DB::table('merged_books')
                        ->select('main_book','sub_book','book_title as sub_book_title','isbn_code as sub_book_isbn')
                        ->leftJoin('book_details', function ($join) {
                            $join->on('merged_books.sub_book', '=', 'book_details.id');
                        })
                        ->where('added_by',$id)
                        //->groupby('isbn_code')
                        ->distinct('isbn_code')
                        ->get()->toArray();

        }catch(\Exception $e){
            return redirect()->route('check_names')->with("error",$e->getMessage()."Line no_a ".$e->getLine()); 
        }

        //print'<pre>';print_r($sub_books);die;
        $main_array = array();
        foreach($main_books as $key=>$main_book_id){
            $main_book_id = get_object_vars($main_book_id);
            if($sub_books[$key]->sub_book_isbn != $main_book_id['main_book_isbn'] && !empty($main_book_id['main_book_isbn']) && !empty($sub_books[$key]->sub_book_isbn)){
                $main_array[$key]=[
                                    'main_book_title'=>$main_book_id['main_book_title'],
                                    'main_book_isbn' => $main_book_id['main_book_isbn'],
                                    'sub_book_title'=>$sub_books[$key]->sub_book_title,
                                    'sub_book_isbn'=>$sub_books[$key]->sub_book_isbn,
                                    ];
            }

        } //print'<pre>';print_r($main_array);die;

        #excel sheet fields            
        $details = array();
        $details[] = ['MAIN BOOK NAME','MAIN BOOK ISBN CODE','SUB BOOK NAME','SUB BOOK ISBN CODE'];

        foreach($main_array as $bd){
            $details[]  = $bd;
        }

        try{
            return Excel::create('different_isbn_from_main_'.date("m/d/Y"), function($excel) use ($details){

                $excel->setTitle('Books/Percentage');
                $excel->setDescription('Book Report');

                $excel->sheet('sheet', function($sheet) use ($details){
                    $sheet->fromArray($details, null, 'A1', false, false);
                });

            })->download('xls');
        }catch(\Exception $e){
            return $e->getMessage();
        }*/

        /*try{
            $check_names = DB::Table('users')->select('id','name','first_name','last_name','middle_name')->where('added_by',$id)->whereNull('first_name')->whereNull('last_name')->get()->toArray();
        }catch(\Exception $e){  
            return $e->getMessage();
        }
        $check_names = json_decode(json_encode($check_names), true);
        echo '<pre>';print_r($check_names);die();

        $final_inser = array();
        foreach($check_names as $item){
            $first_name1 = explode(' ', $item['name']);
            //echo '<pre>';print_r($first_name).'<br>';
            if(count($first_name1)==3){
               $first_name = $first_name1[0];
               $middle_name = $first_name1[1];
               $last_name = $first_name1[2];
            }
            if(count($first_name1)==2){
               $first_name = $first_name1[0];
               $middle_name ='';
               $last_name = '';
            }
            if(count($first_name1)==2){
               $first_name = $first_name1[0];
               $middle_name ='';
               $last_name =  $first_name1[1];
            }
            $final_inser[$item['id']] = [
            //'id'=>$item['id'], 
            //'name' => $item['name'] ,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'middle_name'=>$middle_name,
            ];
            //echo '<pre>';print_r($final_inser);
            
        };
        foreach($final_inser as $book_id => $item){
            try{
                $update_users = DB::table('users')
                        ->where('added_by',$id)
                        ->where('id', $book_id)
                        ->update($item);
            }catch(\Exception $e){
                return $e->getMessage();
            }
        }
        echo '<pre>';print_r($update_users);die();
        echo '<pre>';print_r($update_users);die();*/
    } /*check_names controller ends here */

}/* controller end */