<?php

namespace App\Providers;

use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class DynamicConfigServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     * 
     * Loads configuration from database Settings and overrides .env values.
     * This allows admin panel settings to take precedence.
     * Note: Email settings are now stored in .env, not database.
     */
    public function boot(): void
    {
        // Only run if the settings table exists (avoid errors during migrations)
        if (!$this->canLoadSettings()) {
            return;
        }

        // Email settings are now managed via .env file (not database)
        // $this->loadEmailSettings();
        $this->loadPayPalSettings();
        $this->loadStripeSettings();
        $this->loadAppSettings();
    }

    /**
     * Check if we can safely load settings from database.
     */
    protected function canLoadSettings(): bool
    {
        try {
            // Check if we're in console and running migrations
            if (app()->runningInConsole()) {
                $argv = $_SERVER['argv'] ?? [];
                if (in_array('migrate', $argv) || in_array('migrate:fresh', $argv)) {
                    return false;
                }
            }

            return Schema::hasTable('settings');
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Load and apply email/SMTP settings from database.
     */
    protected function loadEmailSettings(): void
    {
        try {
            $emailSettings = Setting::getGroup('email');
            
            if (empty($emailSettings)) {
                return;
            }

            // Only override if settings are configured in admin panel
            if (!empty($emailSettings['mail_host'])) {
                Config::set('mail.default', 'smtp');
                Config::set('mail.mailers.smtp.host', $emailSettings['mail_host']);
            }

            if (!empty($emailSettings['mail_port'])) {
                Config::set('mail.mailers.smtp.port', (int) $emailSettings['mail_port']);
            }

            // Use explicit encryption setting if available, otherwise auto-detect from port
            if (!empty($emailSettings['mail_encryption'])) {
                $encryption = $emailSettings['mail_encryption'] === 'null' ? null : $emailSettings['mail_encryption'];
                Config::set('mail.mailers.smtp.encryption', $encryption);
            } elseif (!empty($emailSettings['mail_port'])) {
                // Auto-configure encryption based on port
                $port = (int) $emailSettings['mail_port'];
                $encryption = match($port) {
                    465 => 'ssl',
                    587, 25, 2525 => 'tls',
                    default => 'tls',
                };
                Config::set('mail.mailers.smtp.encryption', $encryption);
            }

            if (!empty($emailSettings['mail_username'])) {
                Config::set('mail.mailers.smtp.username', $emailSettings['mail_username']);
            }

            if (!empty($emailSettings['mail_password'])) {
                Config::set('mail.mailers.smtp.password', $emailSettings['mail_password']);
            }

            if (!empty($emailSettings['mail_from_address'])) {
                Config::set('mail.from.address', $emailSettings['mail_from_address']);
            }

            if (!empty($emailSettings['mail_from_name'])) {
                Config::set('mail.from.name', $emailSettings['mail_from_name']);
            }

        } catch (\Exception $e) {
            // Log but don't crash - fall back to .env settings
            Log::warning('DynamicConfig: Could not load email settings: ' . $e->getMessage());
        }
    }

    /**
     * Load and apply PayPal settings from database.
     */
    protected function loadPayPalSettings(): void
    {
        try {
            $paymentSettings = Setting::getGroup('payment');
            
            if (empty($paymentSettings)) {
                return;
            }

            $sandbox = $paymentSettings['paypal_sandbox'] ?? true;
            $mode = $sandbox ? 'sandbox' : 'live';
            
            Config::set('paypal.mode', $mode);

            if (!empty($paymentSettings['paypal_client_id'])) {
                Config::set("paypal.{$mode}.client_id", $paymentSettings['paypal_client_id']);
            }

            if (!empty($paymentSettings['paypal_secret'])) {
                try {
                    $secret = decrypt($paymentSettings['paypal_secret']);
                    Config::set("paypal.{$mode}.client_secret", $secret);
                } catch (\Exception $e) {
                    Config::set("paypal.{$mode}.client_secret", $paymentSettings['paypal_secret']);
                }
            }

            // Set currency from general settings
            $generalSettings = Setting::getGroup('general');
            if (!empty($generalSettings['currency'])) {
                Config::set('paypal.currency', $generalSettings['currency']);
            }

        } catch (\Exception $e) {
            Log::warning('DynamicConfig: Could not load PayPal settings: ' . $e->getMessage());
        }
    }

    /**
     * Load and apply Stripe settings from database.
     */
    protected function loadStripeSettings(): void
    {
        try {
            $paymentSettings = Setting::getGroup('payment');
            
            if (empty($paymentSettings)) {
                return;
            }

            if (!empty($paymentSettings['stripe_key'])) {
                Config::set('services.stripe.key', $paymentSettings['stripe_key']);
            }

            if (!empty($paymentSettings['stripe_secret'])) {
                try {
                    $secret = decrypt($paymentSettings['stripe_secret']);
                    Config::set('services.stripe.secret', $secret);
                } catch (\Exception $e) {
                    Config::set('services.stripe.secret', $paymentSettings['stripe_secret']);
                }
            }

        } catch (\Exception $e) {
            Log::warning('DynamicConfig: Could not load Stripe settings: ' . $e->getMessage());
        }
    }

    /**
     * Load and apply general app settings from database.
     */
    protected function loadAppSettings(): void
    {
        try {
            $generalSettings = Setting::getGroup('general');
            
            if (empty($generalSettings)) {
                return;
            }

            if (!empty($generalSettings['site_name'])) {
                Config::set('app.name', $generalSettings['site_name']);
            }

            if (!empty($generalSettings['timezone'])) {
                Config::set('app.timezone', $generalSettings['timezone']);
                date_default_timezone_set($generalSettings['timezone']);
            }

        } catch (\Exception $e) {
            Log::warning('DynamicConfig: Could not load app settings: ' . $e->getMessage());
        }
    }
}
