<?php

use App\Services\Trading\TradingSettingsService;
use App\Traits\Vrm\Livewire\WithNotifications;
use Livewire\Component;

return new class extends Component {
    use WithNotifications;

    public bool $marketOpen = true;

    public string $mpesaWithdrawalMinAmount = '10';

    public string $mpesaWithdrawalMaxAmount = '0';

    public string $bankWithdrawalMinAmount = '10';

    public string $bankWithdrawalMaxAmount = '0';

    public function mount(TradingSettingsService $settings): void
    {
        $this->marketOpen = $settings->isMarketOpen();
        $this->mpesaWithdrawalMinAmount = (string) $settings->withdrawalMinAmount('mpesa');
        $mpesaMax = $settings->withdrawalMaxAmount('mpesa');
        $this->mpesaWithdrawalMaxAmount = $mpesaMax >= PHP_FLOAT_MAX ? '0' : (string) $mpesaMax;

        $this->bankWithdrawalMinAmount = (string) $settings->withdrawalMinAmount('bank');
        $bankMax = $settings->withdrawalMaxAmount('bank');
        $this->bankWithdrawalMaxAmount = $bankMax >= PHP_FLOAT_MAX ? '0' : (string) $bankMax;
    }

    public function save(TradingSettingsService $settings): void
    {
        $validated = $this->validate([
            'marketOpen' => 'required|boolean',
            'mpesaWithdrawalMinAmount' => 'required|numeric|min:10',
            'mpesaWithdrawalMaxAmount' => 'required|numeric|min:0',
            'bankWithdrawalMinAmount' => 'required|numeric|min:10',
            'bankWithdrawalMaxAmount' => 'required|numeric|min:0',
        ]);

        if ((float) $validated['mpesaWithdrawalMaxAmount'] > 0 && (float) $validated['mpesaWithdrawalMaxAmount'] < (float) $validated['mpesaWithdrawalMinAmount']) {
            $this->addError('mpesaWithdrawalMaxAmount', __('M-Pesa withdrawal maximum amount must be greater than or equal to minimum amount.'));

            return;
        }

        if ((float) $validated['bankWithdrawalMaxAmount'] > 0 && (float) $validated['bankWithdrawalMaxAmount'] < (float) $validated['bankWithdrawalMinAmount']) {
            $this->addError('bankWithdrawalMaxAmount', __('Bank withdrawal maximum amount must be greater than or equal to minimum amount.'));

            return;
        }

        $settings->updateSettings(
            (bool) $validated['marketOpen'],
            $settings->investmentDurationDays(),
            $settings->investmentReturnPercent(),
        );
        $settings->updateWithdrawalLimits(
            (float) $validated['mpesaWithdrawalMinAmount'],
            (float) $validated['mpesaWithdrawalMaxAmount'],
            (float) $validated['bankWithdrawalMinAmount'],
            (float) $validated['bankWithdrawalMaxAmount'],
        );

        $this->notifySuccess(__('Settings updated successfully.'));
    }

    protected function view($data = [])
    {
        return app('view')->file('/home1/xxwewbmy/zidii.fxinvest.io/storage/framework/views/livewire/views/35b51e16.blade.php', $data);
    }
}; 