<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Notification as ModelNotification;
use App\Models\User;
use Illuminate\Http\Request;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Laravel\Firebase\Facades\Firebase;
use Kreait\Firebase\Contract\Messaging;
use App\Services\FirebaseNotificationService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Kreait\Firebase\Messaging\Notification;

class NotificationController extends Controller
{

    public function AllNotifications()
    {
        ModelNotification::whereDate('created_at', '<', now()->subDays(15))->delete();
        $userId = Auth::guard('sanctum')->id();
        $UnreadNotificationsCount = ModelNotification::where(['user_id' => $userId, 'read' => false])->count();
        $allNotifications = ModelNotification::where('user_id', $userId)->orderBy('id', 'DESC')->paginate(10);
        return sendCustomResponse(true, [
            'unread_count' => $UnreadNotificationsCount,
            'notifications' => $allNotifications->values(),
            'pagination' => CustomPagination($allNotifications),
        ], '', '');
    }

    public function changeStatus(Request $request)
    {
        try {
            $request->validate([
                'notification_id' => 'required|exists:notifications,id'
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $userId = Auth::guard('sanctum')->id();

        ModelNotification::where('id', $request->notification_id)->where('user_id', $userId)->update(['read' => true]);

        return sendCustomResponse(true, '', "Notification has been read successfully", '', 200);
    }

    public function allowNotifications(Request $request)
    {
        try {
            $request->validate([
                'allow_notifications' => 'required|boolean'
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $userId = Auth::guard('sanctum')->id();
        User::where('id', $userId)->update(['allow_notifications' => $request->allow_notifications]);

        return sendCustomResponse(true, '', "Notifications receiving has been changed successfully", '', 200);
    }
}
