<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;

class Vehicle extends Model
{
    use HasFactory;

    protected $fillable = [
        'stock_number',
        'slug',
        'make',
        'model',
        'variant',
        'year',
        'registration_year',
        'chassis_number',
        'engine_number',
        'engine_cc',
        'fuel_type',
        'transmission',
        'drive_type',
        'body_type',
        'color',
        'mileage',
        'auction_grade',
        'interior_grade',
        'exterior_grade',
        'purchase_price_jpy',
        'reconditioning_cost_bdt',
        'customs_duty_bdt',
        'registration_cost_bdt',
        'other_charges_bdt',
        'selling_price_bdt',
        'discount_bdt',
        'final_price_bdt',
        'main_image',
        'gallery',
        'interior_photos',
        'exterior_photos',
        'engine_photos',
        'tyre_photos',
        'auction_sheet_url',
        'inspection_report_url',
        'video_url',
        'status',
        'is_featured',
        'is_new_arrival',
        'description',
        'features_list',
        'views_count',
    ];

    protected function casts(): array
    {
        return [
            'gallery' => 'array',
            'interior_photos' => 'array',
            'exterior_photos' => 'array',
            'engine_photos' => 'array',
            'tyre_photos' => 'array',
            'features_list' => 'array',
            'is_featured' => 'boolean',
            'is_new_arrival' => 'boolean',
            'selling_price_bdt' => 'decimal:2',
            'final_price_bdt' => 'decimal:2',
            'year' => 'integer',
            'mileage' => 'integer',
            'engine_cc' => 'integer',
        ];
    }

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

    public function watchlists(): HasMany
    {
        return $this->hasMany(Watchlist::class);
    }

    // Scopes
    public function scopeAvailable(Builder $query): Builder
    {
        return $query->where('status', 'available');
    }

    public function scopeFeatured(Builder $query): Builder
    {
        return $query->where('is_featured', true);
    }

    public function scopeNewArrival(Builder $query): Builder
    {
        return $query->where('is_new_arrival', true);
    }

    // Helpers
    public function getFormattedPriceAttribute(): string
    {
        return '৳' . number_format($this->final_price_bdt, 0);
    }

    public function getFormattedMileageAttribute(): string
    {
        return number_format($this->mileage) . ' km';
    }

    public function getFullNameAttribute(): string
    {
        return "{$this->year} {$this->make} {$this->model}" . ($this->variant ? " {$this->variant}" : "");
    }
}
