<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements FilamentUser
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'company_name',
        'email',
        'mobile',
        'plan',
        'role',
        'status',
        'is_admin',
        'password',
    ];

    protected $hidden = ['password', 'remember_token'];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'is_admin' => 'boolean',
            'password' => 'hashed',
        ];
    }

    public function canAccessPanel(Panel $panel): bool
    {
        return match ($panel->getId()) {
            'admin' => $this->isSuperAdmin() && $this->status === 'active',
            'app' => $this->role === 'customer' && $this->status === 'active',
            default => false,
        };
    }

    public function isSuperAdmin(): bool
    {
        return $this->is_admin || $this->role === 'super_admin' || $this->hasRole('super_admin');
    }

    // Legacy/business relations
    public function accounts(): HasMany { return $this->hasMany(Account::class); }
    public function categories(): HasMany { return $this->hasMany(Category::class); }
    public function followUps(): HasMany { return $this->hasMany(FollowUp::class); }
    public function transactions(): HasMany { return $this->hasMany(Transaction::class); }
    public function notifications(): HasMany { return $this->hasMany(AppNotification::class); }
    public function aiLogs(): HasMany { return $this->hasMany(AiLog::class); }
    public function subscriptions(): HasMany { return $this->hasMany(Subscription::class); }
    public function currentSubscription(): HasOne { return $this->hasOne(Subscription::class)->latestOfMany(); }
    public function usageLogs(): HasMany { return $this->hasMany(UsageLog::class); }
    public function openingBalances(): HasMany { return $this->hasMany(OpeningBalance::class); }
    public function apiTokens(): HasMany { return $this->hasMany(ApiToken::class); }

    // Phase 1 relations
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }

    public function employeeProfile(): HasOne
    {
        return $this->hasOne(EmployeeProfile::class);
    }

    public function activityLogs(): HasMany
    {
        return $this->hasMany(ActivityLog::class);
    }

    public function hasRole(string $slug): bool
    {
        return $this->roles()->where('slug', $slug)->exists();
    }

    public function assignRole(string $slug): void
    {
        $role = Role::where('slug', $slug)->first();
        if ($role && !$this->hasRole($slug)) {
            $this->roles()->attach($role->id);
        }
    }

    public function workloadStats(): array
    {
        $activeTasks = $this->belongsToMany(Task::class, 'task_assignments')
            ->whereHas('status', fn($q) => $q->whereNotIn('slug', ['completed', 'cancelled']))
            ->get();

        $totalEstimatedHours = $activeTasks->sum('estimated_hours');
        
        return [
            'task_count' => $activeTasks->count(),
            'estimated_hours' => $totalEstimatedHours,
            'is_overloaded' => $totalEstimatedHours > 40,
        ];
    }

    public function availabilityPercent(): int
    {
        $stats = $this->workloadStats();
        $baseCapacity = 40; // 40 hours per week
        $remaining = max(0, $baseCapacity - $stats['estimated_hours']);
        
        return (int) (($remaining / $baseCapacity) * 100);
    }
}
