<?php

namespace Modules\Vrc\Entities;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * A vehicle owned by an ERP customer (App\Contact, referenced by
 * erp_customer_id). Service history is the set of repair orders for this
 * vehicle (added in Phase 4). Ownership transfer just re-points
 * erp_customer_id, so history (which lives on the repair orders) is preserved.
 */
class VrcVehicle extends Model
{
    use SoftDeletes;

    protected $table = 'vrc_vehicles';

    protected $fillable = [
        'business_id', 'erp_customer_id', 'make_id', 'model_id', 'year',
        'plate_number', 'vin', 'engine_number', 'color', 'transmission',
        'fuel_type', 'odometer', 'odometer_unit', 'vehicle_type',
        'registration_expiry', 'insurance_company_id', 'insurance_policy_no',
        'insurance_expiry', 'notes', 'is_active',
    ];

    protected $casts = [
        'is_active'           => 'boolean',
        'year'                => 'integer',
        'odometer'            => 'integer',
        'registration_expiry' => 'date',
        'insurance_expiry'    => 'date',
    ];

    public function make(): BelongsTo
    {
        return $this->belongsTo(VrcVehicleMake::class, 'make_id');
    }

    public function model(): BelongsTo
    {
        return $this->belongsTo(VrcVehicleModel::class, 'model_id');
    }

    /** The owning ERP customer. */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(\App\Contact::class, 'erp_customer_id');
    }

    /** Human label: "Make Model (Year) — PLATE". */
    public function getLabelAttribute(): string
    {
        $parts = array_filter([
            optional($this->make)->name,
            optional($this->model)->name,
            $this->year ? "($this->year)" : null,
        ]);
        $label = trim(implode(' ', $parts));
        return $this->plate_number ? trim($label . ' — ' . $this->plate_number, ' —') : ($label ?: ('#' . $this->id));
    }

    /** Free-text search across plate / VIN / engine number. */
    public function scopeSearch(Builder $q, ?string $term): Builder
    {
        $term = trim((string) $term);
        if ($term === '') {
            return $q;
        }
        $like = '%' . $term . '%';
        return $q->where(function (Builder $w) use ($like) {
            $w->where('plate_number', 'like', $like)
                ->orWhere('vin', 'like', $like)
                ->orWhere('engine_number', 'like', $like);
        });
    }
}
