<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = ['name', 'email', 'password', 'role_id', 'avatar', 'phone', 'hourly_rate', 'employee_type', 'is_active'];

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

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

    public function role() { return $this->belongsTo(Role::class); }
    public function consultingJobs() { return $this->hasMany(Job::class, 'consultant_id'); }
    public function managedJobs() { return $this->hasMany(Job::class, 'manager_id'); }
    public function assignedLeads() { return $this->hasMany(Lead::class, 'assigned_to'); }
    public function timeEntries() { return $this->hasMany(\App\Models\TimeEntry::class); }
    public function staffInvoices() { return $this->hasMany(\App\Models\StaffInvoice::class); }

    /**
     * Jobs assigned to this user as a trades worker (pivot: job_trade_assignments).
     */
    public function assignedJobs()
    {
        return $this->belongsToMany(Job::class, 'job_trade_assignments', 'user_id', 'job_id')
                    ->withTimestamps();
    }

    /**
     * Employee task assignments for this factory employee across all jobs.
     */
    public function jobEmployeeTaskAssignments()
    {
        return $this->hasMany(JobEmployeeTaskAssignment::class);
    }

    /**
     * Check if this user's role has a specific permission granted in the DB.
     * Falls back to true when no DB record exists (defer to route-level role checks).
     */
    public function hasPermission(string $key): bool
    {
        if ($this->role?->name === 'office_admin') {
            return true;
        }
        if (!$this->role_id) {
            return false;
        }
        $record = \App\Models\RolePermission::where('role_id', $this->role_id)
            ->where('permission', $key)
            ->first();
        return $record ? (bool) $record->granted : true;
    }

    public function isHourlyRole(): bool
    {
        return in_array($this->role?->name, ['factory_employee', 'processor', 'trades', 'maintenance', 'lead_installer']);
    }

    public function hasRunningTimer(): bool
    {
        return $this->timeEntries()->where('status', 'running')->exists();
    }

    public function getInitialsAttribute(): string
    {
        $parts = explode(' ', $this->name);
        return strtoupper(substr($parts[0], 0, 1) . (isset($parts[1]) ? substr($parts[1], 0, 1) : ''));
    }

    public function getRoleNameAttribute(): string
    {
        return $this->role?->display_name ?? 'Staff';
    }
}
