<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ChangePass;
use App\Http\Requests;
use Illuminate\Support\Facades\Hash;
//use App\elf_users as Users;
use App\Agency;
use App\admins;
use App\Driver;
use App\Staff;
use App\timesheet_new;
use App\timesheet_values;
use App\self_certified;
use App\travel_form;
use App\users as Users;
use App\properties;
//use App\plans;
use Session;
use Mail;

class LoginController extends Controller
{
    public function login( Request $request )
    {   
     if(isset($_POST['username']))
       {
          $username = $_POST['username'];
          $pass = $_POST['pass'];
          if ($username == "admin@hgvdriverhub.app" && $pass == "queper12345") 
             {
                 //$educator = educators::where('id',$status->educator_id)->first();	
                  Session::put('email','admin@hgvdriverhub.app');
                  Session::put('adminController', '1');
                  Session::put('UserID','5645168');
                  Session::put('first_name','Admin');
                  Session::put('profile',url('/public/images/').'/avatar.png');
                  //Session::flash('info',' ');
                  return Redirect('/Dashboard');
             }
             // else
             // {
             // 	return Redirect('AdminLogin')->with('errors' , 'Invalid Password or Username');
             // }
          $results = Users::where('username','=',$username)->first();
          if($results)
          {
              if ($results->agency_id) {
                  $_agency_ = Agency::where("id", $results->agency_id)->first();
                  if ($_agency_->sub_domain != "portal.hgvdriverhub.app") {
                      Session::flash('error','Please try login to the correct domain!');
                      return Redirect('/');
                  }
              } elseif ($results->staff_id) {
                  $_staff_ = Staff::where("id", $results->staff_id)->first();
                  if ($results->sub_domain != "portal.hgvdriverhub.app") {
                      Session::flash('error','Please try login to the correct domain!');
                      return Redirect('/');
                  }
              }
              
            if($results->status == 3)
            {
               Session::flash('error','Your account has been Suspended.Please Contact Support');
               return Redirect()->back();
            }
          $HashPaswword = $results->password;
          if (Hash::check($pass, $HashPaswword))
             {
                  if($status = Users::where('username','=',$username)->first())
                  {
                    if($status)
                    { 
                      if($status->status != 1)
                      {
                        Session::flash('error','Your account is still under review.Please check logging back after 24Hours. If you are still not able to login please email us at support@hgvdriverhub.app');
                          return Redirect()->back();
                      }
                      if($results->role == 10)
                      {
                        // Session::put('adminController', '2');
                        // $_SESSION['roles'] = $results->role_details;
                        // Session::put('UserID',$results->id);
                        // Session::put('first_name',$results->full_name);
                        // Session::put('roles',$results->role_details);
                        // Session::put('address',$results->address);
                        // Session::put('phone',$results->phone);
                        // Session::put('email',$results->username);

                        // return Redirect('/Dashboard');
                      }
                      else
                      {
                        //$settings = settings::where('id',1)->first(); 
                        if($status->admin_id != '' || $status->admin_id != 0)
                        {
                          $admins = admins::where('id',$status->admin_id)->first();	
                          Session::put('email',$results->username);
                          Session::put('adminController', '1');
                          Session::put('AgencyID', '1');
                          Session::put('UserID',$admins->id);
                          Session::put('first_name',$admins->first_name);
                          Session::put('mobile',$admins->mobile);
                          Session::put('address',$admins->address);
                          Session::put('Accountancy','1');
                          Session::put('RouteChecker',1);
                          Session::put('Check','Admin');
                          Session::put('RouteCheckee',1);
                          Session::put('profile',url("public/images").'/'.$admins->profile_image);

                          $_SESSION['adminController'] = 1;
                          $_SESSION['RouteChecker'] = 1;
                          $_SESSION['Accountancy'] = 1;

                          return Redirect('Dashboard');
                        }
                        else if($status->staff_id != '' || $status->staff_id != 0)
                        {
                          //dd($status->staff_id);
                          $staff = Staff::where('id',$status->staff_id)->first();
                          $Agency = Agency::where('id',$staff->agency_id)->first();
                          if($Agency)
                          {
                            Session::put('Accountancy',$Agency->accountancy);
                            $_SESSION['Accountancy'] = $Agency->accountancy;
                          }
                          else
                          {
                            Session::put('Accountancy',1);
                            $_SESSION['Accountancy'] = 1;
                          } 
                          Session::put('email',$staff->email);
                          Session::put('adminController', '2');
                          Session::put('UserID',$staff->id);
                          Session::put('AgencyID', $staff->agency_id);
                          Session::put('first_name',$staff->first_name);
                          Session::put('mobile',$staff->phone_no);
                          Session::put('RouteChecker',1);
                          Session::put('address',$staff->home_address);
                          Session::put('Check','Staff');
                          Session::put('RouteCheckee',1);
                          Session::put('profile',url("public/images").'/'.$staff->profile_image);
                         
                          //Session::put('email',$results->username);
                          $_SESSION['adminController'] = 2;
                          if($status->agency_id == 1)
                          {
                            $_SESSION['RouteChecker'] = 1;
                            Session::put('RouteChecker',1);
                          }
                          else
                          {
                            $_SESSION['RouteChecker'] = 0;
                            Session::put('RouteChecker',0);
                          } 
                          

                          return Redirect('Dashboard');
                        }
                        else if($status->agency_id != '' && $status->agency_id >= 1 && $status->account_verification == 1)
                        {
                          $Agency = Agency::where('id',$status->agency_id)->first();	
                          //dd($Agency);
                          Session::put('email',$Agency->email);
                          Session::put('adminController', '3');
                          Session::put('AgencyID', $Agency->id);
                          Session::put('UserID',$Agency->id);
                          Session::put('first_name',$Agency->company_name);
                          Session::put('mobile',$Agency->phone_no1);
                          Session::put('Accountancy',$Agency->accountancy);
                          Session::put('address',$Agency->address_line1);
                          Session::put('Check','Hirer');
                          Session::put('profile',url("public/images").'/'.$Agency->profile_image);

                          $_SESSION['adminController'] = 3;
                          $_SESSION['Accountancy'] = $Agency->accountancy;
                           $_SESSION['RouteChecker'] = 1;

                          return Redirect('Dashboard');
                        }
                        else if($status->tenant_id != '' || $status->tenant_id != 0)
                        {
                          return Redirect()->back()->with('errors' , 'Your are not allowed to Login. Please download the Mobile App and Login. Thank you');
                        }
                        //echo "<center><h1>Profile Page Under Development</h1></center>";
                        
                       }
                          
                          echo 'Not Allowed';
                         
                    }
                    else
                    {
                         return Redirect()->back()->with('errors' , 'Your account is still under review.Please check logging back after 24Hours.If you are still not able to login please email us at support@hgvdriverhub.app');
                    }
                }
                else
                {
                    return Redirect()->back()->with('errors' , 'Your account is still under review.Please check logging back after 24Hours.If you are still not able to login please email us at support@hgvdriverhub.app');
                }
                 
             }
            else
            {
              Session::flash('error','Invalid Password');
               return Redirect()->back()->with('errors' , 'Invalid Password');   
            }
          }
          else
          {
            Session::flash('error','Invalid Username');
              return Redirect()->back()->with('errors' , 'Invalid Username');    
          } 
      }
      else
      {
         return Redirect('/');
      }
   }


  
  public function ChangePass( ChangePass $request )
  {
    
      $pass = $request->opass;
      $ID = Session::get('UserID');
      if(Session::get('Check') == 'Admin')
        {
          $results = Users::where('admin_id','=',$ID)->first();
        }
        elseif(Session::get('Check') == 'Hirer')
        {
          $results = Users::where('agency_id','=',$ID)->first();
        }
        elseif(Session::get('Check') == 'Staff')
        {
            $results = Users::where('staff_id','=',$ID)->first();
        }
      if($results)
          {
          $HashPaswword = $results->password;
          if (Hash::check($pass, $HashPaswword))
             {
               $results->password = Hash::make($request->confirm_password);
               $results->save();
               Session::flash('success','Password Changed Successfully');
               return redirect()->back();
             }
             else
             {
              Session::flash('error','Current Password Incorrect');
               return redirect()->back();
             }
        }
        else
        {
          return redirect('/');
        }

  }

