<?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;

class Client extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes;

    protected $fillable = [
        'name',
        'company_name',
        'email',
        'phone',
        'position',
        'industry',
        'website',
        'address',
        'notes',
        'status',
        'source',
        'password',
        'is_active',
        'last_login_at',
    ];

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

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

    /* --------- Relationships --------- */

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function meetings()
    {
        return $this->hasMany(Meeting::class);
    }

    public function activeOrders()
    {
        return $this->hasMany(Order::class)
            ->whereIn('status', ['submitted', 'reviewing', 'approved', 'in_progress']);
    }

    /* --------- Scopes --------- */

    public function scopeLeads($q)     { return $q->where('status', 'lead'); }
    public function scopeActive($q)    { return $q->where('status', 'active'); }
    public function scopeProspects($q) { return $q->where('status', 'prospect'); }

    /* --------- Helpers --------- */

    public function statusLabel(): string
    {
        return match ($this->status) {
            'lead'      => 'Шинэ сэжим',
            'prospect'  => 'Болзошгүй',
            'active'    => 'Идэвхтэй',
            'inactive'  => 'Идэвхгүй',
            'archived'  => 'Архивласан',
            default     => $this->status,
        };
    }

    public function statusColor(): string
    {
        return match ($this->status) {
            'lead'      => 'blue',
            'prospect'  => 'yellow',
            'active'    => 'green',
            'inactive'  => 'gray',
            'archived'  => 'red',
            default     => 'gray',
        };
    }

    public function sourceLabel(): string
    {
        return match ($this->source) {
            'website'       => 'Вэб сайт',
            'referral'      => 'Танилцуулга',
            'cold_outreach' => 'Шууд хандалт',
            'social'        => 'Сошиал',
            'event'         => 'Арга хэмжээ',
            'other'         => 'Бусад',
            default         => $this->source,
        };
    }
}
