<?php

namespace App\Models;

use App\Support\PublicStorage;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['key', 'value'])]
class SiteSetting extends Model
{
    public const PRODUCT_FALLBACK_IMAGE = 'product_fallback_image';
    public const CURRENCY_SYMBOL = 'currency_symbol';
    public const CURRENCY_POSITION = 'currency_position';
    public const IBFT_IBAN = 'ibft_iban';
    public const IBFT_ACCOUNT_TITLE = 'ibft_account_title';
    public const IBFT_BANK_NAME = 'ibft_bank_name';
    public const IBFT_ENABLED = 'ibft_enabled';
    public const COD_ENABLED = 'cod_enabled';
    public const SHIPPING_CHARGE = 'shipping_charge';
    public const FREE_SHIPPING_MINIMUM = 'free_shipping_minimum';
    public const ADMIN_ORDER_EMAIL_1 = 'admin_order_email_1';
    public const ADMIN_ORDER_EMAIL_2 = 'admin_order_email_2';
    public const SITEMAP_ENABLED = 'sitemap_enabled';

    public static function value(string $key, ?string $default = null): ?string
    {
        return static::query()->where('key', $key)->value('value') ?? $default;
    }

    public static function put(string $key, ?string $value): self
    {
        return static::query()->updateOrCreate(
            ['key' => $key],
            ['value' => $value]
        );
    }

    public static function productFallbackImageUrl(): string
    {
        $path = static::value(self::PRODUCT_FALLBACK_IMAGE);

        return $path
            ? PublicStorage::url($path)
            : 'https://images.unsplash.com/photo-1556742502-ec7c0e9f34b1?auto=format&fit=crop&w=900&q=80';
    }

    public static function currencySymbol(): string
    {
        return static::value(self::CURRENCY_SYMBOL, 'Rs') ?: 'Rs';
    }

    public static function currencyPosition(): string
    {
        $position = static::value(self::CURRENCY_POSITION, 'left') ?: 'left';

        return in_array($position, ['left', 'right'], true) ? $position : 'left';
    }

    public static function formatPrice(float|int|string $amount): string
    {
        $formattedAmount = number_format((float) $amount);
        $symbol = static::currencySymbol();

        return static::currencyPosition() === 'right'
            ? "{$formattedAmount} {$symbol}"
            : "{$symbol} {$formattedAmount}";
    }

    public static function shippingCharge(): float
    {
        return (float) (static::value(self::SHIPPING_CHARGE, '0') ?: 0);
    }

    public static function freeShippingMinimum(): float
    {
        return (float) (static::value(self::FREE_SHIPPING_MINIMUM, '0') ?: 0);
    }

    public static function calculateShipping(float|int|string $subtotal): float
    {
        $subtotal = (float) $subtotal;
        $minimum = static::freeShippingMinimum();

        if ($minimum > 0 && $subtotal >= $minimum) {
            return 0.0;
        }

        return static::shippingCharge();
    }

    /**
     * @return array<string, string|null>
     */
    public static function ibftSettings(): array
    {
        return [
            'iban' => static::value(self::IBFT_IBAN),
            'account_title' => static::value(self::IBFT_ACCOUNT_TITLE),
            'bank_name' => static::value(self::IBFT_BANK_NAME),
        ];
    }

    /**
     * @return list<string>
     */
    public static function adminOrderEmails(): array
    {
        return collect([
            static::value(self::ADMIN_ORDER_EMAIL_1),
            static::value(self::ADMIN_ORDER_EMAIL_2),
        ])
            ->filter()
            ->map(fn (string $email) => strtolower(trim($email)))
            ->unique()
            ->values()
            ->all();
    }

    public static function sitemapEnabled(): bool
    {
        return static::value(self::SITEMAP_ENABLED, '1') !== '0';
    }

    public static function ibftEnabled(): bool
    {
        return static::value(self::IBFT_ENABLED, '1') !== '0';
    }

    public static function codEnabled(): bool
    {
        return static::value(self::COD_ENABLED, '1') !== '0';
    }

    /**
     * @return array<string, string>
     */
    public static function enabledPaymentMethods(): array
    {
        $methods = [];

        if (static::ibftEnabled()) {
            $methods['ibft'] = 'IBFT Bank Transfer';
        }

        if (static::codEnabled()) {
            $methods['cod'] = 'Cash on Delivery';
        }

        return $methods;
    }
}