    public function ChangePassNew( ChangePass $request )
  {
    
      $pass = $request->opass;
      $ID = Session::get('UserID');
      $results = Users::where('id','=',$ID)->first();
      if($results)
          {
          $HashPaswword = $results->password;
          $results->password = Hash::make($request->confirm_password);
          $results->save();
          $send_email = $results->username;
           Mail::send('emails.passChanged',['email' => $send_email], function ($message) use ($send_email)
           {
                $message->from('noreply@hgvdriverhub.app', 'HGV Driver Hub');
              $message->subject('Password Changed');
              $message->to($send_email);   
           }); 
          session_destroy();
          Session::flush();
          Session::flash('success','Password Changed Successfully');
          return redirect('/');
        }
        else
        {
          Session::flash('error','Invalid Request');
          return redirect('/');
        }

  }
    public function parsestring($string)
    {
      
      $string = str_replace("Percent","%",$string);
      return $string;
    }
    public function APPLogin($username,$pass)
    {   
     
     $username = $this->parsestring($username);
     $pass = $this->parsestring($pass); 
     if(isset($username))
       {
          $results = Users::where('username','=',$username)->first();
          if($results)
          {
            if($results->status == 3)
            {
              echo '0';
              //return Redirect()->back()->with('errors' , 'Account has been Blocked, Contact Support');
            }
          $HashPaswword = $results->password;
          if (Hash::check($pass, $HashPaswword))
             {
                  if($status = Users::where('username','=',$username)->where('status',1)->where('account_verification',1)->first())
                  {
                    //dd($status);
                    if($status)
                    { 
                      if($status->status != 1)
                      {
                         echo '2';
                      }
                      if($results->role == 10)
                      {
                        echo '3';
                      }
                      else
                      {
                        if($status->agency_id != '')
                        {
                           $agency = Agency::where('id',$status->agency_id)->first();
                           if($agency)
                           {
                              $data = json_encode($agency);
                              echo $data.'|-|Agency';
                           }
                        }
                        elseif($status->driver_id != '')
                        {
                           $driver = Driver::select('id','firebase_token','first_name','last_name','phone_no','email','address_line1','address_line2','town','post_code','dob','national_insurance_no','personal_bank_name','bank_sort_code','bank_account_no')->where('id',$status->driver_id)->first();
                           $timesheets = timesheet_new::where('driver_id',$driver->id)->count();
                           $expense = self_certified::where('driver_id',$driver->id)->count();
                           $travel = travel_form::where('driver_id',$driver->id)->count();
                           //dd($driver);
                           if($driver)
                           {
                              //$merged = array_merge($driver,$timesheets,$expense,$travel);
                              $data = json_encode($driver);
                              $data1 = json_encode($timesheets);
                              $data2 = json_encode($expense);
                              $data3 = json_encode($travel);
                              echo $data.'|-|Driver';
                           }
                        }
                        //echo '1';
                       }
                    
                         
                    }
                    else
                    {
                         echo '2';
                    }
                }
                else
                {
                     echo '2';
                }
                 
             }
            else
            {
               echo '4';   
            }
          }
          else
          {
              echo '6'; 
          } 
      }
      else
      {
         echo '5';
      }
   }

