<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Notification;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NotificationController extends Controller
{
    //

    public function getNotificationMessage(Request $request)
    {
        if (!auth('backend')->check()) {
            return response([
                'status' => 0,
                'count' => 0,
                'html' => ''
            ]);
        }

        $userId = auth('backend')->user()->id;
        $page = $request->input('page', 1);
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $count =\DB::table('user_conversations')
	        ->join('conversations', 'user_conversations.conversation_id', '=', 'conversations.id')
            ->where('user_conversations.user_id', $userId)
	        ->whereNotNull('conversations.last_message_id')
            ->where('user_conversations.is_read_last_message', 0)
            ->whereNull('conversations.deleted_at')
            ->count();
        $items = Notification::message()->where('user_id', $userId)->limit($limit)->offset($offset)->orderBy('id', 'desc')->get();

        return response([
            'status' => 1,
            'count' => $count,
            'html' => view('frontend3.notification_item_home', compact('items'))->render()
        ]);
    }

    public function readNotification(Request $request)
    {
        $id = $request->input('id');
        $item = Notification::find($id);
        if ($item) {
            if ($item->is_read) {
                return response([
                    'status' => 0
                ]);
            } else {
                $item->is_read = true;
                $item->save();

                return response([
                    'status' => 1
                ]);
            }
        }

        return response([
            'status' => 0
        ]);
    }

    public function getNotificationHome(Request $request)
    {
        if (!auth('backend')->check()) {
            return response([
                'status' => 0,
                'count' => 0,
                'html' => ''
            ]);
        }

        $userId = auth('backend')->user()->id;
        $page = $request->input('page', 1);
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $count = Notification::publish()->where('is_read', false)->where('to_user', $userId)->count();
        $items = Notification::publish()->where('to_user', $userId)->limit($limit)->offset($offset)->orderBy('id', 'desc')->get();

        return response([
            'status' => 1,
            'count' => $count,
            'html' => view('frontend3.notification_item_home', compact('items'))->render()
        ]);
    }

}
