<?php

namespace App\Services\Dashboard;

use App\Models\User;
use App\Models\UserProfileIntro;

class SelfDashboardService
{
    /**
     * @return array<string, mixed>
     */
    public function buildMeta(User $user, ?UserProfileIntro $intro, int $pendingApprovals): array
    {
        return [
            'greeting' => $this->greeting($user),
            'display_name' => $user->name ?? 'Employee',
            'subtitle' => trim(implode(' · ', array_filter([
                $user->designation?->name,
                $user->department?->name,
                $user->company?->name,
            ]))),
            'profile_completion' => $this->profileCompletionPercent($user, $intro),
            'show_inbox' => $pendingApprovals > 0,
            'quick_links' => $this->quickLinks($user),
        ];
    }

    protected function greeting(User $user): string
    {
        $hour = (int) now()->format('G');
        $name = explode(' ', trim((string) $user->name))[0] ?: 'there';

        $timeGreeting = match (true) {
            $hour < 12 => 'Good morning',
            $hour < 17 => 'Good afternoon',
            default => 'Good evening',
        };

        return $timeGreeting.', '.$name;
    }

    /**
     * @return list<array{label: string, href: string, icon: string}>
     */
    protected function quickLinks(User $user): array
    {
        $links = [
            ['label' => 'Apply leave', 'href' => route('leaves.create'), 'icon' => 'bi-calendar-plus'],
            ['label' => 'My attendance', 'href' => route('attendance.index'), 'icon' => 'bi-clock'],
        ];

        if ($user->canViewOwnPayroll()) {
            $links[] = ['label' => 'My pay', 'href' => route('payroll.index', ['tab' => 'my']), 'icon' => 'bi-cash'];
        }

        if ($user->hasPermission('expenses_create_own') || $user->hasPermission('finance_self_view')) {
            $links[] = ['label' => 'Submit claim', 'href' => route('expenses.create'), 'icon' => 'bi-receipt'];
        }

        return $links;
    }

    public function profileCompletionPercent(User $user, ?UserProfileIntro $intro): int
    {
        $signals = [
            ! empty($user->profile_photo),
            ! empty($user->phone),
            ! empty($user->dob),
            ! empty($user->joining_date),
            ! empty($user->department_id),
            ! empty($user->designation_id),
            ! empty($intro?->about),
            ! empty($intro?->job_love),
            ! empty($intro?->interests_hobbies),
            ! empty($intro?->past_experience),
        ];

        $completed = count(array_filter($signals, fn (bool $value): bool => $value));

        return (int) round(($completed / max(1, count($signals))) * 100);
    }
}
