<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DeliveryInfo extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'title',
        'icon',
        'items',
        'is_active',
        'is_global',
        'order',
    ];

    protected $casts = [
        'items' => 'array',
        'is_active' => 'boolean',
        'is_global' => 'boolean',
    ];

    // Relationships
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeGlobal($query)
    {
        return $query->where('is_global', true)->whereNull('product_id');
    }

    public function scopeForProduct($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order');
    }

    // Helper method to get delivery info for a product
    public static function getForProduct($productId)
    {
        // First, check if product has specific delivery info
        $productInfo = self::active()
            ->forProduct($productId)
            ->ordered()
            ->get();

        if ($productInfo->isNotEmpty()) {
            return $productInfo;
        }

        // Otherwise, return global delivery info
        return self::active()
            ->global()
            ->ordered()
            ->get();
    }
}
