<?php

namespace App\Http\Controllers;

use App\model\Company;
use Illuminate\Http\Request;
use Session;
use DB;
use Auth;



class CompanyController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     * @modified By: chintesh k
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request){

          $user_role  = Auth::user()->user_role;
          $items      = $request->items ?? 25;


          if($user_role == SUPERADMIN){

            $companys = Company::where('company_type',1);
            if(session('companyresult')!=''){

              $company  =   session('companyresult');
              $dataser  =   $company;
              $pref     =   session('setAgentAdminPrefrence');

              if($pref=='mgmt_name'){
                  
                $companys   =   $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_name', 'LIKE', '%'.$dataser.'%');
                                  });

              }else if($pref=='mgmt_email'){
                  
                $companys   =   $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_email', 'LIKE', '%'.$dataser.'%');
                                  });

              }else if($pref=='mgmt_mailing_fax'){
                  
                $companys   =   $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_mailing_fax','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                                  });

              }else if($pref=='mgmt_phone'){
                  
               $companys   =    $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_phone','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                                  });

              }else if($pref=='mgmt_add'){
                  
               $companys   =    $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_add','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                                  });

              }else if($pref=='mgmt_city'){
                  
                $companys   =   $companys->where(function($query) use ($dataser) {
                                  $query->select('*')
                                    ->where('mgmt_city','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                                  });

              }else{

                $companys  =  $companys->where(function($query) use ($dataser) {
                  $query->select('*')
                    ->where('mgmt_name', 'LIKE', '%'.$dataser.'%')
                    ->orWhere('mgmt_identifier', 'LIKE', '%'.$dataser.'%')
                    ->orWhere('mgmt_email', 'LIKE', '%'.$dataser.'%')
                    ->orWhere('mgmt_city','LIKE','%'.$dataser.'%')
                    ->orWhere('mgmt_add','LIKE','%'.$dataser.'%');
                  });
                }
            }
    
          $companys = $companys->sortable()->paginate($items);
          return view('company.index',['company_type'=>1,'heading'=>'Real State Company'], compact('companys'))->withMembers($companys)->withItems($items);
        }else{
          return redirect('viewcompany'); 
        } 
    }
    /**
     * Show the form for creating a new resource.
     * @modified By: chintesh k
     * @return \Illuminate\Http\Response
     */
    public function viewcompany(){

      $companyid  = Auth::user()->company;
      $company    = Company::find($companyid);
      $user_role  = Auth::user()->user_role;
      
      if($user_role != SUPERADMIN){
        if(!empty($company)){
          $state = DB::table('state')->select('id','state_name','state_value')->get();
          return view('company.profilecompany', compact('company'),['state' => $state]);
        }else{
          echo "Sorry you have not assigned company by admin";
        } 
      }else{
        return redirect('/');
      } 
    }

    /**
     * Show the form for creating a new resource.
     * @modified By: chintesh k
     * @return \Illuminate\Http\Response
     */
    public function management(Request $request){

        $user_role  = Auth::user()->user_role;
        $items      = $request->items ?? 25;
        $companys   = Company::where('company_type',2);
         
        if(session('companyresult')!=''){

          $company  =   session('companyresult');
          $dataser  =   $company;
          $pref     =   session('setAgentAdminPrefrence');

          if($pref=='mgmt_name'){
              
            $companys   =   $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_name', 'LIKE', '%'.$dataser.'%');
                              });

          }else if($pref=='mgmt_email'){
              
            $companys   =   $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_email', 'LIKE', '%'.$dataser.'%');
                              });

          }else if($pref=='mgmt_mailing_fax'){
              
            $companys   =   $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_mailing_fax','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                              });

          }else if($pref=='mgmt_phone'){
              
           $companys   =    $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_phone','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                              });

          }else if($pref=='mgmt_add'){
              
           $companys   =    $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_add','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                              });

          }else if($pref=='mgmt_city'){
              
            $companys   =   $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_city','LIKE','%'.preg_replace("/[^0-9.]/", "", $dataser).'%');
                              });

          }else{

            $companys   =   $companys->where(function($query) use ($dataser) {
                              $query->select('*')
                                ->where('mgmt_name', 'LIKE', '%'.$dataser.'%')
                                ->orWhere('mgmt_identifier', 'LIKE', '%'.$dataser.'%')
                                ->orWhere('mgmt_email', 'LIKE', '%'.$dataser.'%')
                                ->orWhere('mgmt_city','LIKE','%'.$dataser.'%')
                                ->orWhere('mgmt_add','LIKE','%'.$dataser.'%');
                              });
          }
        }
        $companys = $companys->sortable()->paginate($items);
        return view('company.index',['company_type'=>2,'heading'=>'Management Company'], compact('companys'))->withMembers($companys)->withItems($items);
    }

    /**
     * Show the form for creating a new resource.
     * @modified By: chintesh k
     * @return \Illuminate\Http\Response
     */
    public function setcompanyresult(Request $request){
      $agenrt_id = $request->input('company');
      Session::put('companyresult',$agenrt_id);
      echo 'success';
    }

    /**
     * Show the form for creating a new resource.
     * @modified By: chintesh k
     * @return \Illuminate\Http\Response
     */
    public function unsetcompanyresult(Request $request){
      $agenrt_id = $request->input('company');
      Session::forget('companyresult');
      echo 'success';
    }  

    /**
   * Show the form for creating a new resource.
   * @modified By: chintesh k
   * @return \Illuminate\Http\Response
   */
  public function mgmtsearch(Request $request){
      
      $ser      =   $request->input('inputVal'); 
      $role     =   Auth::user()->user_role;
      $id       =   Auth::user()->id;
      $company  =   Auth::user()->company;

      $pref     =   session('setAgentAdminPrefrence');
      
      if($pref=='mgmt_name'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_name) As result from company where mgmt_name LIKE '".$ser."%' AND company_type=2 ORDER BY result ASC");

      }else if($pref=='mgmt_email'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_email) As result from company  where mgmt_email LIKE '".$ser."%' AND company_type=2 ORDER BY result ASC");

      }else if($pref=='mgmt_mailing_fax'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT('(',substr(mgmt_mailing_fax,1,3),') ',substr(mgmt_mailing_fax,4,3),'-',substr(mgmt_mailing_fax,7)) As result from company  where mgmt_mailing_fax LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=2 ORDER BY result ASC");

      }else if($pref=='mgmt_phone'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT('(',substr(mgmt_phone,1,3),') ',substr(mgmt_phone,4,3),'-',substr(mgmt_phone,7)) As result from company where mgmt_phone LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=2");

      }else if($pref=='mgmt_add'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_add) As result from company  where mgmt_add LIKE '".$ser."%' AND company_type=2 ORDER BY result ASC");

      }else if($pref=='mgmt_city'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_city) As result from company  where mgmt_city LIKE '".$ser."%' AND company_type=2 ORDER BY result ASC");

      }else{

        $students = \DB::select("select CONCAT(mgmt_name) As result from company  where mgmt_name LIKE '".$ser."%' AND company_type=2 
            UNION select CONCAT(mgmt_identifier) As result from company  where mgmt_identifier LIKE '".$ser."%' AND company_type=2
            UNION select CONCAT(mgmt_email) As result from company  where mgmt_email LIKE '".$ser."%' AND company_type=2 
            UNION select CONCAT(mgmt_mailing_fax) As result from company  where mgmt_mailing_fax LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=2
            UNION select CONCAT(mgmt_phone) As result from company  where mgmt_phone LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=2 
            UNION select CONCAT(mgmt_add) As result from company  where mgmt_add LIKE '".$ser."%' AND company_type=2 
            UNION select CONCAT(mgmt_city) As result from company  where mgmt_city LIKE '".$ser."%' AND company_type=2 ORDER BY result ASC");
      }

      
        if(sizeof($students) > 0){
        $i=1;
       foreach ($students as $keyser => $valueser) {
           
           if($i==1){
               $class='selecteder';
           }else
           {
             $class='';   
           }
          echo "<p class='$class'>" .$valueser->result."</p>";
          
          $i++;
       }
    }else{
            echo "<p>No matches found</p>";
          }
  }

  /**
   * Show the form for creating a new resource.
   * @modified By: chintesh k
   * @return \Illuminate\Http\Response
   */
  public function companysearch(Request $request){
      
      $ser      =   $request->input('inputVal'); 
      $role     =   Auth::user()->user_role;
      $id       =   Auth::user()->id;
      $company  =   Auth::user()->company;

      $pref     =   session('setAgentAdminPrefrence');
      
      if($pref=='mgmt_name'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_name) As result from company where mgmt_name LIKE '".$ser."%' AND company_type=1 ORDER BY result ASC");

      }else if($pref=='mgmt_email'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_email) As result from company  where mgmt_email LIKE '".$ser."%' AND company_type=1 ORDER BY result ASC");

      }else if($pref=='mgmt_mailing_fax'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT('(',substr(mgmt_mailing_fax,1,3),') ',substr(mgmt_mailing_fax,4,3),'-',substr(mgmt_mailing_fax,7)) As result from company  where mgmt_mailing_fax LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=1 ORDER BY result ASC");

      }else if($pref=='mgmt_phone'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT('(',substr(mgmt_phone,1,3),') ',substr(mgmt_phone,4,3),'-',substr(mgmt_phone,7)) As result from company where mgmt_phone LIKE '%".preg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=1");

      }else if($pref=='mgmt_add'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_add) As result from company  where mgmt_add LIKE '".$ser."%' AND company_type=1 ORDER BY result ASC");

      }else if($pref=='mgmt_city'){
          
       $students = \DB::select("SELECT DISTINCT CONCAT(mgmt_city) As result from company  where mgmt_city LIKE '".$ser."%' AND company_type=1 ORDER BY result ASC");

      }else{
        
        $students = \DB::select("select CONCAT(mgmt_name) As result from company  where mgmt_name LIKE '".$ser."%' AND company_type=1 UNION select CONCAT(mgmt_identifier) As result from company  where mgmt_identifier LIKE '".$ser."%' AND company_type=1 UNION select CONCAT(mgmt_email) As result from company  where mgmt_email LIKE '".$ser."%' AND company_type=1 UNION select CONCAT(mgmt_phone) As result from company  where mgmt_phone LIKE '%".$serpreg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=1 UNION select CONCAT(mgmt_mailing_fax) As result from company where mgmt_mailing_fax LIKE '%".$serpreg_replace("/[^0-9.]/", "", $ser)."%' AND company_type=1  UNION select CONCAT(mgmt_add) As result from company  where mgmt_add LIKE '".$ser."%' AND company_type=1 UNION select CONCAT(mgmt_city) As result from company  where mgmt_city LIKE '".$ser."%' AND company_type=1 ORDER BY result ASC");
      }
      
      if(sizeof($students) > 0){
        foreach ($students as $keyser => $valueser) {
          echo "<p>" .$valueser->result."</p>";
        }
      }else{
        echo "<p>No matches found</p>";
      }
  }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        $input      = request()->all();
        if ($files = request()->file('mgmt_email_banner')) {

          $imageName = time().'.'.$files->getClientOriginalExtension();
          $files->move(uploadebannerpath(), $imageName);
        }else{
          $imageName = 'spiritre.png';  
        }

        $company                            =   new Company(); 
        $company->mgmt_name                 =   $input['mgmt_name'];
        $company->mgmt_email                =   $input['mgmt_email'];
        $company->mgmt_phone                =   $input['mgmt_phone'];
        $company->mgmt_add                  =   $input['mgmt_add'];
        $company->mgmt_city                 =   $input['mgmt_city'];
        $company->mgmt_state                =   $input['mgmt_state'];
        $company->mgmt_zip                  =   $input['mgmt_zip'];
        $company->mgmt_mailing_add          =   $input['mgmt_mailing_add'];
        $company->mgmt_mailing_city         =   $input['mgmt_mailing_city'];
        $company->mgmt_mailing_state        =   $input['mgmt_mailing_state'];
        $company->mgmt_mailing_zip          =   $input['mgmt_mailing_zip'];
        $company->mgmt_mailing_fax          =   $input['mgmt_mailing_fax'];
        $company->mgmt_web                  =   $input['mgmt_web'];
        $company->mgmt_primary_name         =   $input['mgmt_primary_name'];
        $company->mgmt_company_color        =   $input['mgmt_company_color'];
        $company->mgmt_email_banner         =   $imageName;
        $company->mgmt_delivery_service     =   $input['mgmt_delivery_service'];
        $company->mgmt_unsubscribe          =   $input['mgmt_unsubscribe'];
        $company->mgmt_domain               =   $input['mgmt_domain'];
        $company->mgmt_delivery_service_api =   $input['mgmt_delivery_service_api'];
        $company->company_type              =   1;
        $company->mgmt_market               =   '';
        $company->mgmt_manager              =   '';
        $company->mgmt_notes                =   '';

     if($company->save())
      {
        Session::flash('message', 'cpya');   
        Session::flash('alert-class', 'alert-success'); 
        return response()->json(['success'=>1]); 
    }
    else{
        Session::flash('message', 'Company not Added!');   
        Session::flash('alert-class', 'alert-danger');
        return response()->json(['success'=>0]); 

    } 
}

