<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class EmailTemplateController extends Controller
{
    /**
     * Display a listing of email templates.
     */
    public function index(): Response
    {
        $templates = EmailTemplate::orderBy('name')->get();

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

    /**
     * Show the form for editing the specified template.
     */
    public function edit(EmailTemplate $emailTemplate): Response
    {
        return Inertia::render('Admin/EmailTemplates/Edit', [
            'template' => $emailTemplate,
        ]);
    }

    /**
     * Update the specified template.
     */
    public function update(Request $request, EmailTemplate $emailTemplate): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'is_active' => 'boolean',
        ]);

        $emailTemplate->update($validated);

        return redirect()->route('admin.email-templates.index')
            ->with('success', 'Plantilla actualizada correctamente.');
    }

    /**
     * Preview the template with sample data.
     */
    public function preview(Request $request, EmailTemplate $emailTemplate)
    {
        // Sample data for preview
        $sampleData = [
            'app_name' => config('app.name', 'CoachPro'),
            'client_name' => 'Juan Pérez',
            'coach_name' => 'Carlos García',
            'user_name' => 'María López',
            'email' => 'cliente@ejemplo.com',
            'password' => 'temporal123',
            'login_url' => url('/login'),
            'dashboard_url' => url('/coach/dashboard'),
            'renew_url' => url('/coach/subscription/plans'),
            'plan_name' => 'Plan Premium',
            'start_date' => now()->format('d/m/Y'),
            'end_date' => now()->addDays(30)->format('d/m/Y'),
            'days_remaining' => '7',
        ];

        $rendered = $emailTemplate->render($sampleData);

        if ($request->wantsJson()) {
            return response()->json($rendered);
        }

        return response($rendered['body'])->header('Content-Type', 'text/html');
    }

    /**
     * Reset all templates to default.
     */
    public function reset(): RedirectResponse
    {
        // Re-run the seeder
        $seeder = new \Database\Seeders\EmailTemplateSeeder();
        $seeder->run();

        return redirect()->route('admin.email-templates.index')
            ->with('success', 'Todas las plantillas han sido restauradas.');
    }

    /**
     * Send test email.
     */
    public function sendTest(Request $request, EmailTemplate $emailTemplate): RedirectResponse
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $sampleData = [
            'app_name' => config('app.name', 'CoachPro'),
            'client_name' => 'Usuario de Prueba',
            'coach_name' => 'Entrenador Demo',
            'user_name' => 'Usuario Demo',
            'email' => $request->email,
            'password' => 'demo123',
            'login_url' => url('/login'),
            'dashboard_url' => url('/coach/dashboard'),
            'renew_url' => url('/coach/subscription/plans'),
            'plan_name' => 'Plan Premium',
            'start_date' => now()->format('d/m/Y'),
            'end_date' => now()->addDays(30)->format('d/m/Y'),
            'days_remaining' => '7',
        ];

        $rendered = $emailTemplate->render($sampleData);

        try {
            \Mail::html($rendered['body'], function ($message) use ($request, $rendered) {
                $message->to($request->email)
                    ->subject($rendered['subject']);
            });

            return back()->with('success', 'Email de prueba enviado correctamente.');
        } catch (\Exception $e) {
            return back()->with('error', 'Error al enviar: ' . $e->getMessage());
        }
    }
}
