<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lead extends Model
{
    protected $fillable = [
        'name', 'company', 'phone', 'email', 'source', 'service',
        'budget', 'stage', 'assigned_to', 'priority', 'last_contact'
    ];

    protected $casts = [
        'last_contact' => 'date',
        'budget' => 'integer',
    ];

    public function employee()
    {
        return $this->belongsTo(Employee::class, 'assigned_to');
    }

    public function notes()
    {
        return $this->hasMany(LeadNote::class)->orderByDesc('created_at');
    }

    // budget formatted in Indian Rupees
    public function getBudgetFormattedAttribute()
    {
        if (!$this->budget) return '--';
        return 'Rs' . number_format($this->budget, 0, '.', ',');
    }

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

    // stage badge CSS class
    public static function stageBadge($stage)
    {
        $map = [
            'New'         => 'b-new',
            'Contacted'   => 'b-contacted',
            'Positive'    => 'b-positive',
            'Follow Up'   => 'b-followup',
            'Negotiation' => 'b-negotiation',
            'Won'         => 'b-won',
            'Lost'        => 'b-lost',
        ];
        return $map[$stage] ?? 'b-new';
    }

    public static function sourceBadge($src)
    {
        $map = [
            'Website'    => 'b-website',
            'WhatsApp'   => 'b-whatsapp',
            'Referral'   => 'b-referral',
            'Phone Call' => 'b-call',
            'Email'      => 'b-email',
            'Walk-in'    => 'b-new',
            'LinkedIn'   => 'b-contacted',
        ];
        return $map[$src] ?? 'b-new';
    }

    public static function stageSelectClass($stage)
    {
        $map = [
            'New'         => 's-new',
            'Contacted'   => 's-contacted',
            'Positive'    => 's-positive',
            'Follow Up'   => 's-followup',
            'Negotiation' => 's-negotiation',
            'Won'         => 's-won',
            'Lost'        => 's-lost',
        ];
        return $map[$stage] ?? 's-new';
    }

    public static function priorityColor($pri)
    {
        return ['High' => '#ef4444', 'Medium' => '#f59e0b', 'Low' => '#10b981'][$pri] ?? '#9aa5b4';
    }

    public static function avatarColors()
    {
        return ['#1a73e8','#8b5cf6','#10b981','#f59e0b','#ef4444','#0ea5e9','#f97316','#ec4899'];
    }
}