    public function activate($credentials)
    {
      $array = explode(":", $credentials);
      $HashPass = $array[1];
      $Data = users::where('username', $array[0])->where('status',0)->first();
      if($Data)
      {
        $status = $Data->status;
        if($status == 3)
        {
          Session::flush('error','System Failure');
          return redirect('/');
        }
        $send_email = $Data->username;
        $Data = $Data->password;
        $Data = str_replace("/", "", $Data);
        if($Data == $array[1])
        {
            if(users::where('username' , '=' ,$array[0])->update(['status' => 1]))
            {
            Mail::send('emails.activate',['name' => $array[0]], function ($message) use ($send_email)
             {

               $message->from('noreply@mysmarthandyman.app', 'MySmartHandyMan');
               $message->subject('Email Verified');
               $message->to($send_email);

             });
            Session::flash('success','Your account has been activated. Please Login to Continue.');
            return redirect('/');
          }
          else
          {
            Session::flash('error','System Failure');
             return redirect('/');
          }
        }
        else
        {
          Session::flash('error','System Failure');
          return redirect('/');
        }
      }
      else
      {
        Session::flush('error','System Failure');
        return redirect('/');
      }

    }
  
   public function logout()
    {
      //session_start();
      session_destroy();
      Session::flush();

      return redirect('/');
    }

