<?php

namespace App\Repositories;

use App\Models\DuitkuSettings;
use App\Models\IpaymuSettings;
use App\Models\PakasirSettings;
use App\Models\TripaySettings;

final class PaymentSettingsRepository
{
    private ?IpaymuSettings $ipaymu = null;
    private ?DuitkuSettings $duitku = null;
    private ?TripaySettings $tripay = null;
    private ?PakasirSettings $pakasir = null;

    public function ipaymu(): ?IpaymuSettings
    {
        return $this->ipaymu ??= IpaymuSettings::first();
    }

    public function duitku(): ?DuitkuSettings
    {
        return $this->duitku ??= DuitkuSettings::first();
    }

    public function tripay(): ?TripaySettings
    {
        return $this->tripay ??= TripaySettings::first();
    }

    public function pakasir(): ?PakasirSettings
    {
        return $this->pakasir ??= PakasirSettings::first();
    }

    public function getActiveGoldRate(): int
    {
        $ipaymu = $this->ipaymu();
        if ($ipaymu && $ipaymu->is_active && $ipaymu->gold_rate) {
            return $ipaymu->gold_rate;
        }

        $duitku = $this->duitku();
        if ($duitku && $duitku->is_active && $duitku->gold_rate) {
            return $duitku->gold_rate;
        }

        $tripay = $this->tripay();
        if ($tripay && $tripay->is_active && $tripay->gold_rate) {
            return $tripay->gold_rate;
        }

        $pakasir = $this->pakasir();
        if ($pakasir && $pakasir->is_active && $pakasir->gold_rate) {
            return $pakasir->gold_rate;
        }

        return 1000; // default
    }

    public function hasAnyActive(): bool
    {
        return $this->isActive($this->ipaymu())
            || $this->isActive($this->duitku())
            || $this->isActive($this->tripay())
            || $this->isActive($this->pakasir());
    }

    public function getActiveGateways(): array
    {
        $gateways = [];

        if ($this->isActive($this->ipaymu())) {
            $gateways[] = 'ipaymu';
        }
        if ($this->isActive($this->duitku())) {
            $gateways[] = 'duitku';
        }
        if ($this->isActive($this->tripay())) {
            $gateways[] = 'tripay';
        }
        if ($this->isActive($this->pakasir())) {
            $gateways[] = 'pakasir';
        }

        return $gateways;
    }

    private function isActive(?object $settings): bool
    {
        return $settings && $settings->is_active;
    }
}
