<?php

namespace App\Http\Controllers;

use App\model\Agentemail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Session;
use DB;
use Mail;
use App\User;
use App\model\Company;
use Auth;

class AgentemailController extends Controller
{

     public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    { 

              // \DB::enableQueryLog();
     // $query2 = DB::getQueryLog();
              // echo '<pre>'; print_r($query2); echo '</pre>'; die();
        //$useragent=$useragent->get();
        //Session::put('agent_id',$first->id);

      
     

      $id=Auth::user()->id;
      
        $data['arusers']=[];
        $data['distributors'] =[];
        $data['agents']=[];
        $data['show']='';
      
       
       $useragent=array();
      if(Auth::user()->user_role == AGENT)
      {
       // echo Auth::user()->user_role; exit;
        if(Auth::user()->manage_manager==1 && Auth::user()->agents_to_manager!=''){
          $agent=explode(',',Auth::user()->agents_to_manager);
 
          if(!empty($agent)){
        $useragent=User::whereIn('id',$agent)->where('status','=',1)->get();
      }
   
      }else{
        Session::put('agent_id',Auth::user()->id);
      }
      
      } 
      elseif(Auth::user()->user_role==ARUSER){
        $useragent=User::where('user_role','=',3)->where('assign_to_ar',Auth::user()->id)->where('status','=',1)->get();
      }elseif(Auth::user()->user_role==ADMIN){
          // DB::enableQueryLog();
          $useragent=User::where('user_role','=',3)
          ->where('create_by_user',Auth::user()->id)
          //->where('status','=',1)
          ->get();
          
            //dd(DB::getQueryLog()); exit;
      }else{
         $useragent=User::where('user_role','=',3)->where('status','=',1)->get();
      }

       if(!session('agent_id'))  
       {
        
         $agentemails = Agentemail::join('users', 'users.id', '=', 'email_list.agent_id')->select(
            'email_list.*',
            'users.name',
            'users.create_by_user',
            'users.last_name'
            );
            
            $first=$useragent->first();

            if(!empty($first)){
            $agentemails=$agentemails->where('email_list.agent_id','=',$first->id);
            Session::put('agent_id',$first->id);

          }else{
             $agentemails=$agentemails->where('email_list.agent_id','=',0);
          }
        } 
        else{

          //Session::forget('agent_id'); for unset session  
          $agentemails = Agentemail::join('users', 'users.id', '=', 'email_list.agent_id')
            ->select(
            'email_list.*',
            'users.name',
            'users.create_by_user',
            'users.last_name'
            )->where('email_list.agent_id', '=', session('agent_id'));
            //Session::forget('agent_id'); 
             // $useragent=User::where('user_role','=',3)->where('status','=',1)->get();
        } 

        $agentemails=$agentemails->sortable()->paginate(15);
      
        return view('agentemail.index',['usersagent' => $useragent,'url'=>'createagentemail','data'=>$data], compact('agentemails'));
    }


