<?php

namespace App\Models;

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

class ShippingMethod extends Model
{
    protected $table = 'shipping_methods';

    protected $fillable = [
        'name',
        'cost',
        'zone',
        'pricing_type',
        'base_cost',
        'per_kg_rate',
        'max_weight_g',
        'estimated_days',
        'is_active',
    ];

    protected $casts = [
        'cost'          => 'decimal:2',
        'base_cost'     => 'decimal:2',
        'per_kg_rate'   => 'decimal:2',
        'max_weight_g'  => 'integer',
        'estimated_days'=> 'integer',
        'is_active'     => 'boolean',
    ];

    /**
     * Orders that used this shipping method.
     */
    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    /**
     * Calculate shipping cost for a given total weight (in grams).
     *
     * Flat rate  → returns `cost` regardless of weight.
     * Weight-based → base_cost + (weight_kg × per_kg_rate), rounded to 2 decimal places.
     */
    public function calculateCost(int $totalWeightGrams = 0): float
    {
        if ($this->pricing_type === 'weight_based') {
            $base    = (float) ($this->base_cost   ?? 0);
            $perKg   = (float) ($this->per_kg_rate ?? 0);
            $weightKg = $totalWeightGrams / 1000;

            return round($base + ($weightKg * $perKg), 2);
        }

        // Default: flat rate
        return (float) ($this->cost ?? 0);
    }

    /**
     * Human-readable label for dropdowns.
     * e.g. "Steadfast — Inside Dhaka (Flat ৳80)"
     */
    public function getDropdownLabelAttribute(): string
    {
        $zone = match($this->zone) {
            'inside_dhaka'  => 'Inside Dhaka',
            'outside_dhaka' => 'Outside Dhaka',
            default         => ucfirst($this->zone),
        };

        if ($this->pricing_type === 'weight_based') {
            $rate = '৳' . number_format((float)$this->base_cost, 0) . ' base + ৳' . number_format((float)$this->per_kg_rate, 0) . '/kg';
            return "{$this->name} — {$zone} (Weight-based, {$rate})";
        }

        return "{$this->name} — {$zone} (Flat ৳" . number_format((float)$this->cost, 0) . ")";
    }

    /**
     * Check whether a given weight (grams) is within this method's limit.
     */
    public function supportsWeight(int $weightGrams): bool
    {
        if ($this->max_weight_g === null) {
            return true;
        }

        return $weightGrams <= $this->max_weight_g;
    }
}