  public function resetpass()
    {
      if(isset($_POST['username']))
       {
        $username = $_POST['username'];
        $results = Users::where('email','=',$username)->first();
        //dd($results);
        
        if($results)
        {
          // if($results->agency_id == '')
          // {
          //  Session::flash('error','Not Allowed');
          //   return Redirect()->back();
          // }
          $results->resetpass = 1;
          $results->save();
          $send_email = $results->username;
          $password = $results->password;
          $username = $results->username;
          Session::put('UserID',$results->id);
          $HashPass = str_replace("/","",$password);
          Mail::send('emails.reset',['email' => $send_email,'username' => $username, 'password' => $HashPass], function ($message) use ($send_email)
           {
                $message->from('noreply@hgvdriverhub.app', 'HGV Driver Hub');
              $message->subject('Reset Password');
              $message->to($send_email);   
           }); 
           session_destroy();
           Session::flush();
           Session::flash('success','We have sent you an email, Please check your email to reset your password.');
            return redirect('/');
        }
        else
        {
           Session::flash('error','Invalid Email, We do not have any member registered with this Email.');
          return Redirect()->back();
        }
       }
    }
     
  public function SetPass($credentials)
    {
      $array = explode(":", $credentials);
      $HashPass = $array[1];
      $Data = users::where('username', $array[0])->first();
      if($Data)
      {
        $status = $Data->status;
        if($status == 3)
        {
          return redirect('/');
        }
        $send_email = $Data->username;
        $Data = $Data->password;
        $Data = str_replace("/", "", $Data);
        //dd($array[1]);
        if($Data == $array[1])
        {
            if(users::where('username' , '=' ,$array[0])->update(['status' => 1]))
            { 
              $Data = users::where('username', $array[0])->first();
              Session::put('UserID',$Data->id);
              return redirect('ChangePasswordNew');
            }
          else
          {
             return redirect('/');
          }
        }
        else
        {
          return redirect('/');
        }
      }
      else
      {
        return redirect('/');
      }

    }

    function getChangepasswordNew()
                      {
                    return view('ChangepasswordNew', [
                        'page_title' => 'Change Password Via Email'
                            ]);

                     }
      public function resetpin($username)
    {

      if(isset($username))
       {
        $username = $username;
        $results = Users::where('username','=',$username)->first();
        //dd($results);
        if($results)
        {
          if($results->status != 0)
          {
            $results->resetpass = 1;
            $results->save();
            $send_email = $results->username;
            $password = $results->password;
            $username = $results->username;
            $HashPass = str_replace("/","",$password);
            Mail::send('emails.resetpin',['email' => $send_email,'username' => $username, 'password' => $HashPass], function ($message) use ($send_email)
             {
                  $message->from('noreply@hgvdriverhub.app', 'HGV Driver Hub');
                $message->subject('Reset PIN');
                $message->to($send_email);   
             }); 
              return redirect('/Login')->with('login', 'We have sent you an email, Please check your email to reset your PIN.');
          }
          else
          {
            return Redirect()->back()->with('errors', 'Invalid Email, We do not have any member registered with this Email.');
          }
        }
        else
        {
          return Redirect()->back()->with('errors', 'Account not Verified, Please verify your account to enable this option');
        }
       }
    }
    
  public function SetPassword($email,$cpass,$npass)
  {
    $npass = $this->parsestring($npass);
    $cpass = $this->parsestring($cpass); 
    $query = users::where('email', '=', $email)->first();
    if($query)
    {
     $pass = Hash::make($npass);
     $query->password = $pass;
     $query->save();
     echo 1;
    } 
    else
    {
      echo 0;
    }
  }
  
  public function UpdateSession($ID,$check)
  {
    if($check == 'Driver')
    {
     $query = users::where('driver_id', '=', $ID)->first();
    }
    else
    {
      $query = users::where('agency_id', '=', $ID)->first();
    }
    if($query)
    {
      $query->last_accessed = date('Y-m-d H:i:s');
      $query->save();
    }
  }

