<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AgencyManagementReport;
use App\Models\EmailLog;
use App\Services\Mail\AgencyManagementMailSettingsManager;
use App\Services\Mail\AgencyManagementReportMailer;
use App\Services\Operations\AgencyManagementReportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AgencyManagementMailController extends Controller
{
    public function __construct(
        private readonly AgencyManagementMailSettingsManager $settings,
        private readonly AgencyManagementReportMailer $mailer,
        private readonly AgencyManagementReportService $reports,
    ) {
    }

    public function settings(): View
    {
        $settings = $this->settings->all();
        $logs = EmailLog::query()
            ->where('subject', 'like', '%Ajans%Yönetim%Raporu%')
            ->latest()
            ->take(25)
            ->get();

        return view('admin.management-reports.mail-settings', compact('settings', 'logs'));
    }

    public function save(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'recipients' => ['nullable', 'string'],
            'cc' => ['nullable', 'string'],
            'bcc' => ['nullable', 'string'],
            'subject_prefix' => ['nullable', 'string', 'max:160'],
            'intro_note' => ['nullable', 'string', 'max:1000'],
            'auto_weekly_enabled' => ['nullable', 'boolean'],
            'auto_monthly_enabled' => ['nullable', 'boolean'],
            'include_html' => ['nullable', 'boolean'],
            'include_csv' => ['nullable', 'boolean'],
        ]);

        $data['auto_weekly_enabled'] = $request->boolean('auto_weekly_enabled');
        $data['auto_monthly_enabled'] = $request->boolean('auto_monthly_enabled');
        $data['include_html'] = $request->boolean('include_html');
        $data['include_csv'] = $request->boolean('include_csv');

        $this->settings->save($data);

        return back()->with('success', 'Ajans yönetim raporu mail ayarları kaydedildi.');
    }

    public function send(Request $request, AgencyManagementReport $managementReport): RedirectResponse
    {
        $options = $request->validate([
            'recipients' => ['nullable', 'string'],
            'cc' => ['nullable', 'string'],
            'bcc' => ['nullable', 'string'],
            'note' => ['nullable', 'string', 'max:1000'],
            'include_html' => ['nullable', 'boolean'],
            'include_csv' => ['nullable', 'boolean'],
        ]);

        $options['include_html'] = $request->boolean('include_html', true);
        $options['include_csv'] = $request->boolean('include_csv', true);

        try {
            $log = $this->mailer->send($managementReport, $options);
        } catch (\Throwable $exception) {
            return back()->with('error', $exception->getMessage());
        }

        if ($log->status === 'failed') {
            return back()->with('error', 'Mail gönderilemedi: '.$log->error_message);
        }

        return back()->with('success', 'Ajans yönetim raporu mail olarak gönderildi.');
    }

    public function sendLatest(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'period_type' => ['nullable', 'in:daily,weekly,monthly,custom'],
            'recipients' => ['nullable', 'string'],
            'generate_if_missing' => ['nullable', 'boolean'],
        ]);

        $period = $data['period_type'] ?? 'weekly';
        $report = AgencyManagementReport::query()
            ->where('period_type', $period)
            ->where('status', 'completed')
            ->latest('generated_at')
            ->latest('id')
            ->first();

        if (! $report || $request->boolean('generate_if_missing')) {
            $report = $this->reports->generate(['period_type' => $period]);
        }

        if (! $report || $report->status !== 'completed') {
            return back()->with('error', 'Gönderilecek tamamlanmış ajans yönetim raporu bulunamadı.');
        }

        try {
            $log = $this->mailer->send($report, [
                'recipients' => $data['recipients'] ?? null,
            ]);
        } catch (\Throwable $exception) {
            return back()->with('error', $exception->getMessage());
        }

        if ($log->status === 'failed') {
            return back()->with('error', 'Mail gönderilemedi: '.$log->error_message);
        }

        return redirect()
            ->route('admin.management-reports.show', $report)
            ->with('success', 'Son ajans yönetim raporu mail olarak gönderildi.');
    }
}
