<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Services\MemberNotificationAutomationService;
use App\Services\PlatformSettings;
use App\Services\TransactionApprovalSettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class SettingController extends Controller
{
    public function edit(PlatformSettings $platformSettings): View
    {
        $tenant = auth()->user()->tenant;

        return view('tenant.settings.index', [
            'tenant' => $tenant,
            'platformMailSettings' => $platformSettings->platformMailSettings(),
            'platformSmsSettings' => $platformSettings->platformSmsSettings(),
            'platformWhatsappSettings' => $platformSettings->platformWhatsappSettings(),
            'platformBillPaymentSettings' => $platformSettings->billPaymentSettings(),
            'platformBillPaymentConfigured' => $platformSettings->billPaymentConfigured(),
            'tenantUsesPlatformMail' => $platformSettings->tenantUsesPlatformMail($tenant),
            'tenantUsesPlatformSms' => $platformSettings->tenantUsesPlatformSms($tenant),
            'tenantUsesPlatformWhatsapp' => $platformSettings->tenantUsesPlatformWhatsapp($tenant),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $tenant = $request->user()->tenant;
        $existingSettings = $tenant->settings ?? [];
        $isSuperAdminTenantPortal = $request->session()->has('impersonating_super_admin_id')
            && filter_var($request->session()->get('can_manage_tenant_communication_gateways'), FILTER_VALIDATE_BOOLEAN);

        if (! $isSuperAdminTenantPortal) {
            $platformSettings = app(PlatformSettings::class);

            $request->merge([
                'sms_use_platform_defaults' => $platformSettings->tenantUsesPlatformSms($tenant) ? '1' : '0',
                'whatsapp_use_platform_defaults' => $platformSettings->tenantUsesPlatformWhatsapp($tenant) ? '1' : '0',
                ...$this->lockedCommunicationSettings($existingSettings, $platformSettings),
            ]);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'public_whatsapp_number' => ['nullable', 'string', 'max:50'],
            'address' => ['nullable', 'string', 'max:1000'],
            'primary_color' => ['required', 'string', 'max:20'],
            'currency' => ['required', 'string', 'max:10'],
            'interest_rate' => ['required', 'numeric', 'min:0'],
            'penalty_rate' => ['required', 'numeric', 'min:0'],
            'logo' => ['nullable', 'image', 'max:2048'],
            'mail_use_platform_defaults' => ['nullable', 'boolean'],
            'mail_mailer' => ['required', 'in:log,smtp'],
            'mail_host' => ['nullable', 'string', 'max:255'],
            'mail_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
            'mail_username' => ['nullable', 'string', 'max:255'],
            'mail_password' => ['nullable', 'string', 'max:255'],
            'mail_scheme' => ['nullable', 'in:tls,ssl,smtps'],
            'mail_verify_peer' => ['nullable', 'boolean'],
            'mail_from_address' => ['nullable', 'email'],
            'mail_from_name' => ['nullable', 'string', 'max:255'],
            'sms_use_platform_defaults' => ['nullable', 'boolean'],
            'sms_driver' => ['required', 'in:log,http,ebulksms'],
            'sms_gateway_url' => ['nullable', 'url', 'max:500'],
            'sms_gateway_method' => ['required', 'in:GET,POST'],
            'sms_gateway_username' => ['nullable', 'string', 'max:255'],
            'sms_gateway_token' => ['nullable', 'string', 'max:1000'],
            'sms_from' => ['nullable', 'string', 'max:100'],
            'sms_to_param' => ['required', 'string', 'max:100'],
            'sms_message_param' => ['required', 'string', 'max:100'],
            'sms_sender_param' => ['required', 'string', 'max:100'],
            'sms_dnd_sender' => ['required', 'in:0,1'],
            'sms_notification_cost_payer' => ['required', 'in:member,tenant'],
            'sms_member_charge' => ['required', 'numeric', 'min:0'],
            'whatsapp_use_platform_defaults' => ['nullable', 'boolean'],
            'whatsapp_driver' => ['required', 'in:log,http,ebulksms'],
            'whatsapp_gateway_url' => ['nullable', 'url', 'max:500'],
            'whatsapp_gateway_method' => ['required', 'in:GET,POST'],
            'whatsapp_gateway_username' => ['nullable', 'string', 'max:255'],
            'whatsapp_gateway_token' => ['nullable', 'string', 'max:1000'],
            'whatsapp_from' => ['nullable', 'string', 'max:100'],
            'whatsapp_to_param' => ['required', 'string', 'max:100'],
            'whatsapp_message_param' => ['required', 'string', 'max:100'],
            'whatsapp_sender_param' => ['required', 'string', 'max:100'],
            'whatsapp_notification_cost_payer' => ['required', 'in:member,tenant'],
            'whatsapp_member_charge' => ['required', 'numeric', 'min:0'],
            'payment_gateway_provider' => ['required', 'in:none,paystack,monnify,flutterwave,providus_bank,wema_bank'],
            'paystack_secret_key' => ['nullable', 'string', 'max:500'],
            'paystack_base_url' => ['nullable', 'url', 'max:500'],
            'paystack_preferred_bank' => ['nullable', 'string', 'max:100'],
            'monnify_api_key' => ['nullable', 'string', 'max:500'],
            'monnify_secret_key' => ['nullable', 'string', 'max:500'],
            'monnify_contract_code' => ['nullable', 'string', 'max:100'],
            'monnify_base_url' => ['nullable', 'url', 'max:500'],
            'flutterwave_secret_key' => ['nullable', 'string', 'max:500'],
            'flutterwave_base_url' => ['nullable', 'url', 'max:500'],
            'providus_client_id' => ['nullable', 'string', 'max:500'],
            'providus_client_secret' => ['nullable', 'string', 'max:500'],
            'providus_base_url' => ['nullable', 'url', 'max:500'],
            'wema_client_id' => ['nullable', 'string', 'max:500'],
            'wema_client_secret' => ['nullable', 'string', 'max:500'],
            'wema_base_url' => ['nullable', 'url', 'max:500'],
            'bill_payment_fee' => ['required', 'numeric', 'min:0'],
            'bill_payment_commission_rate' => ['required', 'numeric', 'min:0', 'max:100'],
            'bill_payment_fee_airtime' => ['nullable', 'numeric', 'min:0'],
            'bill_payment_fee_data' => ['nullable', 'numeric', 'min:0'],
            'bill_payment_fee_electricity' => ['nullable', 'numeric', 'min:0'],
            'bill_payment_fee_cable_tv' => ['nullable', 'numeric', 'min:0'],
            'bill_payment_fee_internet' => ['nullable', 'numeric', 'min:0'],
            'bill_payment_commission_airtime' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'bill_payment_commission_data' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'bill_payment_commission_electricity' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'bill_payment_commission_cable_tv' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'bill_payment_commission_internet' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'account_number_mode' => ['required', 'in:random,prefix_random'],
            'account_number_prefixes' => ['nullable', 'string', 'max:50'],
            'kyc_provider' => ['required', 'in:local,didit'],
            'didit_api_key' => ['nullable', 'string', 'max:1000'],
            'didit_workflow_id' => ['nullable', 'string', 'max:255'],
            'didit_base_url' => ['nullable', 'url', 'max:500'],
            'deposit_approval_required' => ['nullable', 'boolean'],
            'withdrawal_approval_required' => ['nullable', 'boolean'],
            'repayment_approval_required' => ['nullable', 'boolean'],
            'transfer_approval_required' => ['nullable', 'boolean'],
            'member_notification_automations' => ['nullable', 'array'],
            'member_notification_automations.*.enabled' => ['nullable', 'boolean'],
            'member_notification_automations.*.channels' => ['nullable', 'array'],
            'member_notification_automations.*.channels.*' => ['string', 'in:portal,email,sms,whatsapp'],
            'member_notification_automations.*.subject' => ['nullable', 'string', 'max:160'],
            'member_notification_automations.*.body' => ['nullable', 'string', 'max:1000'],
        ]);

        $accountNumberMode = $validated['account_number_mode'];
        $accountNumberPrefixes = $this->normalizeAccountNumberPrefixes($validated['account_number_prefixes'] ?? '');
        $memberNotificationAutomations = MemberNotificationAutomationService::normalizeSettings($validated['member_notification_automations'] ?? []);
        $approvalSettings = app(TransactionApprovalSettings::class)->normalize($validated);
        $usePlatformMail = $request->boolean('mail_use_platform_defaults');
        $mailVerifyPeer = $request->has('mail_verify_peer')
            ? $request->boolean('mail_verify_peer')
            : filter_var($existingSettings['mail_verify_peer'] ?? true, FILTER_VALIDATE_BOOLEAN);
        $usePlatformSms = $request->boolean('sms_use_platform_defaults');
        $usePlatformWhatsapp = $request->boolean('whatsapp_use_platform_defaults');
        $mailPassword = filled($validated['mail_password'] ?? null)
            ? $validated['mail_password']
            : ($existingSettings['mail_password'] ?? null);
        $smsToken = filled($validated['sms_gateway_token'] ?? null)
            ? $validated['sms_gateway_token']
            : ($existingSettings['sms_gateway_token'] ?? null);
        $whatsappToken = filled($validated['whatsapp_gateway_token'] ?? null)
            ? $validated['whatsapp_gateway_token']
            : ($existingSettings['whatsapp_gateway_token'] ?? null);
        $paystackSecret = filled($validated['paystack_secret_key'] ?? null)
            ? $validated['paystack_secret_key']
            : ($existingSettings['paystack_secret_key'] ?? null);
        $monnifyApiKey = filled($validated['monnify_api_key'] ?? null)
            ? $validated['monnify_api_key']
            : ($existingSettings['monnify_api_key'] ?? null);
        $monnifySecretKey = filled($validated['monnify_secret_key'] ?? null)
            ? $validated['monnify_secret_key']
            : ($existingSettings['monnify_secret_key'] ?? null);
        $flutterwaveSecretKey = filled($validated['flutterwave_secret_key'] ?? null)
            ? $validated['flutterwave_secret_key']
            : ($existingSettings['flutterwave_secret_key'] ?? null);
        $providusClientSecret = filled($validated['providus_client_secret'] ?? null)
            ? $validated['providus_client_secret']
            : ($existingSettings['providus_client_secret'] ?? null);
        $wemaClientSecret = filled($validated['wema_client_secret'] ?? null)
            ? $validated['wema_client_secret']
            : ($existingSettings['wema_client_secret'] ?? null);

        if ($accountNumberMode === 'prefix_random' && $accountNumberPrefixes === '') {
            throw ValidationException::withMessages([
                'account_number_prefixes' => 'Enter at least one starting digit, for example 2 or 2,5,7.',
            ]);
        }

        $slug = Str::slug($validated['slug']);

        if ($slug === '') {
            return back()->withErrors(['slug' => 'Enter a valid portal slug.'])->withInput();
        }

        if ($tenant->newQuery()->whereKeyNot($tenant->id)->where(function ($query) use ($slug): void {
            $query->where('slug', $slug)->orWhere('subdomain', $slug);
        })->exists()) {
            return back()->withErrors(['slug' => 'This portal slug is already in use.'])->withInput();
        }

        if ($request->hasFile('logo')) {
            $validated['logo_path'] = $request->file('logo')->store('tenant-logos', 'uploads');
        }

        $tenant->update([
            'name' => $validated['name'],
            'slug' => $slug,
            'subdomain' => $slug,
            'phone' => $validated['phone'] ?? null,
            'address' => $validated['address'] ?? null,
            'primary_color' => $validated['primary_color'],
            'logo_path' => $validated['logo_path'] ?? $tenant->logo_path,
            'settings' => [
                ...($tenant->settings ?? []),
                'currency' => $validated['currency'],
                'public_whatsapp_number' => $validated['public_whatsapp_number'] ?? null,
                'interest_rate' => $validated['interest_rate'],
                'penalty_rate' => $validated['penalty_rate'],
                'mail_use_platform_defaults' => $usePlatformMail,
                'mail_mailer' => $validated['mail_mailer'],
                'mail_host' => $validated['mail_host'] ?? null,
                'mail_port' => $validated['mail_port'] ?? null,
                'mail_username' => $validated['mail_username'] ?? null,
                'mail_password' => $mailPassword,
                'mail_scheme' => $validated['mail_scheme'] ?? null,
                'mail_verify_peer' => $mailVerifyPeer,
                'mail_from_address' => $validated['mail_from_address'] ?? null,
                'mail_from_name' => $validated['mail_from_name'] ?? null,
                'sms_use_platform_defaults' => $usePlatformSms,
                'sms_driver' => $validated['sms_driver'],
                'sms_gateway_url' => $validated['sms_gateway_url'] ?? null,
                'sms_gateway_method' => $validated['sms_gateway_method'],
                'sms_gateway_username' => $validated['sms_gateway_username'] ?? null,
                'sms_gateway_token' => $smsToken,
                'sms_from' => $validated['sms_from'] ?? null,
                'sms_to_param' => $validated['sms_to_param'],
                'sms_message_param' => $validated['sms_message_param'],
                'sms_sender_param' => $validated['sms_sender_param'],
                'sms_dnd_sender' => $validated['sms_dnd_sender'],
                'sms_notification_cost_payer' => $validated['sms_notification_cost_payer'],
                'sms_member_charge' => $validated['sms_member_charge'],
                'whatsapp_use_platform_defaults' => $usePlatformWhatsapp,
                'whatsapp_driver' => $validated['whatsapp_driver'],
                'whatsapp_gateway_url' => $validated['whatsapp_gateway_url'] ?? null,
                'whatsapp_gateway_method' => $validated['whatsapp_gateway_method'],
                'whatsapp_gateway_username' => $validated['whatsapp_gateway_username'] ?? null,
                'whatsapp_gateway_token' => $whatsappToken,
                'whatsapp_from' => $validated['whatsapp_from'] ?? null,
                'whatsapp_to_param' => $validated['whatsapp_to_param'],
                'whatsapp_message_param' => $validated['whatsapp_message_param'],
                'whatsapp_sender_param' => $validated['whatsapp_sender_param'],
                'whatsapp_notification_cost_payer' => $validated['whatsapp_notification_cost_payer'],
                'whatsapp_member_charge' => $validated['whatsapp_member_charge'],
                'payment_gateway_provider' => $validated['payment_gateway_provider'],
                'paystack_secret_key' => $paystackSecret,
                'paystack_base_url' => $validated['paystack_base_url'] ?? 'https://api.paystack.co',
                'paystack_preferred_bank' => $validated['paystack_preferred_bank'] ?? null,
                'monnify_api_key' => $monnifyApiKey,
                'monnify_secret_key' => $monnifySecretKey,
                'monnify_contract_code' => $validated['monnify_contract_code'] ?? null,
                'monnify_base_url' => $validated['monnify_base_url'] ?? 'https://api.monnify.com',
                'flutterwave_secret_key' => $flutterwaveSecretKey,
                'flutterwave_base_url' => $validated['flutterwave_base_url'] ?? 'https://api.flutterwave.com/v3',
                'providus_client_id' => $validated['providus_client_id'] ?? null,
                'providus_client_secret' => $providusClientSecret,
                'providus_base_url' => $validated['providus_base_url'] ?? null,
                'wema_client_id' => $validated['wema_client_id'] ?? null,
                'wema_client_secret' => $wemaClientSecret,
                'wema_base_url' => $validated['wema_base_url'] ?? null,
                'bill_payment_fee' => $validated['bill_payment_fee'],
                'bill_payment_commission_rate' => $validated['bill_payment_commission_rate'],
                'bill_payment_fee_airtime' => $validated['bill_payment_fee_airtime'] ?? null,
                'bill_payment_fee_data' => $validated['bill_payment_fee_data'] ?? null,
                'bill_payment_fee_electricity' => $validated['bill_payment_fee_electricity'] ?? null,
                'bill_payment_fee_cable_tv' => $validated['bill_payment_fee_cable_tv'] ?? null,
                'bill_payment_fee_internet' => $validated['bill_payment_fee_internet'] ?? null,
                'bill_payment_commission_airtime' => $validated['bill_payment_commission_airtime'] ?? null,
                'bill_payment_commission_data' => $validated['bill_payment_commission_data'] ?? null,
                'bill_payment_commission_electricity' => $validated['bill_payment_commission_electricity'] ?? null,
                'bill_payment_commission_cable_tv' => $validated['bill_payment_commission_cable_tv'] ?? null,
                'bill_payment_commission_internet' => $validated['bill_payment_commission_internet'] ?? null,
                'account_number_mode' => $accountNumberMode,
                'account_number_prefixes' => $accountNumberPrefixes ?: null,
                'account_number_serial_next' => null,
                'account_number_serial_end' => null,
                'kyc_provider' => $validated['kyc_provider'],
                'didit_api_key' => $validated['didit_api_key'] ?? null,
                'didit_workflow_id' => $validated['didit_workflow_id'] ?? null,
                'didit_base_url' => $validated['didit_base_url'] ?? 'https://verification.didit.me',
                ...$approvalSettings,
                'member_notification_automations' => $memberNotificationAutomations,
            ],
        ]);

        return back()->with('status', 'Company settings saved.');
    }

    private function normalizeAccountNumberPrefixes(string $prefixes): string
    {
        preg_match_all('/\d/', $prefixes, $matches);

        return implode(',', array_values(array_unique($matches[0] ?? [])));
    }

    private function lockedCommunicationSettings(array $existingSettings, PlatformSettings $platformSettings): array
    {
        $platformSms = $platformSettings->platformSmsSettings();
        $platformWhatsapp = $platformSettings->platformWhatsappSettings();

        return [
            'sms_driver' => $existingSettings['sms_driver'] ?? $platformSms['sms_driver'] ?? 'log',
            'sms_gateway_url' => $existingSettings['sms_gateway_url'] ?? $platformSms['sms_gateway_url'] ?? null,
            'sms_gateway_method' => $existingSettings['sms_gateway_method'] ?? $platformSms['sms_gateway_method'] ?? 'POST',
            'sms_gateway_username' => $existingSettings['sms_gateway_username'] ?? $platformSms['sms_gateway_username'] ?? null,
            'sms_gateway_token' => $existingSettings['sms_gateway_token'] ?? null,
            'sms_from' => $existingSettings['sms_from'] ?? $platformSms['sms_from'] ?? null,
            'sms_to_param' => $existingSettings['sms_to_param'] ?? $platformSms['sms_to_param'] ?? 'to',
            'sms_message_param' => $existingSettings['sms_message_param'] ?? $platformSms['sms_message_param'] ?? 'message',
            'sms_sender_param' => $existingSettings['sms_sender_param'] ?? $platformSms['sms_sender_param'] ?? 'from',
            'sms_dnd_sender' => $existingSettings['sms_dnd_sender'] ?? $platformSms['sms_dnd_sender'] ?? '1',
            'whatsapp_driver' => $existingSettings['whatsapp_driver'] ?? $platformWhatsapp['whatsapp_driver'] ?? 'log',
            'whatsapp_gateway_url' => $existingSettings['whatsapp_gateway_url'] ?? $platformWhatsapp['whatsapp_gateway_url'] ?? null,
            'whatsapp_gateway_method' => $existingSettings['whatsapp_gateway_method'] ?? $platformWhatsapp['whatsapp_gateway_method'] ?? 'POST',
            'whatsapp_gateway_username' => $existingSettings['whatsapp_gateway_username'] ?? $platformWhatsapp['whatsapp_gateway_username'] ?? null,
            'whatsapp_gateway_token' => $existingSettings['whatsapp_gateway_token'] ?? null,
            'whatsapp_from' => $existingSettings['whatsapp_from'] ?? $platformWhatsapp['whatsapp_from'] ?? null,
            'whatsapp_to_param' => $existingSettings['whatsapp_to_param'] ?? $platformWhatsapp['whatsapp_to_param'] ?? 'to',
            'whatsapp_message_param' => $existingSettings['whatsapp_message_param'] ?? $platformWhatsapp['whatsapp_message_param'] ?? 'message',
            'whatsapp_sender_param' => $existingSettings['whatsapp_sender_param'] ?? $platformWhatsapp['whatsapp_sender_param'] ?? 'from',
        ];
    }
}
