<?php

namespace App\Models;

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

class ShippingZone extends Model
{
    use HasFactory;

    protected $fillable = [
        'zone_code',
        'zone_name',
        'description',
        'province_codes',
        'base_price_per_kg',
        'min_charge_weight',
        'weight_rounding',
        'sort_order',
        'is_active',
    ];

    protected $casts = [
        'province_codes'    => 'array',
        'is_active'         => 'boolean',
        'base_price_per_kg' => 'integer',
        'min_charge_weight' => 'integer',
        'weight_rounding'   => 'integer',
    ];

    // ── Scopes ────────────────────────────────────────────────────────────────

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

    // ── Helpers ───────────────────────────────────────────────────────────────

    /**
     * Cari zona berdasarkan kode provinsi.
     * Mengembalikan zona pertama yang cocok, atau null jika tidak ada.
     */
    public static function findByProvinceCode(string $provinceCode): ?self
    {
        return static::active()->get()->first(function (self $zone) use ($provinceCode) {
            return in_array($provinceCode, $zone->province_codes ?? []);
        });
    }

    /**
     * Hitung berat tagihan setelah dibulatkan ke atas sesuai weight_rounding.
     * Contoh: berat 1200 gram, rounding 1000 → tagih 2000 gram (2 kg).
     */
    public function getChargeableWeight(int $weightGram): int
    {
        $minWeight = $this->min_charge_weight;
        $rounding  = $this->weight_rounding;

        if ($weightGram <= $minWeight) {
            return $minWeight;
        }

        return (int) ceil($weightGram / $rounding) * $rounding;
    }

    /**
     * Hitung harga untuk layanan kurir tertentu.
     * $multiplier berasal dari courier_services di ShippingSettings.
     */
    public function calculatePrice(int $weightGram, float $priceMultiplier = 1.0): int
    {
        $chargeableWeight = $this->getChargeableWeight($weightGram);
        $kg               = $chargeableWeight / 1000;
        $price            = (int) round($this->base_price_per_kg * $kg * $priceMultiplier);

        // Pembulatan ke atas ke ribuan terdekat (tampilan lebih bersih)
        return (int) ceil($price / 1000) * 1000;
    }
}
