<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Appointment;   // add this use statement at top of file if not present
use App\Models\FollowUp;

class Lead extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'lead_number', 'contact_id', 'assigned_to', 'status', 'priority', 'source',
        'showroom_id', 'brand_id',
        'designer_id',       // ← ADD THIS
        'booking_date',      // ← ADD THIS
        'preferred_contact', 'enquiry_date', 'follow_up_date', 'project_type',
        'budget_range', 'expected_start', 'description', 'notes', 'internal_notes',
        'site_address', 'site_suburb', 'site_state', 'site_postcode',
    ];

    protected $casts = [
        'enquiry_date' => 'date',
        'follow_up_date' => 'date',
        'expected_start' => 'date',
        'booking_date' => 'date',
    ];

    public function contact() { return $this->belongsTo(Contact::class); }
    public function assignedTo() { return $this->belongsTo(User::class, 'assigned_to'); }
    public function jobs() { return $this->hasMany(Job::class); }
    public function showroom() { return $this->belongsTo(\App\Models\Showroom::class); }
    public function brand() { return $this->belongsTo(\App\Models\Brand::class); }

    public function statusColor(): string
    {
        return match((string)$this->status) {
            'converted' => 'green',
            'new' => 'blue',
            'consult_booked' => 'purple',
            'on_hold' => 'yellow',
            'lost' => 'red',
            'sold' => 'green',
            default => 'gray',
        };
    }

    public function statusLabel(): string
    {
        return match((string)$this->status) {
            'new'            => 'New',
            'consult_booked' => 'Consult Booked',
            'on_hold'        => 'On Hold',
            'lost'           => 'Lost',
            'sold'           => 'Sold',
            'converted'      => 'Converted',
            default          => ucfirst($this->status),
        };
    }

    public function designer(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'designer_id');
    }


    public function brandname(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(\App\Models\Brand::class, 'brand_id');
    }

    public function appointments(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(\App\Models\Appointment::class)->orderBy('appointment_date', 'desc');
    }

    public function followUps(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(\App\Models\FollowUp::class)->orderBy('follow_up_date', 'desc');
    }
}
