<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class EmailTemplateController extends Controller
{
    public function index(): View
    {
        return view('admin.email-templates.index', [
            'templates' => EmailTemplate::query()->latest()->paginate(12),
        ]);
    }

    public function create(): View
    {
        return view('admin.email-templates.create', [
            'template' => new EmailTemplate([
                'is_active' => true,
                'body_html' => '<p>Write your email content here.</p>',
            ]),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        EmailTemplate::query()->create($this->validated($request));

        return redirect()->route('admin.email-templates.index')->with('status', 'Email template created.');
    }

    public function edit(EmailTemplate $emailTemplate): View
    {
        return view('admin.email-templates.edit', [
            'template' => $emailTemplate,
        ]);
    }

    public function update(Request $request, EmailTemplate $emailTemplate): RedirectResponse
    {
        $emailTemplate->update($this->validated($request, $emailTemplate));

        return redirect()->route('admin.email-templates.index')->with('status', 'Email template updated.');
    }

    public function destroy(EmailTemplate $emailTemplate): RedirectResponse
    {
        $emailTemplate->delete();

        return back()->with('status', 'Email template deleted.');
    }

    /**
     * @return array<string, mixed>
     */
    private function validated(Request $request, ?EmailTemplate $template = null): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['nullable', 'string', 'max:255', Rule::unique('email_templates', 'slug')->ignore($template)],
            'subject' => ['required', 'string', 'max:255'],
            'preheader' => ['nullable', 'string', 'max:255'],
            'body_html' => ['required', 'string', 'max:20000'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['slug'] = Str::slug(($data['slug'] ?? null) ?: $data['name']);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
