<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Traits\OrderByTable;
use Illuminate\Support\Facades\DB;
use Livewire\WithPagination;
class NotificationsController extends Component
{
    use WithPagination;
    use OrderByTable;

    public $count, $status_notifications, $user;
    public $search, $first_name, $last_name, $componentName, $pageTitle;

    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function updatingSearch(){
        $this->resetPage();
    }

    public function mount()
    {
        $this->user = auth()->user();

        $this->componentName = 'Notificaciones';
        $this->pageTitle = $this->user->getRoleNames()[0];
        $this->markAllNotificationsAsRead();
    }

    public function render()
    {
        $this->first_name = $this->user->first_name;
        $this->last_name = $this->user->last_name;

        if (strlen($this->search) > 0) {
            $notifications = $this->user->notifications()->where('data', 'LIKE', '%' . $this->search . '%')
            ->where(function ($query) {
                if ($this->status_notifications == 'unread') {
                    $query->where('read_at', NULL);
                }
                else if ($this->status_notifications == 'read') {
                    $query->where('read_at', '<>', NULL);
                }

            })
            ->orderBy('notifications.created_at', 'desc')
            ->paginate($this->pagination);
        }
        else{
            $notifications = $this->user->notifications()
            ->where(function ($query) {
                if ($this->status_notifications == 'unread') {
                    $query->where('read_at', NULL);
                }
                else if ($this->status_notifications == 'read') {
                    $query->where('read_at', '<>', NULL);
                }

            })
            ->orderBy('notifications.created_at', 'desc')
            ->paginate(10);
        }

        $this->count = auth()->user()->notifications->count();

        return view('livewire.notifications.component', compact('notifications'))
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function markAllNotificationsAsRead()
    {
        auth()->user()->notification = 0;
        auth()->user()->save();
    }

    public function markNotificationAsRead($id)
    {
        $notification = auth()->user()->notifications()->findOrFail($id);
        $notification->markAsRead();
        $this->count = auth()->user()->unreadNotifications->count();
    }




}
