<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles, SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'employee_id',
        'supervisor_id',
        'department_id',
        'status',
        'address',
        'hire_date',
        'avatar'
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'hire_date' => 'date',
    ];

    protected $appends = [
        'avatar_url',
        'full_employee_id',
        'is_on_visit',
        'current_location'
    ];

    // Relationships
    public function supervisor()
    {
        return $this->belongsTo(User::class, 'supervisor_id');
    }

    public function subordinates()
    {
        return $this->hasMany(User::class, 'supervisor_id');
    }

    public function department()
    {
        return $this->belongsTo(Department::class);
    }

    public function visits()
    {
        return $this->hasMany(Visit::class, 'employee_id');
    }

    public function currentVisit()
    {
        return $this->hasOne(Visit::class, 'employee_id')
                    ->where('status', 'in_progress')
                    ->latestOfMany();
    }

    public function leaveRequests()
    {
        return $this->hasMany(LeaveRequest::class, 'employee_id');
    }

    public function payrolls()
    {
        return $this->hasMany(Payroll::class, 'employee_id');
    }

    public function assignedVisits()
    {
        return $this->hasMany(Visit::class, 'supervisor_id');
    }

    // Helper methods for role checking - FIXED
    public function isAdmin()
    {
        return $this->hasRole('admin');
    }

    public function isSupervisor()
    {
        return $this->hasRole('supervisor');
    }

    public function isEmployee()
    {
        return $this->hasRole('employee');
    }

    // Scope for active employees
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    // Scope for employees only (not admins/supervisors)
    public function scopeEmployees($query)
    {
        return $query->whereHas('roles', function($q) {
            $q->where('name', 'employee');
        });
    }

    // Get avatar URL (fallback to initials)
    public function getAvatarUrlAttribute()
    {
        if ($this->avatar && file_exists(storage_path('app/public/' . $this->avatar))) {
            return asset('storage/' . $this->avatar);
        }
        
        // Generate initials avatar
        $name = $this->name;
        $words = explode(' ', $name);
        $initials = '';
        
        foreach ($words as $word) {
            if (!empty($word)) {
                $initials .= strtoupper(substr($word, 0, 1));
                if (strlen($initials) >= 2) break;
            }
        }
        
        if (empty($initials)) {
            $initials = substr(strtoupper($this->email), 0, 2);
        }
        
        return 'https://ui-avatars.com/api/?name=' . urlencode($initials) . '&color=fff&background=3b82f6';
    }

    // Get full employee ID with prefix
    public function getFullEmployeeIdAttribute()
    {
        $departmentCode = $this->department ? strtoupper(substr($this->department->name, 0, 3)) : 'EMP';
        return $departmentCode . '-' . str_pad($this->employee_id, 5, '0', STR_PAD_LEFT);
    }

    // Check if user is currently on a visit
    public function getIsOnVisitAttribute()
    {
        return $this->currentVisit()->exists();
    }

    // Get current location if on visit
    public function getCurrentLocationAttribute()
    {
        $visit = $this->currentVisit;
        if ($visit && $visit->current_address) {
            return [
                'address' => $visit->current_address,
                'latitude' => $visit->current_latitude,
                'longitude' => $visit->current_longitude,
                'updated_at' => $visit->last_location_update
            ];
        }
        return null;
    }

    // Get role name
    public function getRoleNameAttribute()
    {
        return $this->roles->first()->name ?? 'No Role';
    }

    // Get readable status
    public function getStatusTextAttribute()
    {
        return $this->status === 'active' ? 'Active' : 'Inactive';
    }
}