<?php

namespace App\Http\Controllers\Admin\Settings;

use Illuminate\Http\Request;
use Inertia\Inertia;

class SmtpSettingsController extends BaseSettingsController
{
    public function index()
    {
        $encryption = config('mail.mailers.smtp.encryption');

        return Inertia::render('admin/settings/smtp/index', [
            'smtpConfig' => [
                'host' => config('mail.mailers.smtp.host', ''),
                'port' => config('mail.mailers.smtp.port', 587),
                'username' => config('mail.mailers.smtp.username', ''),
                'password' => config('mail.mailers.smtp.password', ''),
                'encryption' => $encryption ?: 'none',
                'from_address' => config('mail.from.address', ''),
                'from_name' => config('mail.from.name', ''),
            ],
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'host' => 'required|string|max:255',
            'port' => 'required|integer|min:1|max:65535',
            'username' => 'nullable|string|max:255',
            'password' => 'nullable|string|max:255',
            'encryption' => 'nullable|string|in:tls,ssl,none',
            'from_address' => 'required|email|max:255',
            'from_name' => 'required|string|max:255',
        ]);

        $this->updateEnv([
            'MAIL_HOST' => $request->host,
            'MAIL_PORT' => (string) $request->port,
            'MAIL_USERNAME' => $request->username ?? '',
            'MAIL_PASSWORD' => $request->password ?? '',
            'MAIL_ENCRYPTION' => $request->encryption === 'none' ? '' : $request->encryption,
            'MAIL_FROM_ADDRESS' => $request->from_address,
            'MAIL_FROM_NAME' => $request->from_name,
        ]);

        return back()->with('success', 'SMTP settings updated successfully.');
    }
}
