<?php

namespace App\Models;

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

/**
 * A lift model from the Odyssey Portal's catalog (table `lift_products`). This is the
 * Product Catalog: proposals price against its variants, and its components are the BOM
 * template for projects. (The older CRM-only `App\Models\Product` / `products` table is
 * no longer used by the catalog.)
 */
class LiftProduct extends Model
{
    use SoftDeletes;

    protected $table = 'lift_products';

    protected $fillable = [
        'product_code', 'elevator_category', 'name', 'type', 'category', 'outer_diameter', 'cabin_diameter',
        'door_clear_access', 'door_opening', 'cabin_height', 'description', 'base_price',
        'capacity', 'floors', 'speed', 'dimensions', 'motor_type', 'drive_power', 'power_phase',
        'horsepower', 'power_consumption', 'door_type', 'car_size', 'travel_height', 'min_headroom',
        'colors', 'safety_features', 'shaft_size', 'machine_room_type', 'drive_type', 'image',
        'status', 'sort_order', 'created_by',
    ];

    protected $casts = [
        'base_price' => 'decimal:2',
        'colors' => 'array',
        'safety_features' => 'array',
        'status' => 'boolean',
        'sort_order' => 'integer',
    ];

    public const ELEVATOR_CATEGORIES = ['home_elevator', 'commercial_elevator'];

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

    /**
     * Products offered in the Proposal Create cascade (category → type → technology →
     * model). Legacy products without an elevator_category are excluded.
     */
    public function scopeCatalog(Builder $query): Builder
    {
        return $query->active()
            ->whereIn('elevator_category', self::ELEVATOR_CATEGORIES)
            ->orderBy('sort_order')
            ->orderBy('name');
    }

    /**
     * The cascade's "technology" level is stored in the existing `category` column
     * (electric, hydraulic, grooved_belt, traction, straight, curved).
     */
    public function getTechnologyAttribute(): ?string
    {
        return $this->category;
    }

    public function isStairlift(): bool
    {
        return $this->type === 'stair_lift';
    }

    public function variants(): HasMany
    {
        return $this->hasMany(LiftProductVariant::class, 'lift_product_id');
    }

    public function components(): HasMany
    {
        return $this->hasMany(ProductComponent::class, 'lift_product_id');
    }

    /**
     * Highest floor configuration among the product's active variants, e.g. "G+3".
     */
    public function getFloorConfigurationAttribute(): ?string
    {
        $stops = $this->variants->where('status', true)->max('number_of_stops');

        return $stops ? 'G+'.($stops - 1) : null;
    }
}
