<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use App\Services\EmailService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * EmailTemplateController
 * 
 * Admin controller for managing email templates.
 * Provides CRUD operations and template testing functionality.
 */
class EmailTemplateController extends Controller
{
    protected EmailService $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->middleware('auth');
        $this->middleware('admin');
        $this->emailService = $emailService;
    }

    /**
     * Display a listing of email templates.
     */
    public function index(Request $request): View
    {
        $query = EmailTemplate::query();

        // Filter by type
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // Filter by category
        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        // Filter by active status
        if ($request->filled('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('subject', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        $templates = $query->orderBy('type')
                          ->orderBy('category')
                          ->orderBy('name')
                          ->paginate(20);

        $types = EmailTemplate::distinct()->pluck('type')->sort();
        $categories = EmailTemplate::distinct()->pluck('category')->sort();

        return view('admin.email-templates.index', compact(
            'templates',
            'types',
            'categories'
        ));
    }

    /**
     * Show the form for creating a new email template.
     */
    public function create(): View
    {
        $types = ['user', 'admin'];
        $categories = ['registration', 'license', 'product', 'ticket', 'invoice'];

        return view('admin.email-templates.create', compact('types', 'categories'));
    }

    /**
     * Store a newly created email template.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:email_templates,name',
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'type' => 'required|in:user,admin',
            'category' => 'required|string|max:255',
            'variables' => 'nullable|array',
            'variables.*' => 'string|max:255',
            'is_active' => 'boolean',
            'description' => 'nullable|string|max:1000',
        ]);

        $template = EmailTemplate::create($validated);

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

    /**
     * Display the specified email template.
     */
    public function show(EmailTemplate $emailTemplate): View
    {
        return view('admin.email-templates.show', compact('emailTemplate'));
    }

    /**
     * Show the form for editing the specified email template.
     */
    public function edit(EmailTemplate $emailTemplate): View
    {
        $types = ['user', 'admin'];
        $categories = ['registration', 'license', 'product', 'ticket', 'invoice'];

        return view('admin.email-templates.edit', compact('emailTemplate', 'types', 'categories'));
    }

    /**
     * Update the specified email template.
     */
    public function update(Request $request, EmailTemplate $emailTemplate): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:email_templates,name,' . $emailTemplate->id,
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'type' => 'required|in:user,admin',
            'category' => 'required|string|max:255',
            'variables' => 'nullable|array',
            'variables.*' => 'string|max:255',
            'is_active' => 'boolean',
            'description' => 'nullable|string|max:1000',
        ]);

        $emailTemplate->update($validated);

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

    /**
     * Remove the specified email template.
     */
    public function destroy(EmailTemplate $emailTemplate): RedirectResponse
    {
        $emailTemplate->delete();

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

    /**
     * Toggle template active status.
     */
    public function toggle(EmailTemplate $emailTemplate): RedirectResponse
    {
        $emailTemplate->update(['is_active' => !$emailTemplate->is_active]);

        $status = $emailTemplate->is_active ? 'activated' : 'deactivated';

        return redirect()
            ->back()
            ->with('success', "Email template {$status} successfully.");
    }

    /**
     * Test email template rendering.
     */
    public function test(Request $request, EmailTemplate $emailTemplate): View
    {
        $testData = $request->get('test_data', []);
        
        // Add default test data
        $defaultData = [
            'user_name' => 'John Doe',
            'user_email' => 'john@example.com',
            'site_name' => config('app.name'),
            'site_url' => config('app.url'),
            'current_year' => date('Y'),
            'verification_url' => config('app.url') . '/verify-email?token=test-token',
            'reset_url' => config('app.url') . '/reset-password?token=test-token',
            'license_key' => 'LIC-' . strtoupper(substr(md5(time()), 0, 8)),
            'product_name' => 'Test Product',
            'expires_at' => now()->addYear()->format('M d, Y'),
            'days_remaining' => 30,
            'ticket_id' => '12345',
            'ticket_subject' => 'Test Support Ticket',
            'invoice_number' => 'INV-001',
            'invoice_amount' => '99.99',
            'due_date' => now()->addDays(7)->format('M d, Y'),
            'payment_date' => now()->format('M d, Y'),
            'payment_method' => 'Credit Card',
        ];

        $testData = array_merge($defaultData, $testData);

        try {
            $rendered = $emailTemplate->render($testData);
        } catch (\Exception $e) {
            $rendered = [
                'subject' => 'Error rendering template',
                'body' => 'Error: ' . $e->getMessage(),
            ];
        }

        return view('admin.email-templates.test', compact(
            'emailTemplate',
            'testData',
            'rendered'
        ));
    }

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

        $testData = $request->get('test_data', []);
        
        // Add default test data
        $defaultData = [
            'user_name' => 'Test User',
            'user_email' => $request->test_email,
            'site_name' => config('app.name'),
            'site_url' => config('app.url'),
            'current_year' => date('Y'),
        ];

        $testData = array_merge($defaultData, $testData);

        try {
            $emailService = app(\App\Services\EmailService::class);
            
            // Log the test attempt
            \Log::info('Email test attempt', [
                'template' => $emailTemplate->name,
                'recipient' => $request->test_email,
                'test_data' => $testData
            ]);
            
            $success = $emailService->sendEmail(
                $emailTemplate->name,
                $request->test_email,
                $testData,
                'Test User'
            );

            if ($success) {
                \Log::info('Email test sent successfully', [
                    'template' => $emailTemplate->name,
                    'recipient' => $request->test_email
                ]);
                
                return redirect()
                    ->back()
                    ->with('success', 'Test email sent successfully.');
            } else {
                \Log::error('Email test failed - service returned false', [
                    'template' => $emailTemplate->name,
                    'recipient' => $request->test_email
                ]);
                
                return redirect()
                    ->back()
                    ->with('error', 'Failed to send test email. Please check the logs for more details.');
            }
        } catch (\Exception $e) {
            \Log::error('Email test exception', [
                'template' => $emailTemplate->name,
                'recipient' => $request->test_email,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return redirect()
                ->back()
                ->with('error', 'Error sending test email: ' . $e->getMessage());
        }
    }
}