<?php

namespace App\Http\Controllers;
use anlutro\LaravelSettings\Facade as Setting;

use Illuminate\Http\Request;
use App\Models\PushNotification;
use App\Models\UserAuthLogin;
use Illuminate\Support\Facades\Session;
class PushNotificationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = PushNotification::getLists();
        return view('notifications.index',compact('data'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        request()->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
        $input = $request->all();
        $postData = array(
            'title' => $input['title'],
            'description' => $input['description'],
            'created_at' => date("Y-m-d H:i:s")
        );
        if ($image = $request->file('image')) {
            $destinationPath = public_path('app-assets/images/notification/');
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $profileImage);
            $postData['image'] = "$profileImage";
        }
        PushNotification::create($postData);

        $tokens = array();
        $allTokens = UserAuthLogin::where('device_token','!=','web')->where('device_token','!=','')->where('device_token','!=','1')->pluck('device_token');
        foreach ($allTokens as $r) {
            array_push($tokens, $r);
        }

        $key = setting('fcm_key');
        \Helpers::sendNotification($tokens,$input['description'],$input['title'],$key);

        Session::flash('success', 'Push Notification created successfully!');
        return redirect()->route('notifications.index')
                        ->with('success','Push Notification created successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        PushNotification::find($id)->delete();
        Session::flash('success', 'Push Notification deleted successfully!');
        return redirect()->route('notifications.index')
                        ->with('success','Push Notification deleted successfully');
    }
}
