<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $fillable = [
        'emp_id', 'name', 'role', 'department', 'phone', 'email',
        'status', 'join_date', 'target', 'avatar_color', 'notes'
    ];

    protected $casts = [
        'join_date' => 'date',
    ];

    // leads assigned to this employee
    public function leads()
    {
        return $this->hasMany(Lead::class, 'assigned_to');
    }

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

    public function getWonLeadsCountAttribute()
    {
        return $this->leads()->where('stage', 'Won')->count();
    }

    public function getWinRateAttribute()
    {
        $total = $this->leads()->count();
        if ($total === 0) return 0;
        return round(($this->won_leads_count / $total) * 100);
    }
}
