<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Setting;

class MailConfigServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Only configure mail settings if the settings table exists
        try {
            if (\Schema::hasTable('settings')) {
                $this->configureMail();
            }
        } catch (\Exception $e) {
            // Settings table might not exist during migrations
        }
    }

    /**
     * Configure mail settings from database.
     *
     * @return void
     */
    protected function configureMail()
    {
        try {
            $mailer = Setting::get('mail_mailer', 'smtp');
            $host = Setting::get('mail_host');
            $port = Setting::get('mail_port', '587');
            $username = Setting::get('mail_username');
            $password = Setting::getEncrypted('mail_password');
            $encryption = Setting::get('mail_encryption', 'tls');
            $fromAddress = Setting::get('mail_from_address', 'noreply@afrilen.com');
            $fromName = Setting::get('mail_from_name', 'Afrilen Technologies');

            if ($host && $port) {
                config([
                    'mail.default' => $mailer,
                    'mail.mailers.smtp.host' => $host,
                    'mail.mailers.smtp.port' => $port,
                    'mail.mailers.smtp.username' => $username,
                    'mail.mailers.smtp.password' => $password,
                    'mail.mailers.smtp.encryption' => ($encryption === 'null' || empty($encryption)) ? null : $encryption,
                    'mail.from.address' => $fromAddress,
                    'mail.from.name' => $fromName,
                ]);
            }
        } catch (\Exception $e) {
            // Fail silently if settings can't be loaded
            \Log::warning('Failed to load mail settings from database: ' . $e->getMessage());
        }
    }
}

