<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class PassengerExtraServiceItem extends Model
{
    protected $fillable = [
        'passenger_extra_service_id',
        'title',
        'subtitle',
        'image_path',
        'price',
        'discount_percent',
        'sort_order',
        'is_active',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'discount_percent' => 'decimal:2',
        'sort_order' => 'integer',
        'is_active' => 'boolean',
    ];

    public function service(): BelongsTo
    {
        return $this->belongsTo(PassengerExtraService::class, 'passenger_extra_service_id');
    }

    public function finalPrice(): float
    {
        $price = (float) ($this->price ?? 0);
        $discount = max(0.0, min(100.0, (float) ($this->discount_percent ?? 0)));

        return round($price * (1 - ($discount / 100)), 2);
    }

    public function imagePublicUrl(): ?string
    {
        if (empty($this->image_path)) {
            return null;
        }

        if (! Storage::disk('public')->exists($this->image_path)) {
            return null;
        }

        return url('/api/passenger-extra-service-media?path='.rawurlencode($this->image_path));
    }
}

