<?php

namespace App\Http\Controllers\Employee;

use App\Models\Rule;
use App\Models\User;
use App\Models\Career;
use App\Models\Result;
use App\Models\Statement;
use Illuminate\View\View;
use App\Models\Personality;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function index(): View
    {
        $users = User::count();
        $statements = Statement::count();
        $personalities = Personality::count();
        $rules = Rule::count();
        $results = Result::with('personality')->orderBy('created_at', 'desc')->get();

        return view('employee.pages.dashboard.statistic', compact('users', 'statements', 'personalities', 'rules', 'results'));
    }

    public function historyDetail(Result $result): View
    {
        //? Convert String to array
        $personalityNames = unserialize($result->overall_personality);
        $personalityValues = unserialize($result->overall_score);

        //? Get top personality description
        $result = Result::with('personality')->where('id', $result->id)->first();

        if ($result) {
            $topPersonalityId = $result->personality->pluck('id')->first();
        }

        $potentialCareers = Career::with(['personalities', 'departments'])
            ->whereHas('personalities', function ($query) use ($topPersonalityId) {
                $query->where('personalities.id', $topPersonalityId);
            })
            ->whereHas('departments', function ($query) use ($result) {
                $query->where('departments.id', $result->user->student->department_id);
            })
            ->get();

        return view('employee.pages.dashboard.history', compact('personalityNames', 'personalityValues', 'result', 'potentialCareers'));
    }
}