  public function AppVerifyMobile($email,$code)
  {
    $query = users::where('email', '=', $email)->first();
    if($query)
    {
      if($query->mobile_verify == $code)
      {
       echo 1;
      }
      else
      {
        echo 0;
      }
    }
    else
    {
      echo 0;
    }
  }
  public function resetpassApp($email)
    {
      $email = strtolower($email);
      if($email)
       {
        $username = $email;
        $results = Users::where('email','=',$username)->first();
        //dd($results);
        if($results)
        {
          if($results->status != 0)
          {
            $randomid1 = mt_rand(100000,999999);
            $results->resetpass = 1;
            $results->mobile_verify = $randomid1;
            $results->save();
            $send_email = $results->username;
            $password = $results->password;
            $username = $results->username;
            $HashPass = str_replace("/","",$password);
            
            if($results->driver_id != null || $results->driver_id != '')
            {
              $deep = Driver::where('id',$results->driver_id)->first();
              if($deep)
                {
                 $code = $randomid1;
                 $number = $deep->phone_no;
                 include 'sendmessage.php';

                 echo str_pad(substr($deep->phone_no, -4), strlen($deep->phone_no), '*', STR_PAD_LEFT);
              }
              else
              {
                echo 2;
              }
            }
            elseif($results->agency_id != null || $results->agency_id != '')
            {
              $deep = Agency::where('id',$results->agency_id)->first();
              if($deep)
                {
                 $code = $randomid1;
                 $number = $deep->phone_no1;
                 include 'sendmessage.php';

                 echo str_pad(substr($deep->phone_no1, -4), strlen($deep->phone_no1), '*', STR_PAD_LEFT);
              }
              else
              {
                echo 2;
              }
            }
            
            
          }
          else
          {
            echo 0;
          }
        }
        else
        {
          echo 2;
        }
       }
    }

     public function resetpass_email($credentials)
      {
        $array = explode(":", $credentials);
        $HashPass = $array[1];
        //var_dump($HashPass);
        //exit();
        $Data = Users::where('username', $array[0])->where('resetpass',1)->first();
        if($Data)
        { 
          $Data->resetpass = 0;
          $Data->save();
          $send_email = $Data->username;
          $Data = $Data->password;
          $Data = str_replace("/", "", $Data);
          if($Data == $array[1])
          {
              $origin = uniqid();
              $hashed_random_password = Hash::make($origin);
              if(Users::where('username' , '=' ,$array[0])->update(['password' => $hashed_random_password]))
                 {
                    Mail::send('emails.newpass',['email' => $send_email,'password' => $origin], function ($message) use ($send_email)
                    {
                            $message->from('noreply@hgvdriverhub.app', 'HGV Driver Hub');
                           $message->subject('New Password');
                           $message->to($send_email);
                           
                         }); 
             return redirect('/Login')->with('login', 'Please Check your email and Login with your new password');
          }
          else
          {
            return redirect('/');
          }
        }
        else
        {
            return redirect('/');
        }
      }
      else
      {
        return redirect('/');
      } 
    }


    public function resetpin_email($credentials)
      {
        $array = explode(":", $credentials);
        $HashPass = $array[1];
        //var_dump($HashPass);
        //exit();
        $Data = Users::where('username', $array[0])->where('resetpass',1)->first();
        if($Data)
        { 
          $Data->resetpass = 0;
          $Data->save();
          $send_email = $Data->username;
          $Data = $Data->password;
          $Data = str_replace("/", "", $Data);
          if($Data == $array[1])
          {
              $origin = uniqid();
              $value = rand();
              if(Users::where('username' , '=' ,$array[0])->update(['user_pin' => $value]))
                 {
                    Mail::send('emails.newpin',['email' => $send_email,'password' => $value], function ($message) use ($send_email)
                    {
                            $message->from('noreply@hgvdriverhub.app', 'HGV Driver Hub');
                           $message->subject('New PIN');
                           $message->to($send_email);
                           
                         }); 
             return redirect('/Login')->with('login', 'Your PIN for mobile app has been reset.');
          }
          else
          {
            return redirect('/');
          }
        }
        else
        {
            return redirect('/');
        }
      }
      else
      {
        return redirect('/');
      } 
    }


////////////////////////////////////// APP LOGIN FUNCTIONS /////////////////////////////////////////////////////////




    

}