<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\UpdateEmailTemplateRequest;
use App\Models\EmailTemplate;
use Database\Seeders\EmailTemplateSeeder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class EmailTemplateController extends Controller
{
    public function index(): Response
    {
        $templates = EmailTemplate::query()
            ->orderBy('name')
            ->get();

        return Inertia::render('Admin/EmailTemplates/Index', [
            'templates' => $templates,
        ]);
    }

    public function edit(EmailTemplate $emailTemplate): Response
    {
        return Inertia::render('Admin/EmailTemplates/Edit', [
            'template' => $emailTemplate,
        ]);
    }

    public function update(UpdateEmailTemplateRequest $request, EmailTemplate $emailTemplate): RedirectResponse
    {
        $emailTemplate->update([
            'subject' => $request->validated('subject'),
            'body' => $request->validated('body'),
            'is_active' => $request->boolean('is_active'),
        ]);

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

    public function preview(EmailTemplate $emailTemplate, Request $request): JsonResponse
    {
        $sampleData = $this->getSampleData($emailTemplate);

        $subject = $emailTemplate->subject;
        $body = $emailTemplate->body;

        foreach ($sampleData as $key => $value) {
            $placeholder = '{{'.$key.'}}';
            $subject = str_replace($placeholder, $value, $subject);
            $body = str_replace($placeholder, $value, $body);
        }

        return response()->json([
            'subject' => $subject,
            'body' => $body,
        ]);
    }

    public function resetToDefault(EmailTemplate $emailTemplate): RedirectResponse
    {
        $defaults = EmailTemplateSeeder::getDefaultTemplates();

        $default = collect($defaults)->firstWhere('slug', $emailTemplate->slug);

        if ($default) {
            $emailTemplate->update([
                'subject' => $default['subject'],
                'body' => $default['body'],
                'is_active' => true,
            ]);
        }

        return redirect()
            ->route('admin.email-templates.edit', $emailTemplate)
            ->with('success', 'Email template reset to default.');
    }

    /**
     * Generate sample data for template preview.
     *
     * @return array<string, string>
     */
    private function getSampleData(EmailTemplate $emailTemplate): array
    {
        $sampleValues = [
            'customer_name' => 'John Doe',
            'amount' => '49.99',
            'currency' => 'USD',
            'invoice_number' => 'INV-2026-0001',
            'date' => now()->format('M j, Y'),
            'payment_method' => 'Visa ending in 4242',
            'error_message' => 'Card was declined',
            'plan_name' => 'VPS Pro',
            'billing_cycle' => 'Monthly',
            'cancellation_date' => now()->format('M j, Y'),
            'end_date' => now()->addMonth()->format('M j, Y'),
            'service_type' => 'VPS',
            'hostname' => 'vps-prod-01.ezscale.cloud',
            'ip_address' => '192.168.1.100',
            'username' => 'root',
            'password' => '********',
            'due_date' => now()->addDays(14)->format('M j, Y'),
        ];

        $variables = $emailTemplate->available_variables ?? [];
        $data = [];

        foreach ($variables as $variable) {
            $data[$variable] = $sampleValues[$variable] ?? "{{$variable}}";
        }

        return $data;
    }
}
