<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ReminderType;
use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use App\Services\EmailTemplateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ReminderEmailTemplateController extends Controller
{
    public function __construct(
        private EmailTemplateService $emailTemplateService
    ) {
        $this->middleware('permission:manage_email_templates');
    }

    public function index(Request $request): View
    {
        $slugs = array_map(fn (ReminderType $t) => $t->templateSlug(), ReminderType::cases());

        $q = EmailTemplate::query()
            ->whereIn('slug', $slugs)
            ->orderBy('module')
            ->orderBy('name');

        if ($request->filled('module')) {
            $q->where('module', $request->get('module'));
        }

        $templates = $q->paginate(20)->withQueryString();

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

    public function edit(EmailTemplate $emailTemplate): View
    {
        return view('admin.reminders.email-templates.edit', ['template' => $emailTemplate]);
    }

    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',
        ]);

        $validated['is_active'] = $request->boolean('is_active');
        $validated['body'] = $this->emailTemplateService->sanitizeBody($validated['body']);

        $emailTemplate->update($validated);

        return redirect()->route('admin.reminders.email-templates.index')->with('success', 'Template updated.');
    }

    public function preview(Request $request, EmailTemplate $emailTemplate)
    {
        $request->validate([
            'sample_customer_name' => 'nullable|string|max:255',
            'subject' => 'nullable|string|max:255',
            'body' => 'nullable|string|max:500000',
        ]);

        $subjectTpl = $request->filled('subject') ? (string) $request->get('subject') : $emailTemplate->subject;
        $bodyTpl = $request->filled('body') ? (string) $request->get('body') : $emailTemplate->body;

        $sample = [
            'customer_name' => $request->get('sample_customer_name', 'Sample Customer'),
            'company_name' => 'Demo Company Ltd',
            'company_email' => 'billing@example.com',
            'company_phone' => '+1 555 0100',
            'company_address' => '123 Main St',
            'today_date' => now()->format('M j, Y'),
            'invoice_number' => 'INV-1001',
            'invoice_total' => '1,250.00',
            'invoice_due_date' => now()->addDays(7)->format('M j, Y'),
            'invoice_status' => 'Unpaid',
            'invoice_balance' => '1,250.00',
            'invoice_view_link' => url('/'),
            'quotation_number' => 'QT-2001',
            'quotation_total' => '900.00',
            'quotation_expiry_date' => now()->addDays(14)->format('M j, Y'),
            'quotation_view_link' => url('/'),
            'payment_amount' => '500.00',
            'payment_date' => now()->format('M j, Y'),
            'payment_reference' => 'PAY-0001',
            'purchase_order_number' => 'PO-3001',
            'supplier_name' => 'Sample Supplier',
            'purchase_total' => '2,000.00',
        ];

        $subject = $this->emailTemplateService->apply($subjectTpl, $sample);
        $body = $this->emailTemplateService->apply($this->emailTemplateService->sanitizeBody($bodyTpl), $sample);

        return response()->json(['subject' => $subject, 'body' => $body]);
    }

    public function reset(EmailTemplate $emailTemplate): RedirectResponse
    {
        \Illuminate\Support\Facades\Artisan::call('db:seed', [
            '--class' => 'Database\\Seeders\\ReminderSystemSeeder',
            '--force' => true,
        ]);

        $fresh = EmailTemplate::query()->where('slug', $emailTemplate->slug)->first();

        return redirect()->route('admin.reminders.email-templates.edit', $fresh ?? $emailTemplate)
            ->with('success', 'Template reset from default seeder content.');
    }
}
