<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use Illuminate\Http\Request;

class EmailTemplateController extends Controller
{
    public function index()
    {
        $templates = EmailTemplate::latest()->get();
        return view('admin.email-templates.index', compact('templates'));
    }

    public function create()
    {
        return view('admin.email-templates.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'slug' => 'required|string|unique:email_templates,slug|max:255',
            'name' => 'required|string|max:255',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'custom_css' => 'nullable|string',
            'variables' => 'nullable|string',
            'description' => 'nullable|string',
            'is_active' => 'boolean'
        ]);

        // Traiter les variables
        $validated['variables'] = $request->variables ? array_map('trim', explode(',', $request->variables)) : [];
        $validated['is_active'] = $request->has('is_active');

        EmailTemplate::create($validated);

        return redirect()->route('admin.email-templates.index')
            ->with('success', 'Template email créé avec succès !');
    }

    public function show(EmailTemplate $emailTemplate)
    {
        return view('admin.email-templates.show', compact('emailTemplate'));
    }

    public function edit(EmailTemplate $emailTemplate)
    {
        return view('admin.email-templates.edit', compact('emailTemplate'));
    }

    public function update(Request $request, EmailTemplate $emailTemplate)
    {
        $validated = $request->validate([
            'slug' => 'required|string|max:255|unique:email_templates,slug,' . $emailTemplate->id,
            'name' => 'required|string|max:255',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'custom_css' => 'nullable|string',
            'variables' => 'nullable|string',
            'description' => 'nullable|string',
            'is_active' => 'boolean'
        ]);

        // Traiter les variables
        $validated['variables'] = $request->variables ? array_map('trim', explode(',', $request->variables)) : [];
        $validated['is_active'] = $request->has('is_active');

        $emailTemplate->update($validated);

        return redirect()->route('admin.email-templates.index')
            ->with('success', 'Template email modifié avec succès !');
    }

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

        return redirect()->route('admin.email-templates.index')
            ->with('success', 'Template email supprimé avec succès !');
    }

    public function sendTest(Request $request, EmailTemplate $emailTemplate)
    {
        $validated = $request->validate([
            'test_email' => 'required|email',
            'test_data' => 'nullable|string'
        ]);

        try {
            // Parser les données de test (JSON ou paires key=value)
            $testData = [];
            if (!empty($validated['test_data'])) {
                // Essayer de parser comme JSON
                $jsonData = json_decode($validated['test_data'], true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $testData = $jsonData;
                } else {
                    // Parser comme key=value séparés par des virgules ou nouvelles lignes
                    $lines = preg_split('/[\n,]/', $validated['test_data']);
                    foreach ($lines as $line) {
                        if (strpos($line, '=') !== false) {
                            [$key, $value] = explode('=', $line, 2);
                            $testData[trim($key)] = trim($value);
                        }
                    }
                }
            }

            // Remplir les variables manquantes avec des valeurs par défaut
            if ($emailTemplate->variables) {
                foreach ($emailTemplate->variables as $var) {
                    if (!isset($testData[$var])) {
                        $testData[$var] = "{{$var}}"; // Valeur par défaut
                    }
                }
            }

            // Envoyer l'email de test
            $sent = \App\Services\EmailService::send(
                $emailTemplate->slug,
                $validated['test_email'],
                $testData
            );

            if ($sent) {
                return back()->with('success', "Email de test envoyé avec succès à {$validated['test_email']} !");
            } else {
                return back()->with('error', "Échec de l'envoi de l'email de test. Vérifiez les logs.");
            }
        } catch (\Exception $e) {
            return back()->with('error', "Erreur : " . $e->getMessage());
        }
    }
}
