<?php

namespace App\Filament\Pages;

use App\Models\Setting;
use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Schemas\Components\Grid;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Actions\Contracts\HasActions;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Notifications\Notification;
use Filament\Actions\Action;

class ManageSettings extends Page implements HasForms, HasActions
{
    use InteractsWithForms, InteractsWithActions;

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth';

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

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

    protected static ?string $title = 'Store Settings';

    protected static ?int $navigationSort = 3;

    public ?array $data = [];

    public function mount()
    {
        // Hydrate the form with settings from the database
        $settings = Setting::pluck('value', 'key')->toArray();
        if (!isset($settings['active_storage_disk'])) {
            $settings['active_storage_disk'] = 'public';
        }
        if (!isset($settings['currency_symbol'])) {
            $settings['currency_symbol'] = '৳';
        }
        if (!isset($settings['default_courier'])) {
            $settings['default_courier'] = 'steadfast';
        }
        $this->form->fill($settings);
    }

    public function form(Schema $form): Schema
    {
        return $form
            ->schema([
                Tabs::make('Settings Tabs')
                    ->persistTabInQueryString()
                    ->vertical()
                    ->tabs([
                        // Tab 2: Courier Configuration
                        Tabs\Tab::make('Courier Logistics')
                            ->icon('heroicon-o-truck')
                            ->schema([
                                Hidden::make('default_courier'),

                                Section::make('📦 Steadfast Courier Integration')
                                    ->schema([
                                        Toggle::make('steadfast_enabled')
                                            ->label('Enable Steadfast Courier')
                                            ->default(false)
                                            ->live(),
                                        Grid::make(2)
                                            ->schema([
                                                TextInput::make('steadfast_api_key')
                                                    ->label('API Key')
                                                    ->password()
                                                    ->required(fn ($get) => $get('steadfast_enabled')),
                                                TextInput::make('steadfast_secret_key')
                                                    ->label('Secret Key')
                                                    ->password()
                                                    ->required(fn ($get) => $get('steadfast_enabled')),
                                                \Filament\Schemas\Components\Actions::make([
                                                    \Filament\Actions\Action::make('set_steadfast_default')
                                                        ->label(fn ($get) => $get('default_courier') === 'steadfast' ? '⭐ Current Default (Click to Unset)' : 'Set as Default')
                                                        ->color(fn ($get) => $get('default_courier') === 'steadfast' ? 'success' : 'gray')
                                                        ->action(function ($set, $get) {
                                                            if ($get('default_courier') === 'steadfast') {
                                                                $set('default_courier', null);
                                                                Notification::make()
                                                                    ->title('Default Courier Unset')
                                                                    ->body('Default courier unset. Click Save Courier Settings to persist.')
                                                                    ->success()
                                                                    ->send();
                                                            } else {
                                                                $set('default_courier', 'steadfast');
                                                                Notification::make()
                                                                    ->title('Default Courier Changed')
                                                                    ->body('Steadfast has been set as default. Click Save Courier Settings to persist.')
                                                                    ->success()
                                                                    ->send();
                                                            }
                                                        }),
                                                    \Filament\Actions\Action::make('test_steadfast')
                                                        ->label('⚡ Test Steadfast Connection')
                                                        ->color('warning')
                                                        ->action('testSteadfastConnection'),
                                                ])->columnSpanFull(),
                                            ])
                                            ->visible(fn ($get) => $get('steadfast_enabled')),
                                    ]),

                                Section::make('🚴 Pathao Courier Integration')
                                    ->schema([
                                        Toggle::make('pathao_enabled')
                                            ->label('Enable Pathao Courier')
                                            ->default(false)
                                            ->live(),
                                        Grid::make(2)
                                            ->schema([
                                                TextInput::make('pathao_client_id')
                                                    ->label('Client ID')
                                                    ->required(fn ($get) => $get('pathao_enabled')),
                                                TextInput::make('pathao_client_secret')
                                                    ->label('Client Secret')
                                                    ->password()
                                                    ->required(fn ($get) => $get('pathao_enabled')),
                                                TextInput::make('pathao_username')
                                                    ->label('Pathao Username/Email')
                                                    ->required(fn ($get) => $get('pathao_enabled')),
                                                TextInput::make('pathao_password')
                                                    ->label('Pathao Password')
                                                    ->password()
                                                    ->required(fn ($get) => $get('pathao_enabled')),
                                                TextInput::make('pathao_store_id')
                                                    ->label('Sender Store ID')
                                                    ->helperText('Your Pathao sender store ID (e.g. 123456)')
                                                    ->required(fn ($get) => $get('pathao_enabled')),
                                                \Filament\Schemas\Components\Actions::make([
                                                    \Filament\Actions\Action::make('set_pathao_default')
                                                        ->label(fn ($get) => $get('default_courier') === 'pathao' ? '⭐ Current Default (Click to Unset)' : 'Set as Default')
                                                        ->color(fn ($get) => $get('default_courier') === 'pathao' ? 'success' : 'gray')
                                                        ->action(function ($set, $get) {
                                                            if ($get('default_courier') === 'pathao') {
                                                                $set('default_courier', null);
                                                                Notification::make()
                                                                    ->title('Default Courier Unset')
                                                                    ->body('Default courier unset. Click Save Courier Settings to persist.')
                                                                    ->success()
                                                                    ->send();
                                                            } else {
                                                                $set('default_courier', 'pathao');
                                                                Notification::make()
                                                                    ->title('Default Courier Changed')
                                                                    ->body('Pathao has been set as default. Click Save Courier Settings to persist.')
                                                                    ->success()
                                                                    ->send();
                                                            }
                                                        }),
                                                    \Filament\Actions\Action::make('test_pathao')
                                                        ->label('⚡ Test Pathao Connection')
                                                        ->color('warning')
                                                        ->action('testPathaoConnection'),
                                                ])->columnSpanFull(),
                                            ])
                                            ->visible(fn ($get) => $get('pathao_enabled')),
                                    ]),

                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_courier')
                                        ->label('Save Courier Settings')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveCourier'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 3: Payment Gateways
                        Tabs\Tab::make('Payment Gateways')
                            ->icon('heroicon-o-credit-card')
                            ->schema([
                                Section::make('💵 Cash on Delivery Setup')
                                    ->schema([
                                        Toggle::make('cod_enabled')
                                            ->label('Enable Cash on Delivery')
                                            ->default(true)
                                            ->live(),
                                        Textarea::make('cod_instructions')
                                            ->label('Cash on Delivery Instructions')
                                            ->rows(2)
                                            ->default('Pay with cash upon delivery of your products.')
                                            ->visible(fn ($get) => $get('cod_enabled'))
                                            ->columnSpanFull(),
                                    ]),

                                Section::make('🌸 bKash Checkout Integration')
                                    ->schema([
                                        Grid::make(2)
                                            ->schema([
                                                Toggle::make('bkash_enabled')
                                                    ->label('Enable bKash Payment')
                                                    ->default(false)
                                                    ->live(),
                                                Toggle::make('bkash_sandbox')
                                                    ->label('Sandbox / Test Mode')
                                                    ->default(true)
                                                    ->visible(fn ($get) => $get('bkash_enabled')),
                                            ]),
                                        Grid::make(2)
                                            ->schema([
                                                TextInput::make('bkash_username')
                                                    ->label('bKash Username')
                                                    ->required(fn ($get) => $get('bkash_enabled')),
                                                TextInput::make('bkash_password')
                                                    ->label('bKash Password')
                                                    ->password()
                                                    ->required(fn ($get) => $get('bkash_enabled')),
                                                TextInput::make('bkash_app_key')
                                                    ->label('App Key')
                                                    ->password()
                                                    ->required(fn ($get) => $get('bkash_enabled')),
                                                TextInput::make('bkash_app_secret')
                                                    ->label('App Secret')
                                                    ->password()
                                                    ->required(fn ($get) => $get('bkash_enabled')),
                                                \Filament\Schemas\Components\Actions::make([
                                                    \Filament\Actions\Action::make('test_bkash')
                                                        ->label('⚡ Test bKash Connection')
                                                        ->color('warning')
                                                        ->action('testBkashConnection'),
                                                ])->columnSpanFull(),
                                            ])
                                            ->visible(fn ($get) => $get('bkash_enabled')),
                                    ]),

                                Section::make('🔥 Nagad Checkout Integration')
                                    ->schema([
                                        Grid::make(2)
                                            ->schema([
                                                Toggle::make('nagad_enabled')
                                                    ->label('Enable Nagad Payment')
                                                    ->default(false)
                                                    ->live(),
                                                Toggle::make('nagad_sandbox')
                                                    ->label('Sandbox / Test Mode')
                                                    ->default(true)
                                                    ->visible(fn ($get) => $get('nagad_enabled')),
                                            ]),
                                        Grid::make(2)
                                            ->schema([
                                                TextInput::make('nagad_merchant_id')
                                                    ->label('Nagad Merchant ID')
                                                    ->columnSpanFull()
                                                    ->required(fn ($get) => $get('nagad_enabled')),
                                                Textarea::make('nagad_merchant_private_key')
                                                    ->label('Merchant Private Key')
                                                    ->rows(3)
                                                    ->required(fn ($get) => $get('nagad_enabled')),
                                                Textarea::make('nagad_public_key')
                                                    ->label('Nagad Public Key')
                                                    ->rows(3)
                                                    ->required(fn ($get) => $get('nagad_enabled')),
                                                \Filament\Schemas\Components\Actions::make([
                                                    \Filament\Actions\Action::make('test_nagad')
                                                        ->label('⚡ Test Nagad Keys')
                                                        ->color('warning')
                                                        ->action('testNagadKeys'),
                                                ])->columnSpanFull(),
                                            ])
                                            ->visible(fn ($get) => $get('nagad_enabled')),
                                    ]),

                                Section::make('🌐 SSLCommerz Integration')
                                    ->schema([
                                        Grid::make(2)
                                            ->schema([
                                                Toggle::make('sslcommerz_enabled')
                                                    ->label('Enable SSLCommerz Payment')
                                                    ->default(false)
                                                    ->live(),
                                                Toggle::make('sslcommerz_sandbox')
                                                    ->label('Sandbox / Test Mode')
                                                    ->default(true)
                                                    ->visible(fn ($get) => $get('sslcommerz_enabled')),
                                            ]),
                                        Grid::make(2)
                                            ->schema([
                                                TextInput::make('sslcommerz_store_id')
                                                    ->label('Store ID')
                                                    ->required(fn ($get) => $get('sslcommerz_enabled')),
                                                TextInput::make('sslcommerz_store_password')
                                                    ->label('Store Password')
                                                    ->password()
                                                    ->required(fn ($get) => $get('sslcommerz_enabled')),
                                                \Filament\Schemas\Components\Actions::make([
                                                    \Filament\Actions\Action::make('test_ssl')
                                                        ->label('⚡ Test SSLCommerz Connection')
                                                        ->color('warning')
                                                        ->action('testSslcommerzConnection'),
                                                ])->columnSpanFull(),
                                            ])
                                            ->visible(fn ($get) => $get('sslcommerz_enabled')),
                                    ]),

                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_payment')
                                        ->label('Save Payment Gateways')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('savePayment'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 4: SMS Notifications
                        Tabs\Tab::make('SMS & Notifications')
                            ->icon('heroicon-o-chat-bubble-left-right')
                            ->schema([
                                Select::make('default_sms_gateway')
                                    ->label('SMS Gateway')
                                    ->options([
                                        'bulksmsbd' => 'BulkSMSBD',
                                        'greenweb' => 'Greenweb SMS',
                                        'sslwireless' => 'SSL Wireless SMS',
                                    ])
                                    ->default('bulksmsbd')
                                    ->live(),

                                Section::make('Gateway Credentials')
                                    ->schema([
                                        TextInput::make('bulksmsbd_api_key')
                                            ->label('BulkSMSBD API Key')
                                            ->password()
                                            ->visible(fn ($get) => $get('default_sms_gateway') === 'bulksmsbd')
                                            ->required(fn ($get) => $get('default_sms_gateway') === 'bulksmsbd'),
                                        TextInput::make('bulksmsbd_sender_id')
                                            ->label('BulkSMSBD Sender ID (Approved Masking/Non-masking)')
                                            ->visible(fn ($get) => $get('default_sms_gateway') === 'bulksmsbd'),

                                        TextInput::make('greenweb_token')
                                            ->label('Greenweb API Token')
                                            ->password()
                                            ->visible(fn ($get) => $get('default_sms_gateway') === 'greenweb')
                                            ->required(fn ($get) => $get('default_sms_gateway') === 'greenweb')
                                            ->columnSpanFull(),

                                        TextInput::make('sslwireless_token')
                                            ->label('SSL Wireless API Token')
                                            ->password()
                                            ->visible(fn ($get) => $get('default_sms_gateway') === 'sslwireless')
                                            ->required(fn ($get) => $get('default_sms_gateway') === 'sslwireless'),
                                        TextInput::make('sslwireless_sid')
                                            ->label('SSL Wireless SID (Sender ID)')
                                            ->visible(fn ($get) => $get('default_sms_gateway') === 'sslwireless')
                                            ->required(fn ($get) => $get('default_sms_gateway') === 'sslwireless'),
                                    ])
                                    ->columns(2)
                                    ->visible(fn ($get) => in_array($get('default_sms_gateway'), ['bulksmsbd', 'greenweb', 'sslwireless'])),

                                Section::make('Customer Notification Toggles')
                                    ->description('Configure notifications sent to the customer on order events.')
                                    ->schema([
                                        Toggle::make('sms_order_placed_enabled')
                                            ->label('SMS on Order Placed')
                                            ->default(true),
                                        Toggle::make('email_order_placed_enabled')
                                            ->label('Email on Order Placed')
                                            ->default(true),
                                        Toggle::make('sms_order_shipped_enabled')
                                            ->label('SMS on Order Shipped')
                                            ->default(true),
                                        Toggle::make('email_order_shipped_enabled')
                                            ->label('Email on Order Shipped')
                                            ->default(true),
                                        Toggle::make('sms_order_delivered_enabled')
                                            ->label('SMS on Order Delivered')
                                            ->default(true),
                                        Toggle::make('email_order_delivered_enabled')
                                            ->label('Email on Order Delivered')
                                            ->default(true),
                                        Toggle::make('sms_order_cancelled_enabled')
                                            ->label('SMS on Order Cancelled')
                                            ->default(true),
                                        Toggle::make('email_order_cancelled_enabled')
                                            ->label('Email on Order Cancelled')
                                            ->default(true),
                                        Toggle::make('sms_payment_received_enabled')
                                            ->label('SMS on Payment Received')
                                            ->default(true),
                                        Toggle::make('email_payment_received_enabled')
                                            ->label('Email on Payment Received')
                                            ->default(true),
                                    ])->columns(2),

                                Section::make('Admin Alerts')
                                    ->description('Configure notification alerts sent to store administrators on new order arrivals.')
                                    ->schema([
                                        Toggle::make('admin_order_placed_sms_enabled')
                                            ->label('SMS Alert to Admin')
                                            ->default(false),
                                        Toggle::make('admin_order_placed_email_enabled')
                                            ->label('Email Alert to Admin')
                                            ->default(false),
                                        TextInput::make('admin_notification_phone')
                                            ->label('Admin Notification Phone')
                                            ->placeholder('e.g. 017XXXXXXXX'),
                                        TextInput::make('admin_notification_email')
                                            ->label('Admin Notification Email')
                                            ->email()
                                            ->placeholder('e.g. admin@example.com'),
                                    ])->columns(2),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_sms')
                                        ->label('Save Notification Settings')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveSms'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 5: SMS Templates
                        Tabs\Tab::make('SMS Templates')
                            ->icon('heroicon-o-chat-bubble-bottom-center-text')
                            ->schema([
                                Section::make('SMS Message Templates')
                                    ->description('Customize SMS notifications dispatched on order status updates. Supported shortcodes: {order_number}, {customer_name}, {grand_total}, {tracking_code}')
                                    ->schema([
                                        Textarea::make('sms_template_order_placed')
                                            ->label('Order Placed Template')
                                            ->rows(3)
                                            ->default('Dear {customer_name}, your order #{order_number} has been received. Total: ৳{grand_total}. Thank you for shopping with us!'),
                                        Textarea::make('sms_template_order_shipped')
                                            ->label('Order Shipped Template')
                                            ->rows(3)
                                            ->default('Dear {customer_name}, your order #{order_number} has been shipped. Tracking Code: {tracking_code}.'),
                                        Textarea::make('sms_template_order_delivered')
                                            ->label('Order Delivered Template')
                                            ->rows(3)
                                            ->default('Dear {customer_name}, your order #{order_number} has been delivered successfully. Thank you for choosing us!'),
                                        Textarea::make('sms_template_order_cancelled')
                                            ->label('Order Cancelled Template')
                                            ->rows(3)
                                            ->default('Dear {customer_name}, your order #{order_number} has been cancelled. Please contact us for more info.'),
                                        Textarea::make('sms_template_payment_received')
                                            ->label('Payment Received Template')
                                            ->rows(3)
                                            ->default('Dear {customer_name}, we have received your payment of ৳{grand_total} for order #{order_number}. Thank you!'),
                                        Textarea::make('sms_template_admin_order_placed')
                                            ->label('Admin New Order Alert Template')
                                            ->rows(3)
                                            ->default('New order #{order_number} placed by {customer_name}. Total: ৳{grand_total}.'),
                                        Textarea::make('sms_template_login_otp')
                                            ->label('Login / Registration OTP Template')
                                            ->rows(3)
                                            ->helperText('Supported shortcodes: {code}, {site_name}'),
                                        Textarea::make('sms_template_password_reset')
                                            ->label('Password Reset Verification Template')
                                            ->rows(3)
                                            ->helperText('Supported shortcodes: {code}, {site_name}'),
                                    ])->columns(2),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_sms_templates')
                                        ->label('Save SMS Templates')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveSmsTemplates'),
                                ])->columnSpanFull(),
                             ]),

                        // Tab 5.5: Email Templates
                        Tabs\Tab::make('Email Templates')
                            ->icon('heroicon-o-envelope-open')
                            ->schema([
                                Section::make('Email Message Templates')
                                    ->description('Customize the body content of E-mail notifications. Supported shortcodes: {order_number}, {customer_name}, {grand_total}, {site_name}, {courier_name}, {tracking_code}, {tracking_link}, and {product_list} to embed the responsive items table.')
                                    ->schema([
                                        Textarea::make('email_template_order_placed')
                                            ->label('Order Placed Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('This text is sent when a customer places an order.'),
                                        Textarea::make('email_template_order_shipped')
                                            ->label('Order Shipped Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('Sent when the order is marked as shipped.'),
                                        Textarea::make('email_template_order_delivered')
                                            ->label('Order Delivered Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('Sent when the order is marked as delivered.'),
                                        Textarea::make('email_template_order_cancelled')
                                            ->label('Order Cancelled Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('Sent when the order is cancelled.'),
                                        Textarea::make('email_template_payment_received')
                                            ->label('Payment Received Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('Sent when a payment is received successfully.'),
                                        Textarea::make('email_template_admin_order_placed')
                                            ->label('Admin New Order Alert Template')
                                            ->rows(4)
                                            ->placeholder("Hello Admin...")
                                            ->helperText('Email alert sent to the admin email address.'),
                                        Textarea::make('email_template_password_reset')
                                            ->label('Password Reset Verification Template')
                                            ->rows(4)
                                            ->placeholder("Hello {customer_name}...")
                                            ->helperText('Supported shortcodes: {code}, {site_name}'),
                                    ])->columns(2),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_email_templates')
                                        ->label('Save Email Templates')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveEmailTemplates'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 6: Email SMTP
                        Tabs\Tab::make('Email (SMTP)')
                            ->icon('heroicon-o-envelope')
                            ->schema([
                                Section::make('SMTP Server Configuration')
                                    ->description('Enter your SMTP mailer details to enable system emails.')
                                    ->schema([
                                        TextInput::make('smtp_host')
                                            ->label('SMTP Host')
                                            ->placeholder('e.g. smtp.mailtrap.io'),
                                        TextInput::make('smtp_port')
                                            ->label('SMTP Port')
                                            ->numeric()
                                            ->placeholder('e.g. 587'),
                                        TextInput::make('smtp_username')
                                            ->label('SMTP Username'),
                                        TextInput::make('smtp_password')
                                            ->label('SMTP Password')
                                            ->password(),
                                        Select::make('smtp_encryption')
                                            ->label('Encryption')
                                            ->options([
                                                'tls' => 'TLS',
                                                'ssl' => 'SSL',
                                                'none' => 'None',
                                            ])
                                            ->default('tls'),
                                        TextInput::make('smtp_from_address')
                                            ->label('Sender Email Address')
                                            ->email()
                                            ->placeholder('e.g. no-reply@sawdabazar.com'),
                                        TextInput::make('smtp_from_name')
                                            ->label('Sender Name')
                                            ->placeholder('e.g. Sawdabazar'),
                                    ])->columns(2),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_email')
                                        ->label('Save Email SMTP Settings')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveEmail'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 7: Analytics & Custom Scripts
                        Tabs\Tab::make('Marketing Analytics')
                            ->icon('heroicon-o-chart-bar')
                            ->schema([
                                Section::make('Google Tag Manager & Analytics')
                                    ->schema([
                                        TextInput::make('gtm_container_id')
                                            ->label('GTM Container ID')
                                            ->placeholder('e.g. GTM-XXXXXX'),
                                        TextInput::make('google_analytics_id')
                                            ->label('Google Analytics (GA4) Measurement ID')
                                            ->placeholder('e.g. G-XXXXXX'),
                                    ])->columns(2),

                                Section::make('Meta Pixel & Conversions API (CAPI)')
                                    ->schema([
                                        TextInput::make('meta_pixel_id')
                                            ->label('Meta Pixel ID')
                                            ->placeholder('e.g. 1234567890'),
                                        TextInput::make('meta_capi_token')
                                            ->label('Meta CAPI Access Token')
                                            ->password()
                                            ->placeholder('EAAdB...'),
                                        TextInput::make('meta_capi_test_code')
                                            ->label('Meta CAPI Test Event Code')
                                            ->placeholder('e.g. TEST12345')
                                            ->helperText('Fill this only when debugging/testing API payloads.'),
                                    ])->columns(3),

                                Section::make('Custom Scripts injection')
                                    ->schema([
                                        Textarea::make('header_scripts')
                                            ->label('Header Scripts (Inside <head>)')
                                            ->rows(4)
                                            ->placeholder('<script>...</script>'),
                                        Textarea::make('footer_scripts')
                                            ->label('Footer Scripts (Before </body>)')
                                            ->rows(4)
                                            ->placeholder('<script>...</script>'),
                                    ])->columns(2),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_analytics')
                                        ->label('Save Analytics & Scripts')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveAnalytics'),
                                ])->columnSpanFull(),
                            ]),

                        // Tab 9: Storage Settings
                        Tabs\Tab::make('Storage Settings')
                            ->icon('heroicon-o-server')
                            ->schema([
                                Section::make('Active Storage Configuration')
                                    ->description('Choose where your uploaded storefront media assets will be stored.')
                                    ->schema([
                                        Select::make('active_storage_disk')
                                            ->label('Active Storage Location')
                                            ->options([
                                                'public' => '📁 Local Server Disk (Default)',
                                                'r2' => '☁️ Cloudflare R2 Object Storage',
                                            ])
                                            ->default('public')
                                            ->selectablePlaceholder(false)
                                            ->required()
                                            ->live(),
                                    ]),

                                Section::make('Cloudflare R2 Bucket Credentials')
                                    ->description('Enter your Cloudflare R2 API connection keys.')
                                    ->visible(fn ($get) => $get('active_storage_disk') === 'r2')
                                    ->schema([
                                        TextInput::make('r2_access_key_id')
                                            ->label('R2 Access Key ID')
                                            ->placeholder('e.g. 5a1b3c... (copy from API token page)')
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        TextInput::make('r2_secret_access_key')
                                            ->label('R2 Secret Access Key')
                                            ->placeholder('e.g. 7d8e9f... (copy from API token page)')
                                            ->password()
                                            ->revealable()
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        TextInput::make('r2_bucket')
                                            ->label('R2 Bucket Name')
                                            ->placeholder('e.g. sawdabazar-media')
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        TextInput::make('r2_region')
                                            ->label('Region')
                                            ->default('auto')
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        TextInput::make('r2_endpoint')
                                            ->label('R2 S3 Client Endpoint URL')
                                            ->placeholder('e.g. https://<account-id>.r2.cloudflarestorage.com')
                                            ->url()
                                            ->columnSpanFull()
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        TextInput::make('r2_url')
                                            ->label('Custom Subdomain / Media URL')
                                            ->placeholder('e.g. https://media.sawdabazar.com')
                                            ->url()
                                            ->columnSpanFull()
                                            ->helperText('Your connected Cloudflare subdomain where files will be served from.')
                                            ->required(fn ($get) => $get('active_storage_disk') === 'r2'),

                                        \Filament\Forms\Components\Placeholder::make('cors_instructions')
                                            ->label('ℹ️ Cloudflare R2 CORS Requirement')
                                            ->content(new \Illuminate\Support\HtmlString(
                                                'To prevent browsers from blocking your images, make sure to add a CORS policy in your R2 bucket settings in Cloudflare:<br>' .
                                                '<div style="position: relative; margin-top: 8px;">' .
                                                    '<pre id="cors-config-code" style="background-color: #f3f4f6; padding: 12px; padding-right: 80px; border-radius: 6px; font-family: monospace; font-size: 13px; color: #1f2937; border: 1px solid #e5e7eb; overflow-x: auto; margin: 0;">[{"AllowedHeaders":["*"],"AllowedMethods":["GET","HEAD"],"AllowedOrigins":["*"],"ExposeHeaders":[]}]</pre>' .
                                                    '<button type="button" onclick="(function(btn){ var text = document.getElementById(\'cors-config-code\').textContent; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(function(){ btn.innerHTML = \'✅ Copied\'; btn.style.color=\'#047857\'; setTimeout(function(){ btn.innerHTML = \'📋 Copy\'; btn.style.color=\'#374151\'; }, 2000); }); } else { var el = document.createElement(\'textarea\'); el.value = text; el.style.position = \'absolute\'; el.style.left = \'-9999px\'; document.body.appendChild(el); el.select(); document.execCommand(\'copy\'); document.body.removeChild(el); btn.innerHTML = \'✅ Copied\'; btn.style.color=\'#047857\'; setTimeout(function(){ btn.innerHTML = \'📋 Copy\'; btn.style.color=\'#374151\'; }, 2000); } })(this)" style="position: absolute; top: 8px; right: 8px; background-color: #ffffff; border: 1px solid #d1d5db; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 4px; color: #374151; font-weight: 600; outline: none; transition: all 0.15s ease;" onmouseover="this.style.backgroundColor=\'#f9fafb\'" onmouseout="this.style.backgroundColor=\'#ffffff\'">' .
                                                        '📋 Copy' .
                                                    '</button>' .
                                                '</div>'
                                            ))
                                            ->columnSpanFull(),

                                        \Filament\Schemas\Components\Actions::make([
                                            \Filament\Actions\Action::make('sync_to_r2')
                                                ->label('🚀 Sync Local Files to Cloud R2')
                                                ->color('warning')
                                                ->requiresConfirmation()
                                                ->modalHeading('Sync Files to Cloudflare R2')
                                                ->modalDescription('This will copy all files currently in your local public disk (branding, sliders, avatars, settings, etc.) into your R2 bucket. Files already in the bucket will not be overwritten. Do you want to proceed?')
                                                ->action(function () {
                                                    try {
                                                        $localDisk = \Illuminate\Support\Facades\Storage::disk('public');
                                                        $r2Disk = \Illuminate\Support\Facades\Storage::disk('r2');
                                                        
                                                        $files = $localDisk->allFiles();
                                                        $count = 0;
                                                        
                                                        foreach ($files as $file) {
                                                            if (str_starts_with($file, 'branding/')) {
                                                                continue;
                                                            }
                                                            if (!$r2Disk->exists($file)) {
                                                                $r2Disk->put($file, $localDisk->get($file));
                                                                $count++;
                                                            }
                                                        }
                                                        
                                                        Notification::make()
                                                            ->title('Sync Completed Successfully')
                                                            ->body("{$count} new files copied from local public storage to Cloudflare R2.")
                                                            ->success()
                                                            ->send();
                                                            
                                                    } catch (\Exception $e) {
                                                        Notification::make()
                                                            ->title('Sync Failed')
                                                            ->body('Failed to connect to Cloudflare R2: Unable to sync')
                                                            ->danger()
                                                            ->persistent()
                                                            ->send();
                                                    }
                                                }),
                                        ])->columnSpanFull(),
                                        \Filament\Schemas\Components\Actions::make([
                                            \Filament\Actions\Action::make('save_storage')
                                                ->label('Save Storage & Backup Settings')
                                                ->color('primary')
                                                ->icon('heroicon-m-check')
                                                ->action('saveStorage'),
                                        ])->columnSpanFull(),
                                    ])->columns(2),

                                Section::make('Secure Backup Configuration')
                                    ->description('Configure password encryption for database and file backup archives.')
                                    ->schema([
                                        TextInput::make('backup_encryption_password')
                                            ->label('Backup Zip Encryption Password')
                                            ->placeholder('Keep empty to disable encryption')
                                            ->password()
                                            ->revealable()
                                            ->helperText('If set, all future backup zip archives will be encrypted using AES-256 password encryption. Write down this password somewhere safe; you cannot restore backups without it.'),
                                    ]),
                            ]),

                        // Tab 10: Badhonsworld Importer
                        Tabs\Tab::make('Badhonsworld Importer')
                            ->icon('heroicon-o-arrow-down-tray')
                            ->schema([
                                Section::make('Badhonsworld API Credentials')
                                    ->description('Configure authentication keys to retrieve your reseller pricing.')
                                    ->schema([
                                        TextInput::make('badhonsworld_reseller_token')
                                            ->label('Reseller Authorization Token')
                                            ->placeholder('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
                                            ->password()
                                            ->revealable()
                                            ->helperText('Input your reseller auth token from badhonsworld.com to import your custom buy rate (cost price).')
                                            ->columnSpanFull(),
                                    ]),
                                \Filament\Schemas\Components\Actions::make([
                                    \Filament\Actions\Action::make('save_badhonsworld')
                                        ->label('Save Importer Settings')
                                        ->color('primary')
                                        ->icon('heroicon-m-check')
                                        ->action('saveBadhonsworld'),
                                ])->columnSpanFull(),
                            ]),
                    ])->columnSpanFull()
            ])
            ->statePath('data');
    }

    /**
     * Define page header actions for connectivity tests.
     */
    protected function getHeaderActions(): array
    {
        return [
            $this->testSmsAction(),
            $this->testEmailAction(),
            $this->testCourierAction(),
            $this->clearCacheAction(),
        ];
    }

    /**
     * Test SMS gateway configuration.
     */
    public function testSmsAction(): Action
    {
        return Action::make('testSms')
            ->label('Test SMS Connection')
            ->modalHeading('Send Test SMS')
            ->color('info')
            ->icon('heroicon-m-chat-bubble-left-right')
            ->form([
                TextInput::make('phone')
                    ->label('Recipient Phone Number')
                    ->required()
                    ->placeholder('e.g. 017XXXXXXXX'),
                Textarea::make('message')
                    ->label('Test Message')
                    ->required()
                    ->default('Sawdabazar: SMS connection test successful!'),
            ])
            ->action(function (array $data) {
                $response = \App\Services\SmsService::sendSms($data['phone'], $data['message']);
                if ($response['success']) {
                    Notification::make()
                        ->title('SMS Sent Successfully')
                        ->body($response['message'])
                        ->success()
                        ->send();
                } else {
                    Notification::make()
                        ->title('SMS Sending Failed')
                        ->body($response['message'])
                        ->danger()
                        ->send();
                }
            });
    }

    /**
     * Test SMTP configuration.
     */
    public function testEmailAction(): Action
    {
        return Action::make('testEmail')
            ->label('Test Email Connection')
            ->modalHeading('Send Test Email')
            ->color('info')
            ->icon('heroicon-m-envelope')
            ->form([
                TextInput::make('email')
                    ->label('Recipient Email Address')
                    ->required()
                    ->email()
                    ->placeholder('e.g. admin@example.com'),
                TextInput::make('subject')
                    ->label('Subject')
                    ->required()
                    ->default('Sawdabazar: Email SMTP connection test'),
                Textarea::make('message')
                    ->label('Test Message')
                    ->required()
                    ->default('Sawdabazar: SMTP mailer connection test successful!'),
            ])
            ->action(function (array $data) {
                try {
                    \Illuminate\Support\Facades\Mail::raw($data['message'], function ($message) use ($data) {
                        $message->to($data['email'])
                            ->subject($data['subject']);
                    });

                    Notification::make()
                        ->title('Email Sent Successfully')
                        ->body('SMTP connection test mail has been sent.')
                        ->success()
                        ->send();
                } catch (\Exception $e) {
                    Notification::make()
                        ->title('Email Sending Failed')
                        ->body('Error: ' . $e->getMessage())
                        ->danger()
                        ->send();
                }
            });
    }

    /**
     * Test Courier credentials connectivity.
     */
    public function testCourierAction(): Action
    {
        return Action::make('testCourier')
            ->label('Test Courier API')
            ->modalHeading('Verify Courier API Connection')
            ->color('info')
            ->icon('heroicon-m-truck')
            ->form([
                Select::make('courier')
                    ->label('Courier Service to Test')
                    ->options([
                        'steadfast' => 'Steadfast Courier',
                        'pathao' => 'Pathao Courier',
                    ])
                    ->required()
                    ->default(fn () => Setting::getValue('default_courier', 'steadfast')),
            ])
            ->action(function (array $data) {
                $courier = $data['courier'];
                if ($courier === 'steadfast') {
                    $apiKey = Setting::getValue('steadfast_api_key');
                    $secretKey = Setting::getValue('steadfast_secret_key');

                    if (!$apiKey || !$secretKey) {
                        Notification::make()
                            ->title('Credentials Missing')
                            ->body('Steadfast API Key and Secret Key must be saved first.')
                            ->danger()
                            ->send();
                        return;
                    }

                    try {
                        $response = \Illuminate\Support\Facades\Http::withHeaders([
                            'Api-Key' => $apiKey,
                            'Secret-Key' => $secretKey,
                            'Content-Type' => 'application/json',
                        ])->get('https://portal.steadfast.com.bd/api/v1/get_balance');

                        if ($response->successful()) {
                            $result = $response->json();
                            if (isset($result['status']) && $result['status'] == 200) {
                                Notification::make()
                                    ->title('Steadfast Connection Success')
                                    ->body('Verified successfully. Account balance: ৳' . ($result['current_balance'] ?? '0.00'))
                                    ->success()
                                    ->send();
                            } else {
                                Notification::make()
                                    ->title('Steadfast Auth Failed')
                                    ->body($result['message'] ?? 'Invalid credentials.')
                                    ->danger()
                                    ->send();
                            }
                        } else {
                            Notification::make()
                                ->title('Steadfast Connection Failed')
                                ->body('Server responded with code: ' . $response->status())
                                ->danger()
                                ->send();
                        }
                    } catch (\Exception $e) {
                        Notification::make()
                            ->title('Steadfast Error')
                            ->body($e->getMessage())
                            ->danger()
                            ->send();
                    }
                } elseif ($courier === 'pathao') {
                    $clientId = Setting::getValue('pathao_client_id');
                    $clientSecret = Setting::getValue('pathao_client_secret');
                    $username = Setting::getValue('pathao_username');
                    $password = Setting::getValue('pathao_password');

                    if (!$clientId || !$clientSecret || !$username || !$password) {
                        Notification::make()
                            ->title('Credentials Missing')
                            ->body('Pathao Client ID, Secret, Username, and Password must be saved first.')
                            ->danger()
                            ->send();
                        return;
                    }

                    try {
                        $response = \Illuminate\Support\Facades\Http::post('https://api.pathao.com/aladdin/api/v1/issue-token', [
                            'client_id' => $clientId,
                            'client_secret' => $clientSecret,
                            'username' => $username,
                            'password' => $password,
                            'grant_type' => 'password',
                        ]);

                        if ($response->successful()) {
                            Notification::make()
                                ->title('Pathao Connection Success')
                                ->body('Authentication token generated successfully. Connection verified!')
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title('Pathao Auth Failed')
                                ->body($response->json('message') ?? 'Verify your Client ID, Secret, Username, and Password.')
                                ->danger()
                                ->send();
                        }
                    } catch (\Exception $e) {
                        Notification::make()
                            ->title('Pathao Connection Failed')
                            ->body($e->getMessage())
                            ->danger()
                            ->send();
                    }
                }
            });
    }

    /**
     * Clear application settings and system cache.
     */
    public function clearCacheAction(): Action
    {
        return Action::make('clearCache')
            ->label('Clear Cache')
            ->color('danger')
            ->icon('heroicon-m-trash')
            ->requiresConfirmation()
            ->modalHeading('Clear System Cache')
            ->modalDescription('This will clear ALL caches — settings, config, routes, views, and application cache. New file uploads will take effect immediately after this.')
            ->action(function () {
                try {
                    // 1. Clear settings query cache
                    \App\Models\Setting::clearCache();
                    
                    // 2. Clear all Laravel system caches
                    \Illuminate\Support\Facades\Artisan::call('optimize:clear');
                    
                    Notification::make()
                        ->title('Cache Cleared Successfully')
                        ->body('All system caches (config, routes, views, settings) have been cleared. New changes are now active.')
                        ->success()
                        ->send();
                } catch (\Exception $e) {
                    Notification::make()
                        ->title('Failed to Clear Cache')
                        ->body('Error: ' . $e->getMessage())
                        ->danger()
                        ->send();
                }
            });
    }

    protected function getFormActions(): array
    {
        return [];
    }

    /**
     * Helper to save a subset of settings keys.
     */
    protected function saveSettingsSubset(array $keys, string $group, string $successMessage)
    {
        $changedSettings = [];
        $oldSettings = [];

        foreach ($keys as $key) {
            $value = $this->data[$key] ?? null;
            $oldValue = Setting::getValue($key);

            if (is_array($value)) {
                $isChanged = json_encode($oldValue) !== json_encode($value);
            } else {
                $isChanged = (string)$oldValue !== (string)$value;
            }

            if ($isChanged) {
                $oldSettings[$key] = $oldValue;
                $changedSettings[$key] = $value;
            }

            Setting::setValue($key, $value, $group);
        }

        // Log setting adjustments
        if (count($changedSettings) > 0) {
            \App\Services\AuditLogger::log(
                'settings_updated',
                'Updated Settings Group (' . $group . '): ' . implode(', ', array_keys($changedSettings)),
                $oldSettings,
                $changedSettings
            );
        }

        Setting::clearCache();

        Notification::make()
            ->title('Settings Saved')
            ->body($successMessage)
            ->success()
            ->send();
    }

    public function saveCourier()
    {
        $rules = [];
        $messages = [];

        if ($this->data['steadfast_enabled'] ?? false) {
            $rules['data.steadfast_api_key'] = 'required';
            $rules['data.steadfast_secret_key'] = 'required';

            $messages['data.steadfast_api_key.required'] = 'Steadfast API Key is required when Steadfast Courier is enabled.';
            $messages['data.steadfast_secret_key.required'] = 'Steadfast Secret Key is required when Steadfast Courier is enabled.';
        }

        if ($this->data['pathao_enabled'] ?? false) {
            $rules['data.pathao_client_id'] = 'required';
            $rules['data.pathao_client_secret'] = 'required';
            $rules['data.pathao_username'] = 'required';
            $rules['data.pathao_password'] = 'required';
            $rules['data.pathao_store_id'] = 'required';

            $messages['data.pathao_client_id.required'] = 'Pathao Client ID is required when Pathao Courier is enabled.';
            $messages['data.pathao_client_secret.required'] = 'Pathao Client Secret is required when Pathao Courier is enabled.';
            $messages['data.pathao_username.required'] = 'Pathao Username/Email is required when Pathao Courier is enabled.';
            $messages['data.pathao_password.required'] = 'Pathao Password is required when Pathao Courier is enabled.';
            $messages['data.pathao_store_id.required'] = 'Pathao Sender Store ID is required when Pathao Courier is enabled.';
        }

        $this->validate($rules, $messages);

        // Auto-unset default courier if the corresponding courier is disabled
        $defaultCourier = $this->data['default_courier'] ?? null;
        if ($defaultCourier === 'steadfast' && !($this->data['steadfast_enabled'] ?? false)) {
            $this->data['default_courier'] = null;
        }
        if ($defaultCourier === 'pathao' && !($this->data['pathao_enabled'] ?? false)) {
            $this->data['default_courier'] = null;
        }

        $this->saveSettingsSubset(
            [
                'default_courier', 
                'steadfast_enabled', 'steadfast_api_key', 'steadfast_secret_key', 
                'pathao_enabled', 'pathao_client_id', 'pathao_client_secret', 'pathao_username', 'pathao_password', 'pathao_store_id'
            ],
            'courier',
            'Courier logistics configurations updated successfully.'
        );
    }

    public function testSteadfastConnection()
    {
        $apiKey = $this->data['steadfast_api_key'] ?? '';
        $secretKey = $this->data['steadfast_secret_key'] ?? '';

        if (!$apiKey || !$secretKey) {
            Notification::make()
                ->title('Validation Failed')
                ->body('Steadfast API Key and Secret Key must be filled to test.')
                ->warning()
                ->send();
            return;
        }

        try {
            $response = \Illuminate\Support\Facades\Http::withHeaders([
                'Api-Key' => $apiKey,
                'Secret-Key' => $secretKey,
                'Content-Type' => 'application/json',
            ])->get('https://portal.steadfast.com.bd/api/v1/get_balance');

            if ($response->successful()) {
                $result = $response->json();
                if (isset($result['status']) && $result['status'] == 200) {
                    Notification::make()
                        ->title('Steadfast Connection Success')
                        ->body('Verified successfully. Account balance: ৳' . ($result['current_balance'] ?? '0.00'))
                        ->success()
                        ->send();
                } else {
                    Notification::make()
                        ->title('Steadfast Auth Failed')
                        ->body($result['message'] ?? 'Invalid credentials.')
                        ->danger()
                        ->send();
                }
            } else {
                Notification::make()
                    ->title('Steadfast Connection Failed')
                    ->body('Server responded with code: ' . $response->status())
                    ->danger()
                    ->send();
            }
        } catch (\Exception $e) {
            Notification::make()
                ->title('Steadfast Connection Failed')
                ->body($this->cleanErrorMessage($e))
                ->danger()
                ->send();
        }
    }

    public function testPathaoConnection()
    {
        $clientId = $this->data['pathao_client_id'] ?? '';
        $clientSecret = $this->data['pathao_client_secret'] ?? '';
        $username = $this->data['pathao_username'] ?? '';
        $password = $this->data['pathao_password'] ?? '';

        if (!$clientId || !$clientSecret || !$username || !$password) {
            Notification::make()
                ->title('Validation Failed')
                ->body('Pathao Client ID, Secret, Username, and Password must be filled to test.')
                ->warning()
                ->send();
            return;
        }

        try {
            $response = \Illuminate\Support\Facades\Http::post('https://api.pathao.com/aladdin/api/v1/issue-token', [
                'client_id' => $clientId,
                'client_secret' => $clientSecret,
                'username' => $username,
                'password' => $password,
                'grant_type' => 'password',
            ]);

            if ($response->successful()) {
                Notification::make()
                    ->title('Pathao Connection Success')
                    ->body('Authentication token generated successfully. Connection verified!')
                    ->success()
                    ->send();
            } else {
                Notification::make()
                    ->title('Pathao Auth Failed')
                    ->body($response->json('message') ?? 'Verify your Client ID, Secret, Username, and Password.')
                    ->danger()
                    ->send();
            }
        } catch (\Exception $e) {
            Notification::make()
                ->title('Pathao Connection Failed')
                ->body($this->cleanErrorMessage($e))
                ->danger()
                ->send();
        }
    }

    public function savePayment()
    {
        $rules = [];
        $messages = [];

        // Validate bKash credentials if enabled
        if ($this->data['bkash_enabled'] ?? false) {
            $rules['data.bkash_username'] = 'required';
            $rules['data.bkash_password'] = 'required';
            $rules['data.bkash_app_key'] = 'required';
            $rules['data.bkash_app_secret'] = 'required';

            $messages['data.bkash_username.required'] = 'bKash Username is required when bKash Payment is enabled.';
            $messages['data.bkash_password.required'] = 'bKash Password is required when bKash Payment is enabled.';
            $messages['data.bkash_app_key.required'] = 'bKash App Key is required when bKash Payment is enabled.';
            $messages['data.bkash_app_secret.required'] = 'bKash App Secret is required when bKash Payment is enabled.';
        }

        // Validate Nagad credentials if enabled
        if ($this->data['nagad_enabled'] ?? false) {
            $rules['data.nagad_merchant_id'] = 'required';
            $rules['data.nagad_merchant_private_key'] = 'required';
            $rules['data.nagad_public_key'] = 'required';

            $messages['data.nagad_merchant_id.required'] = 'Nagad Merchant ID is required when Nagad Payment is enabled.';
            $messages['data.nagad_merchant_private_key.required'] = 'Nagad Merchant Private Key is required when Nagad Payment is enabled.';
            $messages['data.nagad_public_key.required'] = 'Nagad Public Key is required when Nagad Payment is enabled.';
        }

        // Validate SSLCommerz credentials if enabled
        if ($this->data['sslcommerz_enabled'] ?? false) {
            $rules['data.sslcommerz_store_id'] = 'required';
            $rules['data.sslcommerz_store_password'] = 'required';

            $messages['data.sslcommerz_store_id.required'] = 'SSLCommerz Store ID is required when SSLCommerz Payment is enabled.';
            $messages['data.sslcommerz_store_password.required'] = 'SSLCommerz Store Password is required when SSLCommerz Payment is enabled.';
        }

        if (count($rules) > 0) {
            $this->validate($rules, $messages);
        }

        $this->saveSettingsSubset(
            [
                'cod_enabled', 'cod_instructions', 
                'bkash_enabled', 'bkash_username', 'bkash_password', 'bkash_app_key', 'bkash_app_secret', 'bkash_sandbox',
                'nagad_enabled', 'nagad_merchant_id', 'nagad_merchant_private_key', 'nagad_public_key', 'nagad_sandbox',
                'sslcommerz_enabled', 'sslcommerz_store_id', 'sslcommerz_store_password', 'sslcommerz_sandbox'
            ],
            'payment',
            'Payment gateway credentials updated successfully.'
        );
    }

    public function testBkashConnection()
    {
        $username = $this->data['bkash_username'] ?? '';
        $password = $this->data['bkash_password'] ?? '';
        $appKey = $this->data['bkash_app_key'] ?? '';
        $appSecret = $this->data['bkash_app_secret'] ?? '';
        $isSandbox = $this->data['bkash_sandbox'] ?? true;

        if (!$username || !$password || !$appKey || !$appSecret) {
            Notification::make()
                ->title('Validation Failed')
                ->body('All bKash credentials must be filled to test the connection.')
                ->warning()
                ->send();
            return;
        }

        $url = $isSandbox 
            ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta/tokenized/checkout/token/grant'
            : 'https://tokenized.pay.bka.sh/v1.2.0-beta/tokenized/checkout/token/grant';

        try {
            $response = \Illuminate\Support\Facades\Http::withHeaders([
                'username' => $username,
                'password' => $password,
            ])->post($url, [
                'app_key' => $appKey,
                'app_secret' => $appSecret,
            ]);

            $data = $response->json();

            if (isset($data['id_token'])) {
                Notification::make()
                    ->title('bKash Connection Successful')
                    ->body('Credentials are valid and successfully authenticated with bKash API.')
                    ->success()
                    ->send();
            } else {
                $errMsg = $data['statusMessage'] ?? ($data['errorMessage'] ?? 'Unauthorized or invalid credentials.');
                Notification::make()
                    ->title('bKash Connection Failed')
                    ->body('Gateway Error: ' . $errMsg)
                    ->danger()
                    ->persistent()
                    ->send();
            }
        } catch (\Exception $e) {
            Notification::make()
                ->title('bKash Connection Failed')
                ->body($this->cleanErrorMessage($e))
                ->danger()
                ->persistent()
                ->send();
        }
    }

    public function testNagadKeys()
    {
        $merchantId = $this->data['nagad_merchant_id'] ?? '';
        $privateKey = $this->data['nagad_merchant_private_key'] ?? '';
        $publicKey = $this->data['nagad_public_key'] ?? '';

        if (!$merchantId || !$privateKey || !$publicKey) {
            Notification::make()
                ->title('Validation Failed')
                ->body('Nagad Merchant ID, Private Key, and Public Key must be filled to test.')
                ->warning()
                ->send();
            return;
        }

        if (!str_contains($privateKey, 'BEGIN PRIVATE KEY') && !str_contains($privateKey, 'BEGIN RSA PRIVATE KEY')) {
            Notification::make()
                ->title('Nagad Private Key Invalid')
                ->body('The Private Key does not appear to be in valid PEM format (missing BEGIN PRIVATE KEY boundary).')
                ->danger()
                ->persistent()
                ->send();
            return;
        }

        if (!str_contains($publicKey, 'BEGIN PUBLIC KEY') && !str_contains($publicKey, 'BEGIN RSA PUBLIC KEY')) {
            Notification::make()
                ->title('Nagad Public Key Invalid')
                ->body('The Public Key does not appear to be in valid PEM format (missing BEGIN PUBLIC KEY boundary).')
                ->danger()
                ->persistent()
                ->send();
            return;
        }

        Notification::make()
            ->title('Nagad Configuration Valid')
            ->body('Nagad Merchant ID and RSA keys format are valid.')
            ->success()
            ->send();
    }

    public function testSslcommerzConnection()
    {
        $storeId = $this->data['sslcommerz_store_id'] ?? '';
        $storePassword = $this->data['sslcommerz_store_password'] ?? '';
        $isSandbox = $this->data['sslcommerz_sandbox'] ?? true;

        if (!$storeId || !$storePassword) {
            Notification::make()
                ->title('Validation Failed')
                ->body('SSLCommerz Store ID and Store Password must be filled to test connection.')
                ->warning()
                ->send();
            return;
        }

        $url = $isSandbox
            ? 'https://sandbox.sslcommerz.com/gwprocess/v4/api.php'
            : 'https://securepay.sslcommerz.com/gwprocess/v4/api.php';

        try {
            $response = \Illuminate\Support\Facades\Http::asForm()->post($url, [
                'store_id' => $storeId,
                'store_passwd' => $storePassword,
                'total_amount' => '10',
                'currency' => 'BDT',
                'tran_id' => 'TEST_' . uniqid(),
                'success_url' => url('/'),
                'fail_url' => url('/'),
                'cancel_url' => url('/'),
                'cus_name' => 'Test User',
                'cus_email' => 'test@example.com',
                'cus_phone' => '01711111111',
                'shipping_method' => 'NO',
                'product_name' => 'Test Product',
                'product_category' => 'General',
                'product_profile' => 'general'
            ]);

            $body = $response->body();

            if (str_contains($body, 'FAILED') && (str_contains($body, 'Store Credential') || str_contains($body, 'unauthorized') || str_contains($body, 'Unauthorized'))) {
                Notification::make()
                    ->title('SSLCommerz Connection Failed')
                    ->body('Gateway Error: Invalid Store ID or Store Password.')
                    ->danger()
                    ->persistent()
                    ->send();
            } else if (str_contains($body, 'SUCCESS') || str_contains($body, 'status":"SUCCESS"') || str_contains($body, 'Gateway Page') || str_contains($body, 'desc')) {
                Notification::make()
                    ->title('SSLCommerz Connection Successful')
                    ->body('Credentials are valid and successfully connected to SSLCommerz API.')
                    ->success()
                    ->send();
            } else {
                Notification::make()
                    ->title('SSLCommerz Connection Check')
                    ->body('Gateway response received. Please check store configurations in SSLCommerz panel.')
                    ->info()
                    ->send();
            }
        } catch (\Exception $e) {
            Notification::make()
                ->title('SSLCommerz Connection Failed')
                ->body($this->cleanErrorMessage($e))
                ->danger()
                ->persistent()
                ->send();
        }
    }

    private function cleanErrorMessage(\Exception $e): string
    {
        $msg = $e->getMessage();
        if (str_contains($msg, 'Could not resolve host') || str_contains($msg, 'cURL error 6')) {
            return 'Connection Error: Could not reach the server. Please verify your internet connection or check API credentials settings.';
        }
        if (str_contains($msg, 'Connection timed out') || str_contains($msg, 'cURL error 28') || str_contains($msg, 'timed out')) {
            return 'Connection Error: Connection timed out. Please check your network connection or API settings.';
        }
        if (preg_match('/cURL error \d+:/i', $msg, $matches)) {
            if (preg_match('/cURL error \d+: [^(\n]+/i', $msg, $match)) {
                return trim($match[0]);
            }
            return 'Connection failed: ' . substr($msg, 0, 80) . '...';
        }
        return strlen($msg) > 100 ? substr($msg, 0, 100) . '...' : $msg;
    }

    public function saveSms()
    {
        $this->saveSettingsSubset(
            [
                'default_sms_gateway', 'bulksmsbd_api_key', 'bulksmsbd_sender_id', 'greenweb_token', 'sslwireless_token', 'sslwireless_sid',
                'sms_order_placed_enabled', 'email_order_placed_enabled', 'sms_order_shipped_enabled', 'email_order_shipped_enabled',
                'sms_order_delivered_enabled', 'email_order_delivered_enabled', 'sms_order_cancelled_enabled', 'email_order_cancelled_enabled',
                'sms_payment_received_enabled', 'email_payment_received_enabled', 'admin_order_placed_sms_enabled', 'admin_order_placed_email_enabled',
                'admin_notification_phone', 'admin_notification_email'
            ],
            'sms',
            'SMS & Notification settings updated successfully.'
        );
    }

    public function saveSmsTemplates()
    {
        $this->saveSettingsSubset(
            [
                'sms_template_order_placed', 'sms_template_order_shipped', 'sms_template_order_delivered', 'sms_template_order_cancelled',
                'sms_template_payment_received', 'sms_template_admin_order_placed', 'sms_template_login_otp', 'sms_template_password_reset'
            ],
            'sms',
            'SMS notification templates updated successfully.'
        );
    }

    public function saveEmailTemplates()
    {
        $this->saveSettingsSubset(
            [
                'email_template_order_placed', 'email_template_order_shipped', 'email_template_order_delivered', 'email_template_order_cancelled',
                'email_template_payment_received', 'email_template_admin_order_placed', 'email_template_password_reset'
            ],
            'email',
            'Email notification templates updated successfully.'
        );
    }

    public function saveEmail()
    {
        $this->saveSettingsSubset(
            ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_encryption', 'smtp_from_address', 'smtp_from_name'],
            'email',
            'Email SMTP configuration settings updated successfully.'
        );
    }

    public function saveAnalytics()
    {
        $this->saveSettingsSubset(
            ['gtm_container_id', 'google_analytics_id', 'meta_pixel_id', 'meta_capi_token', 'meta_capi_test_code', 'header_scripts', 'footer_scripts'],
            'analytics',
            'Marketing analytics & custom scripts updated successfully.'
        );
    }

    public function saveStorage()
    {
        $rules = [
            'data.active_storage_disk' => 'required',
        ];
        $messages = [
            'data.active_storage_disk.required' => 'Active Storage Location is required.',
        ];

        if (($this->data['active_storage_disk'] ?? 'public') === 'r2') {
            $rules['data.r2_access_key_id'] = 'required';
            $rules['data.r2_secret_access_key'] = 'required';
            $rules['data.r2_bucket'] = 'required';
            $rules['data.r2_endpoint'] = 'required';
            
            $messages['data.r2_access_key_id.required'] = 'R2 Access Key ID is required.';
            $messages['data.r2_secret_access_key.required'] = 'R2 Secret Access Key is required.';
            $messages['data.r2_bucket.required'] = 'R2 Bucket Name is required.';
            $messages['data.r2_endpoint.required'] = 'R2 S3 Client Endpoint URL is required.';
        }

        $this->validate($rules, $messages);

        $this->saveSettingsSubset(
            ['active_storage_disk', 'r2_access_key_id', 'r2_secret_access_key', 'r2_bucket', 'r2_region', 'r2_endpoint', 'r2_url', 'backup_encryption_password'],
            'storage',
            'Storage and backup configuration updated successfully.'
        );
    }

    public function saveBadhonsworld()
    {
        $this->saveSettingsSubset(
            ['badhonsworld_reseller_token'],
            'badhonsworld',
            'Badhonsworld importer settings updated successfully.'
        );
    }

    /**
     * Fallback default save for full form submission.
     */
    public function save()
    {
        $this->saveCourier();
    }
}
