<?php

namespace App\Modules\Notifications\controllers\api\v1;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Modules\Notifications\Notification;

class NotificationsControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if ($request->get('count')) {
            return response()->json([
                'unread' => Notification::query()->currentUser()->unread()->get()->toArray(),
                'total'  => Notification::query()->currentUser()->count(),
            ]);
        }

        if ($request->get('markAsRead')) {
            $affected = Notification::query()->currentUser()->unread()->update(['read' => 1]);

            return ['affected' => $affected];
        }

        if ($request->get('clearAll')) {
            $affected = Notification::query()->currentUser()->unread()->update(['read' => 1]);

            return ['affected' => $affected, 'message' => 'All notifications marked as read'];
        }

        $query = Notification::query()->select('*')->currentUser();

        // For sidebar, show only unread notifications
        if ($request->get('unreadOnly')) {
            $query = $query->unread();
        }

        $query = $query->orderBy('id', 'desc')->paginate($request->get('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

        return response()->json($response);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    { }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    { }


    public function read($id)
    {
        return Notification::query()->where('id', $id)->update(['read' => true]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    { }
}
