authorizeWrite('settings'); $settings = EmailSetting::first() ?? new EmailSetting(); $senderAccounts = SenderAccount::orderBy('email_address')->get(); $googleStatus = app(GoogleOAuthService::class)->getConnectionStatus(); $firme = $settings->exists ? $settings->firme : collect(); return view('admin.email-settings.index', compact('settings', 'senderAccounts', 'googleStatus', 'firme')); } public function save(Request $request) { $this->authorizeWrite('settings'); $validated = $request->validate([ 'imap_host' => 'required|string|max:255', 'imap_port' => 'required|integer|min:1|max:65535', 'imap_encryption' => 'nullable|in:ssl,tls,none', 'imap_username' => 'required|string|max:255', 'imap_password' => 'nullable|string', 'smtp_host' => 'nullable|string|max:255', 'smtp_port' => 'nullable|integer|min:1|max:65535', 'smtp_encryption' => 'nullable|in:ssl,tls,none', 'smtp_username' => 'nullable|string|max:255', 'smtp_password' => 'nullable|string', 'email_address' => 'required|email', 'email_name' => 'nullable|string|max:255', 'from_email' => 'nullable|email|max:255', 'from_name' => 'nullable|string|max:255', 'reply_to' => 'nullable|email', 'sync_interval_minutes' => 'nullable|integer|min:1|max:60', 'is_active' => 'boolean', 'signature' => 'nullable|string', 'signature_enabled' => 'boolean', 'auth_method' => 'nullable|in:password,oauth', 'google_oauth_connection_id' => 'nullable|integer|exists:google_oauth_connections,id', ]); if (!empty($validated['imap_password'])) { $validated['imap_password'] = Crypt::encryptString($validated['imap_password']); } else { unset($validated['imap_password']); } if (!empty($validated['smtp_password'])) { $validated['smtp_password'] = Crypt::encryptString($validated['smtp_password']); } else { unset($validated['smtp_password']); } $saved = EmailSetting::updateOrCreate( ['id' => $request->id ?? 1], $validated ); $verify = EmailSetting::find($saved->id); $allGood = $verify && $verify->imap_host === $validated['imap_host'] && $verify->email_address === $validated['email_address']; $allGood = $allGood && (!array_key_exists('signature', $validated) || $verify->signature === $validated['signature']) && (!array_key_exists('signature_enabled', $validated) || (bool)$verify->signature_enabled === (bool)$validated['signature_enabled']); if ($allGood) { return back()->with('success', 'Impostazioni email salvate e verificate nel database.'); } else { return back()->with('error', 'Errore nel salvataggio: i dati non sono stati salvati correttamente.'); } } public function testConnection(Request $request) { $this->authorizeWrite('settings'); $settings = EmailSetting::first(); if (!$settings) { return response()->json(['success' => false, 'message' => 'Configurazione non trovata.']); } if (empty($settings->imap_host) || empty($settings->email_address)) { return response()->json(['success' => false, 'message' => 'Prima salva le impostazioni.']); } try { $result = $settings->testConnection(); return response()->json($result); } catch (\Exception $e) { $msg = $e->getMessage(); if (strpos($msg, 'Undefined property') !== false) { $msg = 'Impossibile connettersi al server IMAP. Verifica host, porta, encryption e credenziali.'; } return response()->json(['success' => false, 'message' => 'Errore: ' . $msg]); } } public function testSmtp(Request $request) { $this->authorizeWrite('settings'); $request->validate([ 'email' => 'required|email', ]); $settings = EmailSetting::first(); if (!$settings) { return response()->json(['success' => false, 'message' => 'Configurazione non trovata.']); } try { $mailer = $settings->getSmtpMailer(); if ($mailer === null) { return response()->json(['success' => false, 'message' => 'Impossibile creare il mailer SMTP. Verifica la configurazione.']); } $smtpUser = $settings->smtp_username ?: $settings->email_address; $fromName = $settings->getEffectiveFromName(); $replyToEmail = $settings->from_email ?: $smtpUser; $email = (new Email()) ->from(Address::create($smtpUser, $fromName)) ->to($request->email) ->subject('Test Configurazione SMTP - Glastree') ->text('Test email da Glastree - Configurazione SMTP funziona!'); if ($replyToEmail !== $smtpUser) { $email->replyTo(Address::create($replyToEmail, $fromName)); } $mailer->send($email); \Illuminate\Support\Facades\Log::info('Test SMTP ok', ['to' => $request->email, 'from' => $settings->email_address]); return response()->json(['success' => true, 'message' => 'Email di test inviata a ' . $request->email]); } catch (\Exception $e) { \Illuminate\Support\Facades\Log::error('Test SMTP failed', ['error' => $e->getMessage()]); return response()->json(['success' => false, 'message' => 'Errore invio: ' . $e->getMessage()]); } } public function syncNow() { $this->authorizeWrite('settings'); $settings = EmailSetting::getActive(); if (!$settings) { return back()->with('error', 'Nessuna configurazione email attiva.'); } try { app(\App\Http\Controllers\EmailController::class)->syncEmails(); $settings->update(['last_sync_at' => now()]); return back()->with('success', 'Sincronizzazione completata.'); } catch (\Exception $e) { return back()->with('error', 'Errore sync: ' . $e->getMessage()); } } public function senderStore(Request $request) { $this->authorizeWrite('settings'); $data = $request->validate([ 'email_address' => 'required|email|max:255|unique:sender_accounts,email_address', 'email_name' => 'nullable|string|max:255', 'smtp_host' => 'nullable|string|max:255', 'smtp_port' => 'nullable|integer|min:1|max:65535', 'smtp_encryption' => 'nullable|in:tls,ssl,none', 'smtp_username' => 'nullable|string|max:255', 'smtp_password' => 'nullable|string', 'reply_to' => 'nullable|email|max:255', 'verify_email' => 'nullable|email|max:255', 'note' => 'nullable|string|max:500', 'is_active' => 'boolean', 'auth_method' => 'nullable|in:password,oauth', 'google_oauth_connection_id' => 'nullable|integer|exists:google_oauth_connections,id', ]); if (!empty($data['smtp_password'])) { $data['smtp_password'] = Crypt::encryptString($data['smtp_password']); } else { unset($data['smtp_password']); } $sender = SenderAccount::create($data); return back()->with('success', 'Mittente "' . $sender->email_address . '" creato con successo.'); } public function senderUpdate(Request $request, int $id) { $this->authorizeWrite('settings'); $sender = SenderAccount::findOrFail($id); $data = $request->validate([ 'email_address' => 'required|email|max:255|unique:sender_accounts,email_address,' . $id, 'email_name' => 'nullable|string|max:255', 'smtp_host' => 'nullable|string|max:255', 'smtp_port' => 'nullable|integer|min:1|max:65535', 'smtp_encryption' => 'nullable|in:tls,ssl,none', 'smtp_username' => 'nullable|string|max:255', 'smtp_password' => 'nullable|string', 'reply_to' => 'nullable|email|max:255', 'verify_email' => 'nullable|email|max:255', 'note' => 'nullable|string|max:500', 'is_active' => 'boolean', 'auth_method' => 'nullable|in:password,oauth', 'google_oauth_connection_id' => 'nullable|integer|exists:google_oauth_connections,id', ]); if (!empty($data['smtp_password'])) { $data['smtp_password'] = Crypt::encryptString($data['smtp_password']); } else { unset($data['smtp_password']); } $sender->update($data); return back()->with('success', 'Mittente "' . $sender->email_address . '" aggiornato.'); } public function senderDestroy(int $id) { $this->authorizeDelete('settings'); $sender = SenderAccount::findOrFail($id); $sender->delete(); if (request()->expectsJson()) { return response()->json(['success' => true, 'message' => 'Mittente eliminato.']); } return back()->with('success', 'Mittente eliminato.'); } public function destroy(): RedirectResponse { $this->authorizeDelete('settings'); EmailAttachment::chunk(100, function ($attachments) { foreach ($attachments as $attachment) { if ($attachment->file_path && Storage::exists($attachment->file_path)) { Storage::delete($attachment->file_path); } } }); EmailFolder::whereIn('type', ['inbox', 'sent', 'drafts', 'trash', 'archive', 'starred'])->each(function ($folder) { $folder->delete(); }); $settings = EmailSetting::first(); if ($settings) { $settings->delete(); } return redirect('/impostazioni/email')->with('success', 'Configurazione email eliminata. Messaggi, cartelle e allegati rimossi completamente.'); } public function senderTestSmtp(Request $request, int $id) { $this->authorizeWrite('settings'); $request->validate(['email' => 'required|email']); $sender = SenderAccount::findOrFail($id); try { $sender->sendEmail( $request->email, 'Test Configurazione SMTP - ' . config('app.name'), 'Test email da ' . config('app.name') . ' - Configurazione SMTP mittente "' . $sender->email_address . '" funziona!' ); return response()->json(['success' => true, 'message' => 'Email di test inviata a ' . $request->email]); } catch (\Exception $e) { return response()->json(['success' => false, 'message' => 'Errore invio: ' . $e->getMessage()]); } } public function firmaStore(Request $request) { $this->authorizeWrite('settings'); $data = $request->validate([ 'nome' => 'required|string|max:255', 'contenuto_html' => 'nullable|string', 'is_default' => 'boolean', ]); $settings = EmailSetting::getActive(); if (!$settings) { return redirect('/impostazioni/email')->with('error', 'Account email non configurato.'); } $firma = $settings->firme()->create($data); if ($data['is_default'] ?? false) { $settings->firme()->where('id', '!=', $firma->id)->update(['is_default' => false]); } return redirect('/impostazioni/email#firme')->with('success', 'Firma "' . $firma->nome . '" creata.'); } public function firmaUpdate(Request $request, int $id) { $this->authorizeWrite('settings'); $data = $request->validate([ 'nome' => 'required|string|max:255', 'contenuto_html' => 'nullable|string', 'is_default' => 'boolean', ]); $firma = Firma::findOrFail($id); $firma->update($data); if ($data['is_default'] ?? false) { Firma::where('email_setting_id', $firma->email_setting_id) ->where('id', '!=', $firma->id) ->update(['is_default' => false]); } return redirect('/impostazioni/email#firme')->with('success', 'Firma "' . $firma->nome . '" aggiornata.'); } public function firmaSetDefault(int $id) { $this->authorizeWrite('settings'); $firma = Firma::findOrFail($id); Firma::where('email_setting_id', $firma->email_setting_id)->update(['is_default' => false]); $firma->update(['is_default' => true]); return redirect('/impostazioni/email#firme')->with('success', 'Firma "' . $firma->nome . '" impostata come predefinita.'); } public function firmaDestroy(int $id) { $this->authorizeWrite('settings'); $firma = Firma::findOrFail($id); $nome = $firma->nome; $firma->delete(); return redirect('/impostazioni/email#firme')->with('success', 'Firma "' . $nome . '" eliminata.'); } }