<?php

namespace App\Http\Controllers\API\User;

use Validator;
use Illuminate\Http\Request;

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

/**
 * Class RegisterDevice
 *
 * @package App\Http\Controllers\API\User
 */
class RegisterDevice extends ApiController
{
    use FileSystemTrait;

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

        if (0 === count($errors->all())) {
            try {
                $token = FcmToken::where('device_id', $request->get('device_id'))->first();
                if (null === $token) {
                    $token = new FcmToken();
                }

                $token->useroid = $this->user->oid;
                $token->device_id = $request->get('device_id');
                $token->token = $request->get('fcm_token');
                $token->save();

                $this->response->setMessage(trans('messages.user_fcm_stored'));
            } catch (QueryException $e) {
                $errors->add('sql', $e->getMessage());
            }
        }

        return $this->response
            ->setSuccess((0 === count($errors->all())) ? TRUE : FALSE)
            ->setErrors($errors)
            ->toJson();
    }
}