<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use DB;
use Redirect;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = 'admin/facilitylist';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
      //  $this->middleware('guest', ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }


    /*Regisetr and contact*/
    public function contact(Request $request ){

            

            $contact_name = $request->contact_name;
            $contact_email = $request->contact_email;
            $contact_phone = $request->contact_phone;
            $contact_descrip = $request->contact_description;


            $to      = 'info@golars.com,tejeswara.rao@golarsnetworks.com';
            $subject  = "Regarding Contact Us";
            $from     =  Session::get('salesforce_Name');
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$contact_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = '<html><body><h3 style="color:#52A2F4;">'.$contact_name.' want you to contact with you.</h3></br><p><b>Name: &nbsp;</b>'.$contact_name.'</p></br><p><b>Email: &nbsp;</b>'.$contact_email.'</p></br><p><b>Phone Number</b><br>'.$contact_phone.'</p></br><p><b> Description: &nbsp;</b><br>'.$contact_descrip.'</p></body></html>';
            mail($to, $subject, $message, $headers);
            
             $to      = $contact_email;
            $subject  = "Regarding Contact Us";
            //$from     =  'tejeswara.rao@golarsnetworks.com';
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$contact_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = 'We Have Recived Your request, We Will Contact You Shortly! If You Have Any Queries Feel Free To Contact Us on 1-317-500-0000.';
            mail($to, $subject, $message, $headers);
            //Session::flash('mail', 'We Will Contact You Shortly');

            return Redirect::back()->with('message','Request Email Has Been Sent. We Will Contact You Shortly ! If You Have Any Queries Please Contact Us.');


    }
    public function register(Request $request ){

            

            $reg_name = $request->reg_name;
            $reg_email = $request->reg_email;
            $reg_phone = $request->reg_phone;
            


            $to      = 'info@golars.com,tejeswara.rao@golarsnetworks.com';
            $subject  = "Regarding Register";
            $from     =  Session::get('salesforce_Name');
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$reg_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = '<html><body><h3 style="color:#52A2F4;">'.$reg_name.' want you to Register  with your organization.</h3></br><p><b>Name: &nbsp;</b>'.$reg_name.'</p></br><p><b>Email: &nbsp;</b>'.$reg_email.'</p></br><p><b>Phone Number</b><br>'.$reg_phone.'</p></body></html>';
            mail($to, $subject, $message, $headers);
            
             $to      = $reg_email;
            $subject  = "Regarding Contact Us";
            //$from     =  'tejeswara.rao@golarsnetworks.com';
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$reg_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = 'We Have Recived Your request, We Will Contact You Shortly! If You Have Any Queries Feel Free To Contact Us on 1-317-500-0000.';
            mail($to, $subject, $message, $headers);
            //Session::flash('mail', 'We Will Contact You Shortly');

            return Redirect::back()->with('message','Register Request Email Has Been Sent. We Will Contact You Shortly ! If You Have Any Queries Please Contact Us.');

    }
    public function Reset(Request $request ){

            

            $reset_name = $request->reset_name;
            $reset_email = $request->reset_email;
            $reset_phone = $request->reset_phone;
            
            $to      = 'info@golars.com,tejeswara.rao@golarsnetworks.com';
            $subject  = "Regarding Reset Password";
            $from     =  Session::get('salesforce_Name');
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$reset_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = '<html><body><h3 style="color:#52A2F4;">'.$reset_name.' want you to Reset  his password.</h3></br><p><b>Name: &nbsp;</b>'.$reset_name.'</p></br><p><b>Email: &nbsp;</b>'.$reset_email.'</p></br><p><b>Phone Number</b><br>'.$reset_phone.'</p></body></html>';
            mail($to, $subject, $message, $headers);
            
             $to      = $reset_email;
            $subject  = "Regarding Contact Us";
            //$from     =  'tejeswara.rao@golarsnetworks.com';
            //$email =Session::get('salesforce_email');
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers  .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers  .= 'From: '.$reset_email."\r\n".
            'Reply-To: '.$from."\r\n" .
            'X-Mailer: PHP/' . phpversion();
            $message   = 'We Have Recived Your request, We Will Contact You Shortly! If You Have Any Queries Feel Free To Contact Us on 1-317-500-0000.';
            mail($to, $subject, $message, $headers);
            //Session::flash('mail', 'We Will Contact You Shortly');

            return Redirect::back()->with('message','Reset Request Email Has Been Sent. We Will Contact You Shortly ! If You Have Any Queries Please Contact Us.');

    }
    /**
    * Get Login page
    */
    public function index(){
        
        return view('auth/login');
    }
    
    public function getLogin(Request $request)
    {

      if (Auth::check()) {
            return redirect('admin/facilitylist');
        }
        return view('auth/login');
    }

    /**
     * Post Login page
     */

    public function postLogin(Request $request)
    {
        
   
            /*$userdata = array(
                    'email' => 'user@golarstank.com',
                    'password' => '123456'
                  );
                  Auth::attempt($userdata);*/
                  
        $salesforce = new User;
        $remember=$request['remember'];
        if($remember!=1)
            $remember=0;
            if($request['email'] && $request['password'])
            {

                $email = $request['email'];
                $pass = $request['password'];



              //  $emailcheck = "SELECT External_ID__c,Passcode__c,Id FROM Contact WHERE External_ID__c ='".$email."'";

              $emailcheck =  "SELECT External_ID__c,Passcode__c,Id FROM Contact WHERE External_ID__c ='".$email."'";


               // $passcheck = "SELECT External_ID__c,Passcode__c,Id FROM Contact WHERE Passcode__c = '".$pass."'";

                 $Emailcheck = \Salesforce::query($emailcheck);


                // $Passcheck = \Salesforce::query($passcheck);

                 
                 $Emailchecking = count($Emailcheck->records); 
					if($Emailchecking > 0){
                 $Passchecking = $Emailcheck->records[0]->Passcode__c;
             
					}
                 if($Emailchecking <= 0 ){
                    $msg = '<h4 style="color:red;font-size:small;" >User ID IS Wrong</h4';
                    return $msg;
                 }elseif($pass != $Passchecking){
                    $msg = '<h4 style="color:red;font-size:small;">Password Is Wrong</h4';
                    return $msg;
                 }

                 $val_result = User::salesforce_auth( $email,$pass);

                if($val_result){
              
               $val_results = $val_result;

                  $userdata = array(
                    'email' => 'user@golarstank.com',
                    'password' => '123456'
                  );
              // doing login.
                    if (Auth::attempt($userdata)) { 
                        date_default_timezone_set('Asia/Calcutta');
                        $logout_date = date("Y-m-d H:i:s");

                         Session::set('salesforce_Id',$val_results[0]->Id);
                         Session::set('salesforce_Name',$val_results[0]->Name);
                        Session::set('salesforce_OwnerId',$val_results[0]->OwnerId);
                        //Session::set('salesforce_Email',$val_results[0]->Email);
                        session::get('salesforce_Id');
                        
                       $session_id =  session::get('salesforce_Id');
                       $session_name =  session::get('salesforce_Name');
                       $ip_address = $request->getClientIp();
                       //$session_email = session::get('salesforce_Email');
                       /*User Inserting on login*/

                     DB::table('ip_store')->insert(['user_id'=>$session_id,'ip_address'=>$ip_address]);


                       if (User::where('user_id', $session_id)->count() == 0) {
                           $new = new User;$new->user_id = $session_id;$new->name = $session_name;
                            $new->save();
                       }
                       $msg = 'success';
                        return $msg;
                        
                    } else{

                            
                    return  redirect('/');
                    }
            }else{

                 return  redirect('/');
            }

               /* User::salesforce_auth(['FirstName' =>$request['email'], 'Id' => $request['password']],$remember)*/
               //echo "string2"; die;
                /*Auth::user()->avatar_url==''?Session::set('avatar_url','../uploads/no_avatar.jpg'): Session::set('avatar_url',"../uploads/".Auth::user()->avatar_url);*/

               
            } else{
                 return redirect('/');
            }
         return redirect('/');
    }


}
