<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Enums\UserType;
use App\Models\Company;
use App\Models\Department;
use Illuminate\Http\Request;
use App\Enums\OriginStatusType;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
  /**
   * Handle the incoming request.
   */
  public function __invoke(Request $request)
  {
    $company = Company::active($request)->first();
    $department = Department::active($request)->first();

    $allowedRole = UserType::getValues();
    $user = auth()->user();

    $data = [
      'title' => 'Dashboard',
      'company' => $company,
      'department' => $department,
      'companies' => Company::selectOptions()
        ->where('status', OriginStatusType::Active)
        ->get(),
      'departments' => Department::selectOptions()
        ->where('status', OriginStatusType::Active)
        ->when($company, function ($query) use ($company) {
          $query->where('company_id', $company->id);
        })
        ->when($user->role !== UserType::PresidentDirector, function ($query) use ($user) {
          $query->whereHas('userDepartments', function ($q) use ($user) {
            $q->where('user_id', $user->id);
          });
        })
        ->get(),
    ];

    if (in_array($user->role, $allowedRole)) {
      return Inertia::render('Admin/Dashboard/Index', $data);
    }
    return redirect('/');
  }
}
