<?php

namespace App\Http\Includes\Engineers;

use App\Models\Donor;
use App\Models\Drive;
use App\Models\Notification;
use App\Models\Team;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class TopBar extends Component
{
    public $search;
    public $queryString = ['search'];
    public function open($id)
    {
        $notification = Notification::find($id);
        if ($notification->user_id == 0) {
        } else {
            $notification->seen = true;
        }

        $notification->save();

        if (Auth::user()->belongsToTeam(Team::find(1))) {
            $home = '/engineers';
        } else if (Auth::user()->belongsToTeam(Team::find(2)) && Auth::user()->id != 1) {
            $home = '/frontdesk';
        } else if (Auth::user()->belongsToTeam(Team::find(3))) {
            $home = '/users';
        }

        if ($notification->user_id == 0) {
        } else {
            redirect()->to($home . $notification->link);
        }
    }

    public function render()
    {
        $notifications = Notification::orderBy('id','desc')->orWhere('user_id', 0)->orWhere('user_id', auth()->user()->id)->where('seen', false)->get();
        $drives = Drive::orWhere('iaea_no', 'LIKE', '%' . $this->search . '%')->orWhere('name', 'LIKE', '%' . $this->search . '%');
        $donors = Donor::orWhere('model_no', 'LIKE', '%' . $this->search . '%')->orWhere('serial_no', 'LIKE', '%' . $this->search . '%')->orWhere('name', 'LIKE', '%' . $this->search . '%')->get();
        $users = User::orWhere('first_name', 'LIKE', '%' . $this->search . '%')->orWhere('last_name', 'LIKE', '%' . $this->search . '%')->orWhere('email', 'LIKE', '%' . $this->search . '%')->get()->except(auth()->user()->id);

        foreach ($users as $user) {
            $drives = $drives->orWhere('user_id', $user->id);
        }
        if ($this->search == 'Drives') {
            $users = [];
            $donors = [];
        }
        if ($this->search == 'Users') {
            $drives = [];
            $donors = [];
        }

        if (Auth::user()->belongsToTeam(Team::find(1))) {
        } else if (Auth::user()->belongsToTeam(Team::find(2)) && Auth::user()->id != 1) {
        } else {
            $donors = [];
            $users = [];
            $drives = Drive::orWhere('iaea_no', 'LIKE', '%' . $this->search . '%')->orWhere('name', 'LIKE', '%' . $this->search . '%')->where('user_id', auth()->user()->id)->get();
        }

        $drives = $drives->get();

        return view('includes.engineers.top-bar', [
            'notifications' => $notifications,
            'drives' => $drives,
            'users' => $users,
            'donors' => $donors
        ]);
    }
}
