<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\Auditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Deal extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    public const STAGES = [
        'new' => 'Nou',
        'contact' => 'Calculație',
        'agree' => 'Aprobare',
        'scheduled' => 'Programat',
        'arrived' => 'Sosit',
        'in_work' => 'În lucru',
        'done' => 'Finalizat',
        'lost' => 'Pierdut',
    ];

    public const QUOTE_STATUSES = [
        'pending' => 'În așteptare',
        'sent' => 'Trimis · fără răspuns',
        'seen' => 'Văzut ✓',
        'responded' => 'A răspuns',
    ];

    public const CONFIRM_CHANNELS = [
        'whatsapp' => 'WhatsApp',
        'sms' => 'SMS',
        'telegram' => 'Telegram',
        'call' => 'Apel',
    ];

    protected $fillable = [
        'company_id', 'client_id', 'vehicle_id',
        'name', 'price', 'stage', 'source', 'note',
        'assigned_to', 'won_at', 'lost_at', 'lost_reason',
        'urgent', 'quote_sent_at', 'quote_status', 'quote_seen_at',
        'scheduled_at', 'bay', 'confirmed_at', 'confirmed_via',
        'last_action_at',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'won_at' => 'datetime',
        'lost_at' => 'datetime',
        'urgent' => 'boolean',
        'quote_sent_at' => 'datetime',
        'quote_seen_at' => 'datetime',
        'scheduled_at' => 'datetime',
        'confirmed_at' => 'datetime',
        'last_action_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::saving(function (self $deal) {
            $deal->last_action_at = now();
        });
    }

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function vehicle(): BelongsTo
    {
        return $this->belongsTo(Vehicle::class);
    }

    public function assignedTo(): BelongsTo
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    public function isOpen(): bool
    {
        return ! in_array($this->stage, ['done', 'lost'], true);
    }
}