    public function email(){
      
        $id=Auth::user()->id;
        $role = Auth::user()->user_role;
       
      
        $data =array();
        $data['arusers']=[];
        $data['distributors'] =[];
        $data['agents']=[];
        $data['show']='1';
        $agentemails ='';
        if($role==1 || $role==2){
            
            $id           =   Auth::User()->id;
            $distributor = (!empty($_GET['distributor'])?$_GET['distributor']:'');
            $data['arusers']  =   User::where('user_role','=',4)
                                        ->where('users.create_by_user','=',$id)
                                        ->orderBy('name','ASC')
                                        ->get();
                              
            
            $data['distributors'] = User::where('user_role','=',AGENT)
                                        ->where('manage_distributor',1)
                                        ->where('status','=',1)
                                        ->where('company','=',Auth::user()->company)
                                        ->orderBy('name','ASC')
                                        ->get();
                                        
            //echo $distributor; exit;
            $id           =   Auth::User()->id;
            if(empty($distributor)){
                $data['agents'] =   User::where('user_role','=',3)
                                            ->where('create_by_user','=',$id)
                                        ->orderBy('name','ASC')
                                        ->get(); 
            }else{
                $data['agents'] =   User::where('user_role','=',AGENT)
                                        ->where('status','=',1)
                                        ->where('lead_source_access_to_gent', 'LIKE', '%' . $distributor . '%')
                                        ->orderBy('name','ASC')
                                        ->get(); 
            }
                                
            $aruser = (!empty($_GET['aruser'])?$_GET['aruser']:'');
            $agent = (!empty($_GET['agent'])?$_GET['agent']:$aruser);
           //print_r($id); exit;
            if(!empty($_GET['aruser']) || !empty($_GET['agent']) || !empty($_GET['distributor'])){
                $agentemails =Agentemail::where('agent_id',$agent)->sortable()->paginate(15);
            }else{
                $agentemails =Agentemail::where('agent_id',$id)->sortable()->paginate(15); 
            }
             
        }else{
             $agentemails =Agentemail::where('agent_id',$id)->sortable()->paginate(15);
        }
        ///echo $agentemails->count(); exit;
        //$agentemails =Agentemail::sortable()->paginate(15);
        return view('agentemail.index',['usersagent' =>array(),'url'=>'createemail','data'=>$data], compact('agentemails'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $id         =   Auth::user()->id;
        $useragent  =   array();
        if(Auth::user()->user_role != SUPERADMIN){
          $emaildetail = Agentemail::where('agent_id',Auth::user()->id) ->orderBy('id', 'desc')->first();
          
          $signature = $emaildetail['email_signature'];
        }else{
          $signature = '';
        }

      if(Auth::user()->user_role == AGENT){
       
        if(Auth::user()->manage_manager==1 && Auth::user()->agents_to_manager!=''){
          $agent=explode(',',Auth::user()->agents_to_manager);
 
          if(!empty($agent)){
            $useragent=User::whereIn('id',$agent)->where('status','=',1)->get();
          }
        }else{
          Session::put('agent_id',Auth::user()->id);
        }
      }elseif(Auth::user()->user_role == ARUSER){
        $useragent  =   User::where('user_role','=',3)->where('assign_to_ar',Auth::user()->id)->where('status','=',1)->get();
      }elseif(Auth::user()->user_role == ADMIN){
        $useragent  =   User::where('user_role','=',3)->where('create_by_user',Auth::user()->id)->where('status','=',1)->get();
      }else{
        $useragent  =   User::where('user_role','=',3)->where('status','=',1)->get();
      }

      $company      =  Auth::user()->company;
      $company      =  Company::find($company);


      if(!empty($company)){
        $logo   =   asset('/images/bannerimages/'.$company->mgmt_email_banner); 
      }else{
        $logo   =   asset('/images/spirit_logo.png');
      }

      return view('agentemail.createemail',
           ['usersagent'  => $useragent,
            'signature'   => $signature,
            'logo'        => $logo
            ]);
    }

    public function createemail(){

        $id   =   Auth::user()->id;
        if(Auth::user()->user_role != SUPERADMIN){
          $emaildetail = Agentemail::where('agent_id',Auth::user()->id) ->orderBy('id', 'desc')->first();
          $signature = (!empty($emaildetail['email_signature'])?$emaildetail['email_signature']:'');
        }else{
          $signature = '';
        }
        
        $company    =   Auth::user()->company;
        $company    =   Company::find($company);


        if(!empty($company)){
          $logo     =   asset('/images/bannerimages/'.$company->mgmt_email_banner);
        }else{
          
          $logo     =   asset('/images/spirit_logo.png');
        }

        return view('agentemail.createemail',
            [
              'usersagent'  =>  array(),
              'signature'   =>  $signature,
              'logo'        =>  $logo
            ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
    
       
       try {

            $data             = $request->input();
            $validatedData    = $request->validate([
                'email_name'      => 'required|max:100',
                'email_sub'       => 'required',
                'email_signature' => 'required',
            ]);
    
     //print_r($data); exit;
     
            $agentemail                  = new Agentemail(); 
            $agentemail->agent_id        = $data['agent_id'];
            $agentemail->email_name      = $data['email_name'];
            $agentemail->email_sub       = $data['email_sub'];
            $agentemail->email_signature = $data['email_signature'];
            $agentemail->email_body      = htmlentities($data['email_body']);
          
            if($agentemail->save()){
              Session::flash('message', 'ccc');   
              Session::flash('alert-class', 'alert-success');  
            }else{
              Session::flash('message', 'ncc');   
              Session::flash('alert-class', 'alert-danger');
      } 

        } catch (ModelNotFoundException $exception) {
            return back()->withError($exception->getMessage())->withInput();
        }
        
      return redirect($data['redirect']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\model\Agentemail  $agentemail
     * @return \Illuminate\Http\Response
     */
    public function show(Agentemail $agentemail)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\model\Agentemail  $agentemail
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

      $user_id=Auth::user()->id;
      $user_role=Auth::user()->user_role;
      $agentemail = Agentemail::find($id);

       // if($agentemail->agent_id!=$user_id){
          
       //    if($user_role!=ADMIN && $user_role!=SUPERADMIN){
       //         Session::flash('message',"You Don't have rights to edit this email!");   
       //        Session::flash('alert-class', 'alert-danger');
       //      return redirect('/agentemail');
       //   }else{

       //     if($user_role==ADMIN){
       //       $get_create_user=User::where('id',$agentemail->agent_id);

       //           if($get_create_user!=$user_id){

       //                Session::flash('message',"You Don't have rights to edit this email!");   
       //                Session::flash('alert-class', 'alert-danger');

       //               return redirect('/agentemail');
       //               }
               
       //               }
       //       }
       //   } 

       
       //print_r($agentemail); exit;

       return view('agentemail/editemail', compact('agentemail'),
         ['usersagent' => User::where('user_role','=',3)->where('id','!=',$id)->get(),'url'=>'agentemail']);
    }

 

    public function editemail($id){

        $user_id    =   Auth::user()->id;
        $user_role  =   Auth::user()->user_role;
        $agentemail =   Agentemail::find($id);
        
        $user_role=3;
        $agent_id =  $agentemail->agent_id;
        if(!empty($agent_id)){
            $User = User::where('id','=',$agent_id)->get();
            $user_role = $User[0]->user_role;
            
            $usersagent = User::where('user_role','=',$user_role)
                                        ->where('users.create_by_user','=',$user_id)
                                        ->get();
                                        
            // $usersagent = User::where('user_role','=',$user_role)
            //               ->where('id','!=',$id)
            //               ->get();
                                        
        }else{
            $usersagent = User::where('user_role','=',$user_role)
                          ->where('id','!=',$id)
                          ->get();
        }
        
    
        
        return view('agentemail/editemail', compact('agentemail'),
        [
        'usersagent'  => $usersagent,
        'url'         =>  'emails'
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\model\Agentemail  $agentemail
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Agentemail $agentemail)
    {
        $id = $request['id'];
        $redirect_url=$request->input('redirect_url');
        unset($_REQUEST['redirect_url']);
        $data = $request->input();
         //echo '<pre>'; print_r($data); echo '</pre>'; die();
        $agentemail = array(
          'agent_id'        => $data['agent_id'],
          'email_name'      => $data['email_name'],
          'email_sub'       => $data['email_sub'],
          'email_signature' => $data['email_signature'],
          'email_body'      => $data['email_body'],
        );

        //echo '<pre>'; print_r($user); echo '</pre>'; die();
        $updateagentemail = Agentemail::where('id', $id)->update($agentemail);

        if($updateagentemail)
        {
          Session::flash('message', 'uemail');   
          Session::flash('alert-class', 'alert-success');  
        }
        else{
          Session::flash('message', 'nuemail');   
          Session::flash('alert-class', 'alert-danger');
        } 
      return redirect('/'.$redirect_url.'/'.$id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\model\Agentemail  $agentemail
     * @return \Illuminate\Http\Response
     */
    public function destroy($id,Request $request)
    {    
      $redirect_url=$request->input('return_url');
         $istru = DB::table("email_list")->delete($id);
         if($istru)
         {
              Session::flash('message', 'eddd');   
              Session::flash('alert-class', 'alert-success');  

          }
          else{
              Session::flash('message', 'endd');   
              Session::flash('alert-class', 'alert-danger');

          } 
          return redirect($redirect_url);
    }

    public function setagentsesion(Request $request)
    {
      $agent_id = $_POST['agent_id'];
      $settype = $_POST['settype'];
      if($settype == 'setsig')
      {
        $emaildetail = Agentemail::where('agent_id',$agent_id) ->orderBy('id', 'desc')->first();
          //echo '<pre>'; print_r($emaildetail); echo '</pre>'; die();
        $signature = $emaildetail['email_signature'];
      }
      else
      {
        Session::put('agent_id', $agent_id);
      }
    }
}
