<?php

namespace App\Modules\Push;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Davibennun\LaravelPushNotification\Facades\PushNotification;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Crypt;
use Exception;
use App\Http\Controllers\BaseController;

class PushControllerREST extends BaseController
{
    public function store()
    {
        $data = request()->all();
        $data['user_id'] = getAuthUserId();

        $device = PushDevice::create($data);

        if (! $device->exists) {
            return response()->json(['errors' => $device->errors->all()], 400);
        }

        return $device;
    }

    public function sendPreviewData()
    {
        $device = PushDevice::query()->where('type', 'preview')->where('display_id', request()->get('preview_id'))->first();
        $data = json_encode(request()->all());

        if (! $device) {
            return response()->json(['error' => 'No display devices were found.'], 400);
        }

        try {
            PushNotification::app('androidFDTablet')
                ->to($device->device_id)
                ->send(Crypt::encrypt($data));
        } catch (Exception $e) {
            Log::error($e);
        }
    }
}
