<?php

namespace App\Livewire\Admin;

use App\Models\Company;
use App\Models\Forum;
use App\Models\Job;
use App\Models\Notification;
use App\Models\Product;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class NotifcationComponent extends Component
{
    public $countUnreadNotif;
    public $notifications = [];
    public function render()
    {

        $this->countUnreadNotif = Notification::where('receiver_id', Auth::id())->where('is_read', 0)->count();

        return view('livewire.admin.notifcation-component');
    }

    public function markAsRead($id){
        $record = Notification::where('id', $id)->first();
        $record->is_read = 1;
        $record->save();
        if($record->model_id != null && $record->model_id > 0){
            if($record->type == 'PRODUCT'){
                $product = Product::find($record->model_id);
                if($product){
                    return redirect(route('admin.productDetail', $product->id));
                }
            }elseif($record->type == 'JOB'){
                $job = Job::find($record->model_id);
                if($job){
                    return redirect(route('admin.jobDetail', $job->id));
                }
            }elseif($record->type == 'FORUM'){
                $forum = Forum::find($record->model_id);
                if($forum){
                    return redirect(route('admin.forumDetail', $forum->id));
                }
            }elseif($record->type == 'COMPANY'){
                $company = Company::find($record->model_id);
                if($company){
                    return redirect(route('admin.companyDetail', $company->id));
                }
            }
        }
        $this->countUnreadNotif = Notification::where('receiver_id', Auth::id())->where('is_read', 0)->count();
    }

    public function fetchNotifications(){
        $this->notifications = Notification::where('receiver_id', Auth::id())
        ->orderBy('id', 'DESC')->limit(15)->get();
    }
}
