<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\EmailLog;
use App\Services\Mail\MailSettingsManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;
use Throwable;

class MailSettingController extends Controller
{
    public function settings(MailSettingsManager $settingsManager): View
    {
        $page_title = 'SMTP / Mail Ayarları';
        $page_description = 'Otomatik rapor mailleri için SMTP ayarları';
        $settings = $settingsManager->all();
        unset($settings['smtp_password']);

        return view('admin.mail.settings', compact('page_title', 'page_description', 'settings'));
    }

    public function save(Request $request, MailSettingsManager $settingsManager): RedirectResponse
    {
        $data = $request->validate([
            'smtp_host' => ['nullable', 'string', 'max:255'],
            'smtp_port' => ['nullable', 'integer'],
            'smtp_username' => ['nullable', 'string', 'max:255'],
            'smtp_password' => ['nullable', 'string', 'max:255'],
            'smtp_encryption' => ['nullable', 'in:tls,ssl,none'],
            'from_name' => ['nullable', 'string', 'max:255'],
            'from_email' => ['nullable', 'email', 'max:255'],
            'reply_to' => ['nullable', 'email', 'max:255'],
        ]);

        $settingsManager->save($data);

        return back()->with('success', 'Mail ayarları kaydedildi. SMTP şifresi şifreli ayar kasasında saklandı.');
    }

    public function test(Request $request, MailSettingsManager $settingsManager): RedirectResponse
    {
        $data = $request->validate([
            'test_email' => ['required', 'email', 'max:255'],
        ]);

        $log = EmailLog::create([
            'subject' => 'DW Ads Reporter Test Maili',
            'recipients' => [$data['test_email']],
            'status' => 'queued',
        ]);

        try {
            $settingsManager->apply();
            $settings = $settingsManager->all();

            Mail::send('emails.test.smtp', ['settings' => $settings], function ($message) use ($data, $settings) {
                $message->to($data['test_email'])->subject('DW Ads Reporter Test Maili');

                if (filled($settings['from_email'] ?? null)) {
                    $message->from($settings['from_email'], $settings['from_name'] ?? null);
                }

                if (filled($settings['reply_to'] ?? null)) {
                    $message->replyTo($settings['reply_to']);
                }
            });

            $log->update(['status' => 'sent', 'sent_at' => now()]);

            return back()->with('success', 'Test maili gönderildi.');
        } catch (Throwable $exception) {
            report($exception);
            $log->update(['status' => 'failed', 'error_message' => $exception->getMessage()]);

            return back()->with('error', 'Test maili gönderilemedi: ' . $exception->getMessage());
        }
    }

    public function logs(Request $request): View
    {
        $page_title = 'Mail Gönderim Logları';
        $page_description = 'Rapor ve test maili gönderim geçmişi';
        $clients = Client::orderBy('company_name')->get();

        $logs = EmailLog::with(['client', 'report'])
            ->when($request->filled('client_id'), fn ($query) => $query->where('client_id', $request->integer('client_id')))
            ->when($request->filled('status'), fn ($query) => $query->where('status', $request->string('status')))
            ->latest()
            ->paginate(30)
            ->withQueryString();

        return view('admin.mail.logs', compact('page_title', 'page_description', 'clients', 'logs'));
    }
}
