<?php

namespace App\Models;

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

class ShippingZone extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'cost',
        'delivery_time',
        'is_active',
        'order',
    ];

    protected $casts = [
        'cost' => 'decimal:2',
        'is_active' => 'boolean',
    ];

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

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

    /**
     * Calculate shipping cost for an order amount.
     * Returns 0 if free shipping threshold is met.
     */
    public function calculateShipping(float $orderAmount): float
    {
        $freeThreshold = (float) Setting::get('store_free_shipping_threshold', 0);
        $freeEnabled = Setting::get('store_enable_free_shipping', 'false') === 'true';

        if ($freeEnabled && $freeThreshold > 0 && $orderAmount >= $freeThreshold) {
            return 0;
        }

        return $this->cost;
    }
}
