<?php

namespace App\Models;

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

class Setting extends Model
{
    protected $fillable = [
        'key',
        'value',
        'group',
    ];

    public static function get(string $key, $default = null)
    {
        return Cache::remember("setting.{$key}", 3600, function () use ($key, $default) {
            $setting = self::where('key', $key)->first();
            return $setting ? $setting->value : $default;
        });
    }

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

    public static function set(string $key, $value, string $group = 'general'): void
    {
        self::updateOrCreate(
            ['key' => $key],
            ['value' => $value, 'group' => $group]
        );

        Cache::forget("setting.{$key}");
    }

    public static function getByGroup(string $group): array
    {
        return self::where('group', $group)
            ->pluck('value', 'key')
            ->toArray();
    }

    public static function getShopName(): string
    {
        return self::get('shop_name', 'POSGRAF Percetakan');
    }

    public static function getShopAddress(): string
    {
        return self::get('shop_address', 'Jl. Contoh No. 123');
    }

    public static function getShopPhone(): string
    {
        return self::get('shop_phone', '08xx-xxxx-xxxx');
    }

    public static function getShopFooter(): string
    {
        return self::get('shop_footer', 'Terima kasih atas kepercayaan Anda');
    }

    public static function getShopLogo(): ?string
    {
        return self::resolveImageUrl(
            self::get('shop_logo'),
            'images/logo-full.jpg'
        );
    }

    public static function getShopLogoIcon(): ?string
    {
        return self::resolveImageUrl(
            self::get('shop_logo_icon'),
            'images/logo-icon.jpg'
        );
    }

    private static function resolveImageUrl($path, string $defaultAsset): string
    {
        $path = trim((string) $path);

        if ($path !== '') {
            if (
                str_starts_with($path, 'http://') ||
                str_starts_with($path, 'https://') ||
                str_starts_with($path, 'data:')
            ) {
                return $path;
            }

            $publicFile = public_path(ltrim($path, '/'));
            if (is_file($publicFile)) {
                return asset(ltrim($path, '/')) . '?v=' . @filemtime($publicFile);
            }

            $storageFile = storage_path('app/public/' . ltrim($path, '/'));
            if (is_file($storageFile)) {
                return asset('storage/' . ltrim($path, '/')) . '?v=' . @filemtime($storageFile);
            }
        }

        $defaultFile = public_path(ltrim($defaultAsset, '/'));
        if (is_file($defaultFile)) {
            return asset(ltrim($defaultAsset, '/')) . '?v=' . @filemtime($defaultFile);
        }

        return asset(ltrim($defaultAsset, '/'));
    }

    /**
     * Template WA siap ambil
     * Placeholder:
     * {nama}, {invoice}, {tanggal}, {total}, {items}
     */
    public static function getWaTemplate(): string
    {
        return self::get(
            'wa_template',
            "Halo Kak *{nama}*,\n\nKami ingin menginformasikan bahwa orderan Kakak sudah *selesai* dan *siap diambil* ya.\n\n*Detail Order:*\n- No. Invoice: *{invoice}*\n- Tanggal Order: {tanggal}\n- Total: {total}\n- Item:\n{items}\n\nDitunggu kedatangannya, terima kasih!"
        );
    }

    public static function getWaTemplatePiutang(): string
    {
        return self::get(
            'wa_template_piutang',
            "- Sisa Pembayaran: Rp {sisa}\n\nMohon untuk dapat melunasi sisa pembayaran saat pengambilan ya Kak."
        );
    }

    /**
     * Build list item WA dari order_items:
     * product_name + material_name (+ size_description) (+ qty kalau ada)
     */
    protected static function buildWaItemsText($order): string
    {
        $itemsRaw =
            data_get($order, 'orderItems') ??
            data_get($order, 'order_items') ??
            data_get($order, 'items') ??
            data_get($order, 'details') ??
            data_get($order, 'orderDetails') ??
            data_get($order, 'order_details') ??
            null;

        $items = collect($itemsRaw);

        if ($items->isEmpty()) {
            return "- (item tidak ditemukan)";
        }

        $lines = $items->map(function ($item) {
            $product = trim((string) (data_get($item, 'product_name') ?? data_get($item, 'product.name') ?? ''));
            $material = trim((string) (data_get($item, 'material_name') ?? data_get($item, 'material.name') ?? ''));

            $name = $product !== '' ? $product : 'Item';
            if ($material !== '') {
                $name .= " — {$material}";
            }

            $sizeDesc = trim((string) (data_get($item, 'size_description') ?? ''));
            if ($sizeDesc !== '') {
                $name .= " ({$sizeDesc})";
            }

            $qty =
                data_get($item, 'qty') ??
                data_get($item, 'quantity') ??
                data_get($item, 'jumlah') ??
                data_get($item, 'pivot.qty') ??
                data_get($item, 'pivot.quantity') ??
                null;

            if ($qty !== null) {
                $qtyInt = (int) $qty;
                if ($qtyInt < 1) {
                    $qtyInt = 1;
                }
                $name .= " x{$qtyInt}";
            }

            return "- {$name}";
        })
        ->filter()
        ->values();

        return $lines->isNotEmpty() ? $lines->implode("\n") : "- (item tidak ditemukan)";
    }

    public static function buildWaMessage($order): string
    {
        $totalPrice = (float) data_get($order, 'total_price', 0);
        $paidAmount = (float) data_get($order, 'paid_amount', 0);
        $isCredit = (bool) data_get($order, 'is_credit', false);

        $remaining = $totalPrice - $paidAmount;
        if ($remaining < 0) {
            $remaining = 0;
        }

        $template = self::getWaTemplate();
        $itemsText = self::buildWaItemsText($order);

        $replacements = [
            '{nama}' => (string) data_get($order, 'customer_name', '-'),
            '{invoice}' => (string) data_get($order, 'invoice_number', '-'),
            '{tanggal}' => optional(data_get($order, 'created_at'))->format('d M Y') ?? '-',
            '{total}' => 'Rp ' . number_format($totalPrice, 0, ',', '.'),
            '{items}' => $itemsText,
        ];

        $message = str_replace(array_keys($replacements), array_values($replacements), $template);

        if ($isCredit && $remaining > 0) {
            $piutangTemplate = self::getWaTemplatePiutang();
            $piutangReplacements = [
                '{sisa}' => number_format($remaining, 0, ',', '.'),
                '{dibayar}' => 'Rp ' . number_format($paidAmount, 0, ',', '.'),
                '{nama}' => (string) data_get($order, 'customer_name', '-'),
                '{invoice}' => (string) data_get($order, 'invoice_number', '-'),
            ];
            $piutangText = str_replace(array_keys($piutangReplacements), array_values($piutangReplacements), $piutangTemplate);
            $message .= "\n" . $piutangText;
        }

        return $message;
    }
}