<?php

namespace App\Http\Controllers\Coach;

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

class EmailTemplateController extends Controller
{
    /**
     * Display email templates list.
     */
    public function index(Request $request): Response
    {
        $coach = $request->user();
        
        // Get coach's custom templates
        $customTemplates = CoachEmailTemplate::where('coach_id', $coach->id)->get()->keyBy('type');
        
        // Build templates list with defaults
        $templates = [];
        foreach (CoachEmailTemplate::$templateTypes as $type => $info) {
            $custom = $customTemplates->get($type);
            $templates[] = [
                'type' => $type,
                'name' => $info['name'],
                'description' => $info['description'],
                'variables' => $info['variables'],
                'subject' => $custom ? $custom->subject : $info['default_subject'],
                'body' => $custom ? $custom->body : $info['default_body'],
                'is_active' => $custom ? $custom->is_active : true,
                'is_custom' => $custom !== null,
            ];
        }

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

    /**
     * Show form to edit a template.
     */
    public function edit(Request $request, string $type): Response
    {
        $coach = $request->user();
        
        if (!isset(CoachEmailTemplate::$templateTypes[$type])) {
            abort(404);
        }

        $info = CoachEmailTemplate::$templateTypes[$type];
        $custom = CoachEmailTemplate::where('coach_id', $coach->id)
            ->where('type', $type)
            ->first();

        $template = [
            'type' => $type,
            'name' => $info['name'],
            'description' => $info['description'],
            'variables' => $info['variables'],
            'subject' => $custom ? $custom->subject : $info['default_subject'],
            'body' => $custom ? $custom->body : $info['default_body'],
            'is_active' => $custom ? $custom->is_active : true,
            'default_subject' => $info['default_subject'],
            'default_body' => $info['default_body'],
        ];

        return Inertia::render('Coach/EmailTemplates/Edit', [
            'template' => $template,
        ]);
    }

    /**
     * Update a template.
     */
    public function update(Request $request, string $type): RedirectResponse
    {
        $coach = $request->user();
        
        if (!isset(CoachEmailTemplate::$templateTypes[$type])) {
            abort(404);
        }

        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'body' => 'required|string|max:50000',
            'is_active' => 'boolean',
        ]);

        CoachEmailTemplate::updateOrCreate(
            ['coach_id' => $coach->id, 'type' => $type],
            [
                'subject' => $validated['subject'],
                'body' => $validated['body'],
                'is_active' => $validated['is_active'] ?? true,
            ]
        );

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

    /**
     * Reset a template to default.
     */
    public function reset(Request $request, string $type): RedirectResponse
    {
        $coach = $request->user();
        
        CoachEmailTemplate::where('coach_id', $coach->id)
            ->where('type', $type)
            ->delete();

        return back()->with('success', 'Plantilla restaurada a valores por defecto.');
    }

    /**
     * Send a test email.
     */
    public function sendTest(Request $request, string $type): RedirectResponse
    {
        $coach = $request->user();
        
        if (!isset(CoachEmailTemplate::$templateTypes[$type])) {
            abort(404);
        }

        $info = CoachEmailTemplate::$templateTypes[$type];
        $custom = CoachEmailTemplate::getForCoach($coach->id, $type);

        $subject = $custom ? $custom->subject : $info['default_subject'];
        $body = $custom ? $custom->body : $info['default_body'];

        // Create test data
        $testData = [
            'buyer_name' => 'Cliente de Prueba',
            'plan_name' => 'Plan de Ejemplo',
            'amount' => '99.00',
            'ends_at' => now()->addDays(30)->format('d/m/Y'),
            'coach_name' => $coach->name,
            'payment_instructions' => 'Instrucciones de pago de ejemplo',
            'days_remaining' => '5',
        ];

        foreach ($testData as $key => $value) {
            $subject = str_replace("{{{$key}}}", $value, $subject);
            $body = str_replace("{{{$key}}}", $value, $body);
        }

        try {
            \Illuminate\Support\Facades\Mail::html($body, function ($message) use ($coach, $subject) {
                $message->to($coach->email)
                    ->subject('[TEST] ' . $subject);
            });

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