<?php

namespace App\Http\Controllers\API\User;

use Validator;
use Illuminate\Http\Request;

use App\Http\Controllers\API\ApiController;
use App\Models\FcmToken;

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

    /**
     * Logout
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'device_id' => 'required'
        ]);
        $errors = $validator->messages();

        if (0 === count($errors->all())) {
            $fcmToken = FcmToken::where('device_id', $request->get('device_id'))->first();

            if ((null !== $fcmToken) && ($fcmToken->useroid === $this->user->oid)) {
                $fcmToken->delete();
                $this->response->setSuccess(true);
            } else {
                $errors->add('logout_device_id_not_found', trans('messages.logout_device_id_not_found'));
            }
        }

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