<?php

namespace App\Providers;

use App\Models\AssessmentAttempt;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        $this->applyMailSettings();

        Event::listen(Registered::class, function (Registered $event) {
            $event->user->assignRole(\Spatie\Permission\Models\Role::findOrCreate('member'));

            // Claim assessment attempts taken as a guest with this email
            AssessmentAttempt::whereNull('user_id')
                ->where('guest_email', $event->user->email)
                ->update(['user_id' => $event->user->id]);
        });

        // Track sign-ins so we can show real "last seen" activity. Skip while
        // impersonating so an admin's "view as" doesn't overwrite the member's
        // genuine last-login timestamp.
        Event::listen(Login::class, function (Login $event) {
            if (session()->has('impersonator_id')) {
                return;
            }

            $event->user->forceFill([
                'last_login_at' => now(),
                'last_login_ip' => request()->ip(),
                'login_count' => (int) ($event->user->login_count ?? 0) + 1,
            ])->saveQuietly();
        });
    }

    /**
     * Apply admin-configured email settings (from the Configurations page) to the
     * live mailer, so entering SMTP details makes email send with no redeploy.
     */
    private function applyMailSettings(): void
    {
        $s = \App\Models\Setting::map();

        if (empty($s) || empty($s['mail_mailer'] ?? null)) {
            return;
        }

        config(['mail.default' => $s['mail_mailer']]);

        if (! empty($s['mail_from_address'] ?? null)) {
            config(['mail.from.address' => $s['mail_from_address']]);
        }
        if (! empty($s['mail_from_name'] ?? null)) {
            config(['mail.from.name' => $s['mail_from_name']]);
        }

        if ($s['mail_mailer'] === 'smtp') {
            foreach ([
                'smtp_host' => 'mail.mailers.smtp.host',
                'smtp_port' => 'mail.mailers.smtp.port',
                'smtp_username' => 'mail.mailers.smtp.username',
                'smtp_password' => 'mail.mailers.smtp.password',
            ] as $key => $path) {
                if (! empty($s[$key] ?? null)) {
                    config([$path => $s[$key]]);
                }
            }

            $encryption = $s['smtp_encryption'] ?? 'tls';
            config(['mail.mailers.smtp.encryption' => $encryption === 'none' ? null : $encryption]);
        }
    }
}
