<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Vehicle extends Model
{
    use \Illuminate\Database\Eloquent\Concerns\HasUuids, \Illuminate\Database\Eloquent\Factories\HasFactory, SoftDeletes;

    protected $fillable = [
        'make', 'model', 'year', 'price', 'stock_number', 'stock_quantity',
        'vin', 'description', 'category', 'fuel_type', 'transmission',
        'mileage', 'color', 'status', 'featured', 'branch_id', 'features',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'year' => 'integer',
        'stock_quantity' => 'integer',
        'mileage' => 'integer',
        'featured' => 'boolean',
        'features' => 'array',
    ];

    public function images()
    {
        return $this->hasMany(VehicleImage::class);
    }

    public function specifications()
    {
        return $this->hasMany(VehicleSpecification::class);
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function pricing()
    {
        return $this->hasOne(VehiclePricing::class);
    }

    public function testDriveBookings()
    {
        return $this->hasMany(TestDriveBooking::class);
    }

    public function serviceBookings()
    {
        return $this->hasMany(ServiceBooking::class);
    }

    public function getMainImageUrlAttribute()
    {
        // Try to find a primary image first
        $primaryImage = $this->images->where('is_primary', true)->first();

        if ($primaryImage) {
            return $primaryImage->image_url;
        }

        // Fallback to first image
        $firstImage = $this->images->first();
        if ($firstImage) {
            return $firstImage->image_url;
        }

        // Fallback placeholder
        return '/assets/images/placeholder-car.jpg';
    }
}