public function storemgmt()
    {
      $input = request()->all();
     
          $imageName = 'spiritre.png';  


      $company               = new Company(); 
      $company->mgmt_name                 = $input['mgmt_name'];
      $company->mgmt_identifier           = ''; //$input['mgmt_identifier'];
      $company->mgmt_email                = $input['mgmt_email'];
      $company->mgmt_phone                = $input['mgmt_phone'];
      $company->mgmt_add                  = $input['mgmt_add'];
      $company->mgmt_city                 = $input['mgmt_city'];
      $company->mgmt_state                = $input['mgmt_state'];
      $company->mgmt_zip                  = $input['mgmt_zip'];
      $company->mgmt_notes                = $input['mgmt_notes'];
      $company->mgmt_email_banner         = $imageName;
      $company->company_type              = 2;
      $company->mgmt_market               = $input['mgmt_market'];       
      $company->mgmt_manager              = $input['mgmt_manager'];
      $company->mgmt_mailing_fax          = $input['mgmt_mailing_fax'];
      $company->mgmt_web                  = $input['mgmt_web'];
                               
     if($company->save())
      {
        Session::flash('message', 'smgt');   
        Session::flash('alert-class', 'alert-success'); 
        return response()->json(['success'=>1]); 
    }
    else{
        Session::flash('message', 'Company not Added!');   
        Session::flash('alert-class', 'alert-danger');
        return response()->json(['success'=>0]); 

    } 
}

    /**
     * Display the specified resource.
     *
     * @param  \App\model\Company  $company
     * @return \Illuminate\Http\Response
     */
    public function show(Company $company)
    {
        $state = DB::table('state')->select('id','state_name','state_value')->get(); 

        $data['btntitle'] = 'Create Company';

        return view('company.addcompany',[
            'state' => $state,'company_type'=>1]);
    }

    public function addmanagement(Company $company){
      $state=DB::table('state')->select('id','state_name','state_value')->get();
      $data['btntitle'] = 'Create Company';
      return view('company.addmanagement',['state'=>$state,'company_type'=>2]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\model\Company  $company
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        $input = request()->all();
        $id    =   $input['id'];
        $company = Company::find($id);
         //echo '<pre>'; print_r($propertys); echo '</pre>'; die();
        $state = DB::table('state')->select('id','state_name','state_value')->get();
        return view('company.editcompany', compact('company'),[
         'state' => $state]);
    }

    public function editmanagement(){
      $input = request()->all();
      $id    =   $input['id'];
      $company = Company::find($id);
         //echo '<pre>'; print_r($propertys); echo '</pre>'; die();
      $state=DB::table('state')->select('id','state_name','state_value')->get();
      return view('company.editmanagement', compact('company'),['state' => $state]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\model\Company  $company
     * @return \Illuminate\Http\Response
     */

    public function checkcompany(Request $request){

           $company = $request->input('company');

            $id = $request->input('id');

           $Company = Company::where('mgmt_name','=',$company)->where('company_type',1)->whereNotIn('id',[$id])->first();
           
           if(!empty($Company)){
            echo '{"status":false,"res":"failed"}';
           }else{
              echo '{"status":true,"res":"Success"}';
           }
    }

    public function checkmanagement(Request $request){

      $company = $request->input('company');

      $Company=Company::where('mgmt_name','=',$company)->where('company_type',2)->first();
      if(!empty($Company)){
        echo '{"status":false,"res":"failed"}';
      }else{
          echo '{"status":true,"res":"Success"}';
      }
    }  
    public function update()
    {
        $input = request()->all();
        $id    =   $input['id'];
         if ($files = request()->file('mgmt_email_banner')) {

        // for save original image
        
        /*$ImageUpload = Image::make($files);
        $originalPath = 'public/images/';
        $ImageUpload->save($originalPath.time().$files->getClientOriginalName());

        // for save thumnail image
        $thumbnailPath = 'public/images/thumbnail/';
        $ImageUpload->resize(250,125);
        $ImageUpload = $ImageUpload->save($thumbnailPath.time().$files->getClientOriginalName());

        
        $bannername = time().$files->getClientOriginalName();*/

        $imageName = time().'.'.$files->getClientOriginalExtension();
        $files->move(uploadebannerpath(), $imageName);
        
        }
        else{
          
          $company = Company::find($id);

          $imageName = $company->mgmt_email_banner;  
        }

        if(isset($input['mgmt_identifier']) && $input['mgmt_identifier']!=''){
         $mgmt_identifier=$input['mgmt_identifier'];
        }else{
          $mgmt_identifier='';
        }

        $company = array(
            'mgmt_name'                 => $input['mgmt_name'],
            'mgmt_identifier'           => $mgmt_identifier,
            'mgmt_email'                => $input['mgmt_email'],
            'mgmt_phone'                => $input['mgmt_phone'],
            'mgmt_add'                  => $input['mgmt_add'],
            'mgmt_city'                 => $input['mgmt_city'],
            'mgmt_state'                => $input['mgmt_state'],
            'mgmt_zip'                  => $input['mgmt_zip'],
            'mgmt_mailing_add'          => $input['mgmt_mailing_add'],
            'mgmt_mailing_city'         => $input['mgmt_mailing_city'],
            'mgmt_mailing_state'        => $input['mgmt_mailing_state'],
            'mgmt_mailing_zip'          => $input['mgmt_mailing_zip'],
            'mgmt_mailing_fax'          => $input['mgmt_mailing_fax'],
            'mgmt_web'                  => $input['mgmt_web'],
            'mgmt_primary_name'         => $input['mgmt_primary_name'],
            'mgmt_email_banner'         => $imageName,
            'mgmt_company_color'        => $input['mgmt_company_color'],
            'mgmt_delivery_service'     => $input['mgmt_delivery_service'],
            'mgmt_unsubscribe'          => $input['mgmt_unsubscribe'],
            'mgmt_domain'               => $input['mgmt_domain'],
            'mgmt_delivery_service_api' => $input['mgmt_delivery_service_api']
          );

        //echo '<pre>'; print_r($property); echo '</pre>'; die();
        $updatecompany = Company::where('id', $id)->update($company);

        if($updatecompany)
        {
          Session::flash('message', 'cpuy');   
          Session::flash('alert-class', 'alert-success');  

      }
      else{
        Session::flash('message', 'Property not Updated!');   
        Session::flash('alert-class', 'alert-danger');

    } 
}
  
  public function updatemanagement()
    {
        $input = request()->all();
        $id    =   $input['id'];
        
          
        $company = Company::find($id);

        $imageName = $company->mgmt_email_banner; 

        $company = array(
            'mgmt_name'                 => $input['mgmt_name'],
            'mgmt_identifier'           => '',
            'mgmt_email'                => $input['mgmt_email'],
            'mgmt_phone'                => $input['mgmt_phone'],
            'mgmt_add'                  => $input['mgmt_add'],
            'mgmt_city'                 => $input['mgmt_city'],
            'mgmt_state'                => $input['mgmt_state'],
            'mgmt_mailing_fax'          => $input['mgmt_mailing_fax'],
            'mgmt_zip'                  => $input['mgmt_zip'],
            'mgmt_web'                  => $input['mgmt_web'],
            'mgmt_market'               => $input['mgmt_market'],       
            'mgmt_manager'              => $input['mgmt_manager'],
            'mgmt_notes'                => $input['mgmt_notes']      
          );

        //echo '<pre>'; print_r($property); echo '</pre>'; die();
        $updatecompany = Company::where('id', $id)->update($company);

      if($updatecompany)
      {
        Session::flash('message', 'umgt');   
        Session::flash('alert-class', 'alert-success');  
      }
      else{
        Session::flash('message', 'Property not Updated!');   
        Session::flash('alert-class', 'alert-danger');
    } 
}
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\model\Company  $company
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $istru = DB::table("company")->delete($id);
        if($istru)
        {
          Session::flash('message', 'scgt');   
          Session::flash('alert-class', 'alert-success');  
        }else{
          Session::flash('message', 'Record not Deleted!');   
          Session::flash('alert-class', 'alert-danger');
        } 
      return redirect('management');
    }
}
