<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Employee;
use App\Device;
use Mail;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        $user = User::where("email", $credentials['email'])->first();

        if ($user) {
            if (Hash::check($credentials['password'], $user->password)) {
                return [
                    'status' => 200,
                    'message' => 'logged_in_successfully',
                    'profile' => $user
                ];
            } else {
                return [
                    'status' => 100,
                    'message' => 'email_or_password_is_invalid'
                ];
            }
        }
    }
    public function employee_login()
    {
        $credentials = request(['email', 'password']);

        $user = Employee::where("email", $credentials['email'])->first();
        $user->lastLogin = date("Y-m-d");
        $user->save();

        if ($user) {
            if (Hash::check($credentials['password'], $user->password)) {
                return [
                    'status' => 200,
                    'message' => 'logged_in_successfully',
                    'profile' => $user
                ];
            } else {
                return [
                    'status' => 100,
                    'message' => 'email_or_password_is_invalid'
                ];
            }
        }
    }

    public function signup()
    {
        // dd("working");
        $request = request(['email', 'password', "first_name", "last_name", "username", "type"]);
        $username = User::where("username", $request['username'])->first();
        if ($username) {
            return [
                'status' => 100,
                "message" => "username_already_exist"
            ];
        }
        $email = User::where("email", $request['email'])->first();
        if ($email) {
            return [
                'status' => 100,
                "message" => "email_already_exist"
            ];
        }
        User::create([
            'email' => $request['email'],
            'password' => bcrypt($request['password']),
            'first_name' => $request['first_name'],
            'last_name' => $request['last_name'],
            'username' => $request['username'],
            'type' => $request['type'],
        ]);

        $user = User::where("email", $request['email'])->first();

        return [
            'status' => 200,
            'message' => 'email_or_password_is_invalid',
            'profile' => $user
        ];
    }

    public function verifyManager()
    {
        // dd("working");
        $request = request(['code', 'id']);
        $user = User::where("id", $request['id'])->where('code', $request['code'])->first();
        if ($user) {
            $user->code = null;
            $user->save();
            return [
                'status' => 200,
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    public function verifyEmployee()
    {
        // dd("working");
        $request = request(['code', 'id']);
        $user = Employee::where("id", $request['id'])->where('code', $request['code'])->first();
        if ($user) {
            $user->code = null;
            $user->save();
            return [
                'status' => 200,
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    public function confirmEmail()
    {
        // dd("working");
        $request = request(['email']);
        $user = User::where("email", $request['email'])->first();
        if ($user) {
            $code = rand(1000, 9999);
            Mail::send('emails.html', ['content' => 'Kære '.$user->name.',<br><br>Din bekræftelseskode er: '.$code.'<br><br>Med venlig hilsen<br>Risskov Total Maler A/S'], function ($message) use ($user) {
              $message->from('noreply@rtmas.com', 'RTM A/S');
              $message->subject('Gendannelse af adgangskode');
              $message->to($user->email);
            });
            $user->code = $code;
            $user->save();
            return [
                'status' => 200,
                "message" => "email_found",
                "id" => $user->id
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    public function employeeConfirmEmail()
    {
        // dd("working");
        $request = request(['email']);
        $user = Employee::where("email", $request['email'])->first();
        if ($user) {
            $code = rand(1000, 9999);
            Mail::send('emails.html', ['content' => 'Kære '.$user->name.',<br><br>Din bekræftelseskode er: '.$code.'<br><br>Med venlig hilsen<br>Risskov Total Maler A/S'], function ($message) use ($user) {
              $message->from('noreply@rtmas.com', 'RTM A/S');
              $message->subject('Gendannelse af adgangskode');
              $message->to($user->email);
            });
            $user->code = $code;
            $user->save();
            return [
                'status' => 200,
                "message" => "email_found",
                "id" => $user->id
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    public function resetPassword()
    {
        // dd("working");
        $request = request(['id', 'password']);
        $user = User::where("id", $request['id'])->first();
        if ($user) {
            $user->password = bcrypt($request['password']);
            $user->save();
            return [
                'status' => 200,
                "message" => "password_changes_successfully"
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    public function employeeResetPassword()
    {
        // dd("working");
        $request = request(['id', 'password']);
        $user = Employee::where("id", $request['id'])->first();
        if ($user) {
            $user->password = bcrypt($request['password']);
            $user->save();
            return [
                'status' => 200,
                "message" => "password_changes_successfully"
            ];
        } else {
            return [
                'status' => 100,
            ];
        }
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth('api')->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
            'profile' => auth('api')->user(),
            'status' => 200
        ]);
    }

    public function sendNotification($id, $type, $title, $message = "")
    {
        $devices = Device::where("user_id", $id)->where("type", $type)->select("token")->orderBy('id', 'desc')->limit(10)->get();
        $responses = [];
        foreach ($devices as $device) {
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://exp.host/--/api/v2/push/send',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => 'to=' . $device->token . '&sound=default&title=' . $title . '&body=' . $message,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/x-www-form-urlencoded'
                ),
            ));

            $response = curl_exec($curl);
            $responses[] = $response;


            curl_close($curl);
        }
        return [
            'status' => 200,
            'message' => "Success",
            'response' => $responses
        ];
    }

    public function device(request $request)
    {

        $device = Device::where('token', $request->token)->where('type', $request->type)->where('user_id', $request->user_id)->first();
        if (!$device) {
            $device = new Device();
        }

        $device->token = $request->token;
        $device->type = $request->type;
        $device->user_id = $request->user_id;
        $device->platform = $request->platform;
        $device->save();
    }
}
