<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ShippingSetting extends Model
{
    protected $fillable = [
        'shipping_type',
        'flat_rate',
        'governorate_rates',
    ];

    protected function casts(): array
    {
        return [
            'flat_rate' => 'decimal:2',
            'governorate_rates' => 'array',
        ];
    }

    public static function current(): self
    {
        return static::first() ?? new static([
            'shipping_type' => 'flat',
            'flat_rate' => 50,
            'governorate_rates' => null,
        ]);
    }

    public function calculateShippingCost(?string $governorate = null): float
    {
        return match ($this->shipping_type) {
            'free' => 0,
            'flat' => (float) $this->flat_rate,
            'per_governorate' => $this->getGovernorateRate($governorate),
            default => 0,
        };
    }

    protected function getGovernorateRate(?string $governorate): float
    {
        if (! $governorate || ! is_array($this->governorate_rates)) {
            return 0;
        }

        return (float) ($this->governorate_rates[$governorate] ?? 0);
    }
}
