<?php

namespace App\Data;

use App\Models\Setting;

class PaymentGateways
{
    public static function registry(): array
    {
        return [
            'zibal' => [
                'id'               => 'zibal',
                'name'             => 'درگاه پرداخت زیبال',
                'description'      => 'پرداخت آنلاین از طریق درگاه اینترنتی زیبال',
                'admin_icon'       => 'ti-credit-card',
                'checkout_icon'    => 'bi-credit-card-2-back',
                'enabled_key'      => 'zibal_enabled',
                'settings_route'   => 'admin.settings.zibal',
                'display_name_key' => 'zibal_display_name',
                'icon_key'         => 'zibal_icon',
                'is_installment'   => false,
            ],
            'card_to_card' => [
                'id'             => 'card_to_card',
                'name'           => 'پرداخت کارت به کارت',
                'description'    => 'واریز مستقیم به حساب بانکی فروشگاه',
                'admin_icon'     => 'ti-building-bank',
                'checkout_icon'  => 'bi-bank',
                'enabled_key'    => 'card_to_card_enabled',
                'settings_route' => 'admin.settings.card-to-card',
                'is_installment' => false,
            ],
            'torobpay' => [
                'id'               => 'torobpay',
                'name'             => 'پرداخت اقساطی ترب‌پی',
                'description'      => 'پرداخت اقساطی آنلاین از طریق درگاه ترب‌پی',
                'admin_icon'       => 'ti-calendar-dollar',
                'checkout_icon'    => 'bi-calendar2-check',
                'enabled_key'      => 'torobpay_enabled',
                'settings_route'   => 'admin.settings.torobpay',
                'display_name_key' => 'torobpay_display_name',
                'icon_key'         => 'torobpay_icon',
                'is_installment'   => true,
            ],
            'digipay' => [
                'id'               => 'digipay',
                'name'             => 'پرداخت اقساطی دیجی‌پی',
                'description'      => 'پرداخت اقساطی / اعتباری از طریق درگاه یکپارچه دیجی‌پی',
                'admin_icon'       => 'ti-calendar-stats',
                'checkout_icon'    => 'bi-calendar2-week',
                'enabled_key'      => 'digipay_enabled',
                'settings_route'   => 'admin.settings.digipay',
                'display_name_key' => 'digipay_display_name',
                'icon_key'         => 'digipay_icon',
                'is_installment'   => true,
            ],
        ];
    }

    /**
     * All gateways with saved order and checkout_active + is_enabled flags.
     * Used by the admin settings page.
     */
    public static function orderedList(): array
    {
        $registry = self::registry();
        $saved    = json_decode(Setting::get('checkout_payment_methods', '[]'), true) ?? [];
        $savedMap = array_column($saved, null, 'id');

        $orderedIds = array_column($saved, 'id');
        $newIds     = array_diff(array_keys($registry), $orderedIds);
        $finalIds   = array_merge($orderedIds, array_values($newIds));

        $methods = [];
        foreach ($finalIds as $id) {
            if (!isset($registry[$id])) continue;
            $gw = $registry[$id];
            $gw['is_enabled']      = (bool) Setting::get($gw['enabled_key'], false);
            $gw['checkout_active'] = isset($savedMap[$id])
                ? (bool) ($savedMap[$id]['checkout_active'] ?? false)
                : false;
            // Saved override, otherwise registry default
            $gw['is_installment'] = isset($savedMap[$id]['is_installment'])
                ? (bool) $savedMap[$id]['is_installment']
                : (bool) ($gw['is_installment'] ?? false);
            $methods[] = $gw;
        }

        return $methods;
    }

    /**
     * Only gateways that are both checkout_active and enabled in their own settings.
     * Used by the checkout page. Returns extra display data per gateway type.
     */
    public static function activeForCheckout(): array
    {
        $registry = self::registry();
        $saved    = json_decode(Setting::get('checkout_payment_methods', '[]'), true) ?? [];

        $result = [];
        foreach ($saved as $item) {
            $id = $item['id'] ?? null;
            if (!$id || !isset($registry[$id])) continue;
            if (!($item['checkout_active'] ?? false)) continue;

            $gw = $registry[$id];
            if (!Setting::get($gw['enabled_key'], false)) continue;

            $gw['is_installment'] = isset($item['is_installment'])
                ? (bool) $item['is_installment']
                : (bool) ($gw['is_installment'] ?? false);

            // Resolve display name from settings if a key is defined
            if (!empty($gw['display_name_key'])) {
                $customName = Setting::get($gw['display_name_key'], '');
                if ($customName !== '') {
                    $gw['name'] = $customName;
                }
            }

            // Resolve checkout icon image from settings
            if (!empty($gw['icon_key'])) {
                $iconFile = Setting::get($gw['icon_key'], '');
                if ($iconFile !== '' && file_exists(public_path('uploads/payment-icons/' . $iconFile))) {
                    $gw['checkout_logo'] = 'uploads/payment-icons/' . $iconFile;
                }
            }

            // Attach gateway-specific display data
            if ($id === 'card_to_card') {
                $raw = Setting::get('card_to_card_number', '');
                $gw['card_number']    = $raw ? implode('-', str_split($raw, 4)) : '';
                $gw['account_number'] = Setting::get('card_to_card_account', '');
                $gw['holder_name']    = Setting::get('card_to_card_holder_name', '');
                $gw['card_desc']      = Setting::get('card_to_card_description', '');
            }

            $result[] = $gw;
        }

        return $result;
    }

    /**
     * Gateway ids classified as installment / cash based on settings (is_installment).
     *
     * @return list<string>
     */
    public static function gatewayIdsByType(bool $installment): array
    {
        $ids = [];
        foreach (self::orderedList() as $gw) {
            $isInstallment = (bool) ($gw['is_installment'] ?? false);
            if ($isInstallment === $installment) {
                $ids[] = (string) $gw['id'];
            }
        }

        return array_values(array_unique($ids));
    }

    /** @return list<string> */
    public static function cashGatewayIds(): array
    {
        return self::gatewayIdsByType(false);
    }

    /** @return list<string> */
    public static function installmentGatewayIds(): array
    {
        return self::gatewayIdsByType(true);
    }

    /**
     * Enabled installment gateways for product-page promo boxes.
     * Uses is_installment from payment-methods settings (DB), requires gateway enabled.
     *
     * @return array<int, array>
     */
    public static function installmentGateways(): array
    {
        $result = [];

        foreach (self::orderedList() as $gw) {
            if (empty($gw['is_installment']) || empty($gw['is_enabled'])) {
                continue;
            }

            if (!empty($gw['display_name_key'])) {
                $customName = Setting::get($gw['display_name_key'], '');
                if ($customName !== '') {
                    $gw['name'] = $customName;
                }
            }

            $gw['checkout_logo'] = null;
            if (!empty($gw['icon_key'])) {
                $iconFile = Setting::get($gw['icon_key'], '');
                if ($iconFile !== '' && file_exists(public_path('uploads/payment-icons/' . $iconFile))) {
                    $gw['checkout_logo'] = 'uploads/payment-icons/' . $iconFile;
                }
            }

            $result[] = $gw;
        }

        return $result;
    }
}
