<?php

namespace App\Http\Livewire;

use App\Models\Company;
use App\Models\Contract;
use App\Models\User;
use Symfony\Component\HttpFoundation\Request;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DashboardController extends Component
{
    public $company_name, $count_users, $count_companies, $count_contracts, $count_employees_actives, $company_plan_name;
    public function mount()
    {
        UserAuthPermission('Dashboard');
    }
    public function render()
    {

        if (Auth::user()->hasRole('Administrador') || Auth::user()->hasRole('Recursos Humanos') || Auth::user()->hasRole('Asistente Administrativo')) {
            $company_id = Auth::user()->CompanyInfo('id');
            $this->count_users = DB::table('company_user')->where('company_id', $company_id)->count();
            $this->count_companies = 1;
            $this->count_contracts = Contract::count();
            $this->count_employees_actives = User::Role('Empleado')->where(function ($query) {
                $query->where('status', 'ACTIVO');
            })->join('company_user', 'users.id', '=', 'company_user.user_id')
            ->where('company_user.company_id', $company_id)->count();
            //$company_plan_name = Company::find($company_id)->join('plans', 'companies.plan_id', '=', 'plans.id')->where('companies.id', $company_id)->first();
            $this->company_plan_name = Company::find($company_id)->plan;
        }
        else if (Auth::user()->hasRole('Empleado')){
            $this->company_name = Auth::user()->CompanyInfo('name');
        }
        else {
            $this->count_users = User::count();
            $this->count_companies = Company::count();
            $this->count_contracts = Contract::count();
            $this->count_employees_actives = User::Role('Empleado')->where('status', 'ACTIVO')->count();
            $this->company_plan_name = '';
        }
        return view('livewire.dashboard.component')
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function logout(Request $request) {
        Auth::logout();
        return redirect('/login');
    }
}
