<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Payment\Filament\Pages;

use App\Models\Setting;
use Filament\Actions\Action;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Schema;

class PaymentSettings extends Page
{
    use InteractsWithForms;

    protected static \UnitEnum|string|null $navigationGroup = '插件';

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-credit-card';

    protected static ?string $navigationLabel = '支付设置';

    protected string $view = 'filament.pages.plugin-settings';

    public array $data = [];

    public function mount(): void
    {
        $this->form->fill([
            'pay_sandbox' => (int) Setting::get('pay_sandbox', 1) === 1,
            'pay_alipay_app_id' => Setting::get('pay_alipay_app_id', ''),
            'pay_alipay_app_secret' => Setting::get('pay_alipay_app_secret', ''),
            'pay_wechat_app_id' => Setting::get('pay_wechat_app_id', ''),
            'pay_wechat_mch_id' => Setting::get('pay_wechat_mch_id', ''),
            'pay_wechat_mch_secret' => Setting::get('pay_wechat_mch_secret', ''),
        ]);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('通用')
                    ->schema([
                        Toggle::make('pay_sandbox')->label('沙箱模式（无需真实密钥即可测试支付流程）')->default(true),
                    ]),
                Section::make('支付宝')
                    ->columns(2)
                    ->schema([
                        TextInput::make('pay_alipay_app_id')->label('App ID')->columnSpanFull(),
                        TextInput::make('pay_alipay_app_secret')->label('应用私钥（app_secret_cert）')->password()->columnSpanFull(),
                    ]),
                Section::make('微信支付')
                    ->columns(2)
                    ->schema([
                        TextInput::make('pay_wechat_app_id')->label('App ID'),
                        TextInput::make('pay_wechat_mch_id')->label('商户号 MCH ID'),
                        TextInput::make('pay_wechat_mch_secret')->label('API 密钥')->password()->columnSpanFull(),
                    ]),
            ])
            ->statePath('data');
    }

    public function save(): void
    {
        $data = $this->form->getState();

        foreach ($data as $key => $value) {
            Setting::set($key, is_bool($value) ? (string) (int) $value : (string) $value);
        }

        Notification::make()->title('支付设置已保存')->success()->send();
    }

    protected function getFormActions(): array
    {
        return [
            Action::make('save')->label('保存')->submit('save'),
        ];
    }
}
