<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use  App\User;
use Illuminate\Support\Facades\Auth;
use  App\Mes_user;
use Session;

class AuthController extends Controller
{
    /**
     * Store a new user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function register(Request $request)
    {
        //validate incoming request 
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required'
        ]);

        try {

            $user = new User;
            $user->name = $request->input('name');
            $user->email = "a@b";
            $plainPassword = $request->input('password');
            $user->password = app('hash')->make($plainPassword);

            $user->save();

            $user = new Mes_user;
            $user->user_fname = $request->input('fname');
            $user->user_lname = $request->input('lname');
            $user->user_name = $request->input('name');
            $user->user_lvl = $request->input('lvl');
            $user->user_depoid = $request->input('depo');
            $user->user_departmentid = $request->input('depart');
            $user->user_cuser = $request->input('cuser');
            $user->user_cdate = $request->input('cdate');
            $user->user_edate = $request->input('cdate');
            $plainPassword = $request->input('password');
            $user->user_password = app('hash')->make($plainPassword);
            $user->save();

            //return successful response
            return response()->json(['user' => $user, 'message' => 'CREATED'], 201);

        } catch (\Exception $e) {
            //return error message
            return response()->json(['message' => $e], 409);
        }

    }

    public function login(Request $request)
    {
          //validate incoming request 
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required',
        ]);
        
       $ipad =  $request->ip();

        $credentials = $request->only(['name', 'password']);

        if (! $token = Auth::attempt($credentials)) {
            return response()->json(['message' => $ipad], 401);
        }

        $nm = $request->input('name');

        $results = app('db')->select("SELECT `mes_user`.*,`mes_depot`.`dep_name` from `mes_user` join `mes_depot` on `mes_depot`.`dep_id` = `mes_user`.`user_depoid` 
        where `user_name` ='$nm' and `user_departmentid` ='Marketing'");
            $token_id = $this->respondWithToken($token);
            
            if($results[0]->all_inactive!=0){
                return response()->json(['message' => 'Blocked User'], 401);
            }elseif($results[0]->user_status!=0){
                return response()->json(['message' => 'Success','token'=>$token_id->original['token'],'user'=>$results]);
            }else{
                return response()->json(['message' => 'Inactive User'], 401);
            }
            
            $_SESSION["uname"] = $results[0]->user_name;
    }
    
    public function login_web(Request $request)
    {
          //validate incoming request 
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required',
        ]);
        
       $ipad =  $request->ip();

        $credentials = $request->only(['name', 'password']);

        if (! $token = Auth::attempt($credentials)) {
            return response()->json(['message' => $ipad], 401);
        }

        $nm = $request->input('name');

        $results = app('db')->select("SELECT `mes_user`.*,`mes_depot`.`dep_name` from `mes_user` join `mes_depot` on `mes_depot`.`dep_id` = `mes_user`.`user_depoid` 
        where `user_name` ='$nm'");
            $token_id = $this->respondWithToken($token);
            
            if($results[0]->all_inactive!=0){
                return response()->json(['message' => 'Blocked User'], 401);
            }elseif($results[0]->user_status!=0){
                return response()->json(['message' => 'Success','token'=>$token_id->original['token'],'user'=>$results]);
            }else{
                return response()->json(['message' => 'Inactive User'], 401);
            }
            
            $_SESSION["uname"] = $results[0]->user_name;
    }

     public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }
    
    
    public function update(Request $request)
    {
        //validate incoming request 
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required'
        ]);

        try {

            $user = new User;
            $plainPassword = $request->input('password');
            $pwrd = app('hash')->make($plainPassword);

            User::where('name', $request->input('name'))
                ->update(['password' => $pwrd]);
                
            Mes_user::where('user_name', $request->input('name'))
                ->update(['user_password' => $pwrd]);

                     //return successful response
            return response()->json(['message' => "Done"], 409);

        } catch (\Exception $e) {
            //return error message
            return response()->json(['message' => $e], 409);
        }

    }
    
public function test(){
    $webservice_url = "https://www.w3schools.com/xml/tempconvert.asmx";

$input_celsius = 36;

$request_param = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <CelsiusToFahrenheit xmlns="https://www.w3schools.com/xml/">
      <Celsius>' . $input_celsius . '</Celsius>
    </CelsiusToFahrenheit>
  </soap12:Body>
</soap12:Envelope>';

$headers = array(
    'Content-Type: text/xml; charset=utf-8',
    'Content-Length: '.strlen($request_param)
);

$ch = curl_init($webservice_url);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $request_param);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$data = curl_exec ($ch);

$result = $data;

if ($result === FALSE) {
    printf("CURL error (#%d): %s<br>\n", curl_errno($ch),
    htmlspecialchars(curl_error($ch)));
}

curl_close ($ch);

echo $input_celsius . ' Celsius => ' . $data . ' Fahrenheit';
}

}