<?php

namespace App\Http\Controllers\Admin;

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

class EmailTemplateController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $templates = \App\Models\EmailTemplate::all();
        
        $logicMap = [
            'seller-welcome' => 'Sent immediately after a new seller registers.',
            'admin-new-seller' => 'Sent to Admin when a new seller registers.',
            'buyer-welcome' => 'Sent immediately after a new buyer registers.',
            'seller-profile-updated' => 'Sent to Seller when their profile is updated (Security Alert).',
            'seller-verified' => 'Sent to Seller when their KYC is approved by Admin.',
            'kyc-rejected' => 'Sent to Seller when their KYC document is rejected.',
            'seller-rejected' => 'Sent to Seller when their account application is rejected.',
            'product-approved' => 'Sent to Seller when their product is approved.',
            'product-rejected' => 'Sent to Seller when their product is rejected.',
            'subscription-activated' => 'Sent to Seller when their subscription payment is successful.',
            'promotion-activated' => 'Sent to Seller when their promotion package is activated.',
            'subscription-expiring' => 'Sent to Seller 3-7 days before subscription expiry.',
            'subscription-expired' => 'Sent to Seller when subscription expires.',
            'rfq-posted-confirmation' => 'Sent to Buyer confirming their RFQ submission.',
            'admin-new-rfq' => 'Sent to Admin when a new RFQ is posted.',
            'new-rfq-notification' => 'Sent to relevant Sellers when a matching RFQ is posted.',
            'new-inquiry-received' => 'Sent to Seller when a Buyer sends an inquiry.',
            'inquiry-confirmation' => 'Sent to Buyer confirming their inquiry was sent.',
            'quote-submitted' => 'Sent to Buyer when a Seller submits a quote.',
            'quote-revised' => 'Sent to Buyer when a Seller revises a quote.',
            'quote-accepted' => 'Sent to Seller when Buyer accepts their quote.',
            'quote-rejected' => 'Sent to Seller when Buyer rejects their quote.',
            'payment-failed' => 'Sent to User when a payment transaction fails.',
        ];

        return view('admin.email_templates.index', compact('templates', 'logicMap'));
    }

    public function create()
    {
        return view('admin.email_templates.create');
    }

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

        \App\Models\EmailTemplate::create($request->all());

        return redirect()->route('admin.email_templates.index')->with('success', 'Email template created successfully.');
    }

    public function edit(\App\Models\EmailTemplate $emailTemplate)
    {
        return view('admin.email_templates.edit', compact('emailTemplate'));
    }

    public function update(Request $request, \App\Models\EmailTemplate $emailTemplate)
    {
        $request->validate([
            'subject' => 'required|string|max:255',
            'body' => 'required|string',
            'is_active' => 'boolean',
        ]);

        $emailTemplate->update($request->only('subject', 'body', 'is_active'));

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

    public function toggleStatus(\App\Models\EmailTemplate $emailTemplate)
    {
        $emailTemplate->update(['is_active' => !$emailTemplate->is_active]);
        return redirect()->back()->with('success', 'Template status updated.');
    }

    public function test(Request $request, \App\Models\EmailTemplate $emailTemplate)
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $recipient = $request->email;
        
        // Mock data for testing variables
        $mockData = [];
        if ($emailTemplate->variables) {
            foreach ($emailTemplate->variables as $var) {
                $mockData[$var] = "[TEST_{{ strtoupper($var) }}]";
            }
        }

        $sent = \App\Services\EmailService::send($emailTemplate->slug, $recipient, $mockData);

        if ($sent) {
            return redirect()->back()->with('success', "Test email sent to {$recipient}");
        } else {
            return redirect()->back()->with('error', "Failed to send test email. Check logs.");
        }
    }
}
