<?php

namespace App\Services;

use App\Constants\Status;
use App\Models\Language;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;

class AppConfigService
{
    /**
     * Apply application-wide settings dynamically.
     */
    public function applyAppSettings(): void
    {
        $defaultLanguage     = Language::default();
        $defaultLanguageCode = $defaultLanguage->code ?? 'en';

        Config::set([
            'app.timezone'                          => setting('site_timezone', 'utc'),
            'app.env'                               => setting('site_environment', 'local'),
            'app.debug'                             => setting('development_mode', true),
            'app.locale'                            => $defaultLanguageCode,
            'app.default_language'                  => $defaultLanguageCode,
            'security.duplicate_submission_timeout' => setting('submission_lock_duration', 5),
        ]);
    }

    /**
     * Dynamically apply SMTP email settings.
     */
    public function applyMailSettings(): void
    {
        Config::set('mail', [
            'default' => 'smtp',
            'from'    => [
                'name'    => setting('site_title', 'Wallet System'),
                'address' => setting('email_from_address', 'noreply@example.com'),
            ],
            'mailers' => [
                'smtp' => [
                    'transport'  => 'smtp',
                    'host'       => setting('mail_host', 'smtp.example.com'),
                    'port'       => setting('mail_port', 587),
                    'username'   => setting('mail_username', 'user@example.com'),
                    'password'   => setting('mail_password', 'password'),
                    'encryption' => setting('mail_secure', 'tls'),
                ],
            ],
        ]);
    }

    public function applySmsConfig(): void
    {
        $twilioConfig = pluginCredentials('twilio');

        // Ensure Pusher is enabled before setting configuration
        if (! isset($twilioConfig['status']) || $twilioConfig['status'] !== Status::TRUE) {
            return;
        }
        Config::set('twilio-notification-channel', [
            'account_sid' => $twilioConfig['account_sid'],
            'auth_token'  => $twilioConfig['auth_token'],
            'from'        => $twilioConfig['from'],
        ]);
    }

    /**
     * Force HTTPS if enabled.
     */
    public function forceHttpsIfEnabled(): void
    {
        if (config('app.env') !== 'local' && setting('force_https', false)) {
            URL::forceScheme('https');
        }
    }
}
