<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;
use App\Http\Controllers\API\BaseController as BaseController;
use Validator;
use App\Models\User;
class RegisterController extends BaseController
{
    public function register(Request $request)
    {
    	try{
	    	   $validator = Validator::make($request->all(), [
		            'name' => 'required',
		            'phone' => 'required|string|unique:users',
		            'password' => 'required',
	          ]);
	   
	        if($validator->fails()){
	            return $this->sendError('Validation Error.', $validator->errors());       
	        }

	        $input = $request->all();
	        $input['password'] = bcrypt($input['password']);
	        $input['name'] = $request->name;
	        $input['phone'] = $request->phone;
	        $user = User::create($input);	

	        $success['token'] =  $user->createToken('MyApp')->plainTextToken;
	        $success['id'] = $user->id;
	        $success['name'] =  $user->name;
	        $success['phone'] =  $user->phone;

	        return $this->sendResponse($success, 'User register successfully.');

    	}catch(Exception $e){
              
            $message = $e->getMessage();
  
            $code = $e->getCode();       
  
            $string = $e->__toString();       
            return response()->json(['message'=>$message, 'execption_code'=>$code, 'execption_string'=>$string]);
            exit;
        }
    }

    public function login(Request $request)
    {
        try{
        	if(Auth::attempt(['phone' => $request->phone, 'password' => $request->password])){ 
	            $user = Auth::user(); 
	            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
	            $success['id'] = $user->id;
		        $success['name'] =  $user->name;
		        $success['phone'] =  $user->phone;
	            return $this->sendResponse($success, 'User login successfully.');
	        } 
	        else{ 
	            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
	        } 
        }catch(Exception $e){
              
            $message = $e->getMessage();
  
            $code = $e->getCode();       
  
            $string = $e->__toString();       
            return response()->json(['message'=>$message, 'execption_code'=>$code, 'execption_string'=>$string]);
            exit;
        }
    }

    public function logout(Request $request)
    {   
    	try
    	{
    	   auth()->user()->tokens()->delete();
    	   return response()->json(['message'=>'successfully logged out!']);
    	}
    	catch(Exception $e){
    		$message = $e->getMessage();
  
            $code = $e->getCode();       
  
            $string = $e->__toString();       
            return response()->json(['message'=>$message, 'execption_code'=>$code, 'execption_string'=>$string]);
            exit;
    	}
    }
}
