<?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\Select;
use Filament\Forms\Components\Textarea;
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_alipay_public_key' => Setting::get('pay_alipay_public_key', ''),
            'pay_alipay_mode' => Setting::get('pay_alipay_mode', 'normal'),
            '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', ''),
            'pay_wechat_mch_cert' => Setting::get('pay_wechat_mch_cert', ''),
            'pay_wechat_platform_cert' => Setting::get('pay_wechat_platform_cert', ''),
            'pay_wechat_mode' => Setting::get('pay_wechat_mode', 'normal'),
        ]);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('通用')
                    ->description('关闭沙箱后才会调用真实支付网关；支付宝/微信各自可选正式环境或官方沙箱环境（需对应环境的凭据）')
                    ->schema([
                        Toggle::make('pay_sandbox')->label('沙箱模式（模拟支付，无需真实密钥即可测试完整流程）')->default(true),
                    ]),
                Section::make('支付宝')
                    ->description('正式/沙箱环境凭据：open.alipay.com → 沙箱环境或控制台，RSA2 密钥生成器获取应用私钥与支付宝公钥')
                    ->columns(2)
                    ->schema([
                        Select::make('pay_alipay_mode')
                            ->label('网关环境')
                            ->options(['normal' => '正式环境', 'sandbox' => '沙箱环境'])
                            ->default('normal'),
                        TextInput::make('pay_alipay_app_id')
                            ->label('App ID')
                            ->placeholder('正式 / 沙箱应用 ID')
                            ->columnSpan(2),
                        Textarea::make('pay_alipay_app_secret')
                            ->label('应用私钥（RSA2 PEM）')
                            ->rows(5)
                            ->helperText('以 -----BEGIN PRIVATE KEY----- 开头')
                            ->columnSpan(2),
                        Textarea::make('pay_alipay_public_key')
                            ->label('支付宝公钥（RSA2 PEM）')
                            ->rows(5)
                            ->helperText('以 -----BEGIN PUBLIC KEY----- 开头；用于回调验签')
                            ->columnSpan(2),
                    ]),
                Section::make('微信支付')
                    ->description('微信商户平台（pay.weixin.qq.com）→ 账户中心 → API 安全：APIv3 密钥、商户 API 证书（apiclient_key.pem）、平台证书')
                    ->columns(2)
                    ->schema([
                        Select::make('pay_wechat_mode')
                            ->label('网关环境')
                            ->options(['normal' => '正式环境', 'sandbox' => '沙箱环境'])
                            ->default('normal'),
                        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('APIv3 密钥')->password()->columnSpan(2),
                        Textarea::make('pay_wechat_mch_cert')
                            ->label('商户 API 证书私钥（apiclient_key.pem）')
                            ->rows(5)
                            ->columnSpan(2),
                        Textarea::make('pay_wechat_platform_cert')
                            ->label('微信支付平台证书（公钥 PEM）')
                            ->rows(5)
                            ->columnSpan(2),
                    ]),
            ])
            ->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'),
        ];
    }
}
