<?php

namespace App\Http\Controllers\API\User;

use Validator;
use Illuminate\Http\Request;

use App\Libraries\Users\AuthAPI;
use App\Http\Controllers\API\ApiController;
use App\Models\User;

/**
 * Class Login
 *
 * @package App\Http\Controllers\API\User
 */
class Login extends ApiController
{

    /**
     * Returns the authentification data
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|min:4',
            'password' => 'required|min:8',
        ]);

        $errors = $validator->messages();

        if (0 === count($errors->all())) {
            $user = User::whereRaw(
                'username = ?',
                [
                    strtolower($request->get('username'))
                ]
            )->first();

            if ($user && password_verify($request->get('password'), $user->password)) {
                $auth = AuthAPI::getInstance()->setSession($user, false);
                $this->response
                    ->setResponse([
                        'user' => $user->apiOutputData([ 'token' => $auth['token_value'] ])
                    ])
                    ->setSuccess(true);
            } else {
                $errors->add('login_failed', __('validation.invalid_login'));
            }
        }

        return $this->response
            ->setErrors($errors)
            ->toJson();
    }
}