<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class ShippingSetting extends Model
{
    protected $fillable = ['key', 'value', 'label', 'type'];

    // ── Static helpers ────────────────────────────────────────────────────────

    /**
     * Ambil nilai setting berdasarkan key.
     * Cache selama 60 menit untuk performa.
     */
    public static function getValue(string $key, mixed $default = null): mixed
    {
        return Cache::remember("shipping_setting_{$key}", 3600, function () use ($key, $default) {
            $setting = static::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
    }

    /**
     * Set nilai setting, lalu hapus cache.
     */
    public static function setValue(string $key, mixed $value): void
    {
        static::updateOrCreate(['key' => $key], ['value' => $value]);
        Cache::forget("shipping_setting_{$key}");
    }

    /**
     * Cek apakah gratis ongkir aktif.
     */
    public static function isFreeShippingEnabled(): bool
    {
        return (bool) static::getValue('free_shipping_enabled', '1');
    }

    /**
     * Ambil minimum belanja untuk gratis ongkir (dalam rupiah).
     */
    public static function getFreeShippingMinimum(): int
    {
        return (int) static::getValue('free_shipping_minimum', 500000);
    }

    /**
     * Cek apakah subtotal memenuhi syarat gratis ongkir.
     */
    public static function qualifiesForFreeShipping(int $subtotal): bool
    {
        if (!static::isFreeShippingEnabled()) {
            return false;
        }
        return $subtotal >= static::getFreeShippingMinimum();
    }

    /**
     * Ambil berat default produk (gram).
     */
    public static function getDefaultProductWeight(): int
    {
        return (int) static::getValue('default_product_weight', 1000);
    }

    /**
     * Ambil prefix nomor resi.
     */
    public static function getTrackingPrefix(): string
    {
        return strtoupper(static::getValue('tracking_prefix', 'FRN'));
    }

    /**
     * Ambil daftar layanan kurir (array of arrays).
     */
    public static function getCourierServices(): array
    {
        $raw = static::getValue('courier_services', '[]');
        $services = is_array($raw) ? $raw : json_decode($raw, true);
        return is_array($services) ? array_filter($services, fn($s) => $s['is_active'] ?? true) : [];
    }

    /**
     * Ambil detail satu layanan kurir berdasarkan code.
     */
    public static function getCourierByCode(string $code): ?array
    {
        foreach (static::getCourierServices() as $service) {
            if (($service['code'] ?? '') === $code) {
                return $service;
            }
        }
        return null;
    }

    /**
     * Invalidate seluruh cache shipping settings.
     */
    public static function clearCache(): void
    {
        $keys = static::pluck('key');
        foreach ($keys as $key) {
            Cache::forget("shipping_setting_{$key}");
        }
    }
}
