<?php

namespace App\Providers;

use Illuminate\Support\Facades\Vite;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        if (file_exists(base_path('.env'))) {
            $lines = file(base_path('.env'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $env = [];
            foreach ($lines as $line) {
                if (strpos(trim($line), '#') === 0) {
                    continue;
                }
                $parts = explode('=', $line, 2);
                if (count($parts) === 2) {
                    $key = trim($parts[0]);
                    $value = trim($parts[1]);
                    // Remove quotes
                    if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
                        $value = substr($value, 1, -1);
                    } elseif (str_starts_with($value, "'") && str_ends_with($value, "'")) {
                        $value = substr($value, 1, -1);
                    }
                    $env[$key] = $value;
                }
            }

            // Force override configs
            if (isset($env['DB_DATABASE'])) {
                config(['database.connections.mysql.database' => $env['DB_DATABASE']]);
            }
            if (isset($env['DB_HOST'])) {
                config(['database.connections.mysql.host' => $env['DB_HOST']]);
            }
            if (isset($env['DB_USERNAME'])) {
                config(['database.connections.mysql.username' => $env['DB_USERNAME']]);
            }
            if (isset($env['DB_PASSWORD'])) {
                config(['database.connections.mysql.password' => $env['DB_PASSWORD']]);
            }
            if (isset($env['APP_URL'])) {
                config(['app.url' => $env['APP_URL']]);
            }
            
            // Mail settings override
            if (isset($env['MAIL_MAILER'])) {
                config(['mail.default' => $env['MAIL_MAILER']]);
            }
            if (isset($env['MAIL_HOST'])) {
                config(['mail.mailers.smtp.host' => $env['MAIL_HOST']]);
            }
            if (isset($env['MAIL_PORT'])) {
                config(['mail.mailers.smtp.port' => (int) $env['MAIL_PORT']]);
            }
            if (isset($env['MAIL_USERNAME'])) {
                config(['mail.mailers.smtp.username' => $env['MAIL_USERNAME']]);
            }
            if (isset($env['MAIL_PASSWORD'])) {
                config(['mail.mailers.smtp.password' => $env['MAIL_PASSWORD']]);
            }
            if (isset($env['MAIL_FROM_ADDRESS'])) {
                config(['mail.from.address' => $env['MAIL_FROM_ADDRESS']]);
            }
            if (isset($env['MAIL_FROM_NAME'])) {
                config(['mail.from.name' => $env['MAIL_FROM_NAME']]);
            }
        }
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Vite::prefetch(concurrency: 3);
        Schema::defaultStringLength(191);

        // Run migrations automatically in development if table column is missing
        if (!app()->runningInConsole()) {
            try {
                if (
                    (Schema::hasTable('products') && !Schema::hasColumn('products', 'discount_percent')) ||
                    (Schema::hasTable('payments') && !Schema::hasColumn('payments', 'payment_proof'))
                ) {
                    \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
                }
            } catch (\Exception $e) {
                // ignore
            }
        }

        // Load database settings dynamically to override configurations at runtime
        try {
            if (!app()->runningInConsole() || Schema::hasTable('settings')) {
                if (Schema::hasTable('settings')) {
                    $settings = \App\Models\Setting::all()->pluck('value', 'key')->toArray();

                    // App Name / Store Name
                    if (!empty($settings['store_name'])) {
                        config(['app.name' => $settings['store_name']]);
                    }

                    // Midtrans
                    if (!empty($settings['midtrans_client_key'])) {
                        config(['services.midtrans.client_key' => $settings['midtrans_client_key']]);
                    }
                    if (!empty($settings['midtrans_server_key'])) {
                        config(['services.midtrans.server_key' => $settings['midtrans_server_key']]);
                    }
                    if (isset($settings['midtrans_is_production'])) {
                        config(['services.midtrans.is_production' => $settings['midtrans_is_production'] === 'true']);
                    }

                    // Fonnte WA Gateway
                    if (!empty($settings['fonnte_token'])) {
                        config(['services.fonnte.token' => $settings['fonnte_token']]);
                    }

                    // Google OAuth
                    if (!empty($settings['google_client_id'])) {
                        config(['services.google.client_id' => $settings['google_client_id']]);
                    }
                    if (!empty($settings['google_client_secret'])) {
                        config(['services.google.client_secret' => $settings['google_client_secret']]);
                    }

                    // Mail Sender (SMTP)
                    if (!empty($settings['mail_host'])) {
                        config([
                            'mail.default' => 'smtp',
                            'mail.mailers.smtp.host' => $settings['mail_host'],
                            'mail.mailers.smtp.port' => (int)($settings['mail_port'] ?? 587),
                            'mail.mailers.smtp.username' => $settings['mail_username'] ?? '',
                            'mail.mailers.smtp.password' => $settings['mail_password'] ?? '',
                            'mail.mailers.smtp.encryption' => (isset($settings['mail_encryption']) && $settings['mail_encryption'] !== 'null') ? $settings['mail_encryption'] : null,
                            'mail.from.address' => $settings['mail_from_address'] ?? 'hello@example.com',
                            'mail.from.name' => $settings['mail_from_name'] ?? ($settings['store_name'] ?? 'E-Shop'),
                        ]);
                    }
                }
            }
        } catch (\Exception $e) {
            // Prevent crash if database is not accessible
        }
    }
}
