<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class MailService
{
    public static function configure(): void
    {
        $s = DB::table('settings')
            ->whereIn('key', [
                'smtp_host', 'smtp_port', 'smtp_encryption',
                'smtp_username', 'smtp_password',
                'smtp_sender_name', 'smtp_sender_email',
            ])
            ->pluck('value', 'key');

        if (!$s->get('smtp_host')) return;

        config([
            'mail.default'                 => 'smtp',
            'mail.mailers.smtp.host'       => $s->get('smtp_host'),
            'mail.mailers.smtp.port'       => (int) ($s->get('smtp_port', 587)),
            'mail.mailers.smtp.encryption' => $s->get('smtp_encryption', 'tls') ?: null,
            'mail.mailers.smtp.username'   => $s->get('smtp_username', ''),
            'mail.mailers.smtp.password'   => $s->get('smtp_password', ''),
            'mail.from.address'            => $s->get('smtp_sender_email', 'noreply@aliman.net'),
            'mail.from.name'               => $s->get('smtp_sender_name', 'نادي الإيمان ٢'),
        ]);

        app(\Illuminate\Mail\MailManager::class)->purge('smtp');
    }

    public static function isEnabled(string $trigger): bool
    {
        return DB::table('settings')
            ->where('key', "email_trigger_{$trigger}")
            ->value('value') === '1';
    }
}
