<?php

namespace App\Http\Controllers\Admin;

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

class NotificationTemplateController extends Controller
{
    /**
     * Display email templates.
     */
    public function emailIndex(Request $request)
    {
        $query = EmailTemplate::query();

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

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }

        $templates = $query->paginate(15);
        $categories = EmailTemplate::distinct()->pluck('category');

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

    /**
     * Create email template.
     */
    public function emailCreate()
    {
        return view('admin.notifications.email-templates.create');
    }

    /**
     * Store email template.
     */
    public function emailStore(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:email_templates,name',
            'slug' => 'required|string|max:255|unique:email_templates,slug',
            'category' => 'required|string|max:100',
            'subject' => 'required|string|max:255',
            'html_body' => 'required|string',
            'text_body' => 'nullable|string',
            'available_variables' => 'nullable|array',
            'is_active' => 'boolean',
        ]);

        $template = EmailTemplate::create([
            ...$validated,
            'created_by' => auth()->id(),
        ]);

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

    /**
     * Show email template.
     */
    public function emailShow(EmailTemplate $emailTemplate)
    {
        return view('admin.notifications.email-templates.show', ['template' => $emailTemplate]);
    }

    /**
     * Edit email template.
     */
    public function emailEdit(EmailTemplate $emailTemplate)
    {
        return view('admin.notifications.email-templates.edit', ['template' => $emailTemplate]);
    }

    /**
     * Update email template.
     */
    public function emailUpdate(Request $request, EmailTemplate $emailTemplate)
    {
        $validated = $request->validate([
            'name' => "required|string|max:255|unique:email_templates,name,{$emailTemplate->id}",
            'category' => 'required|string|max:100',
            'subject' => 'required|string|max:255',
            'html_body' => 'required|string',
            'text_body' => 'nullable|string',
            'available_variables' => 'nullable|array',
            'is_active' => 'boolean',
        ]);

        $emailTemplate->update([
            ...$validated,
            'updated_by' => auth()->id(),
        ]);

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

    /**
     * Delete email template.
     */
    public function emailDestroy(EmailTemplate $emailTemplate)
    {
        $emailTemplate->delete();

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

    /**
     * Preview email template.
     */
    public function emailPreview(Request $request, EmailTemplate $emailTemplate)
    {
        $testData = $request->get('data', []);

        $rendered = $emailTemplate->render($testData);

        return view('admin.notifications.email-templates.preview', [
            'template' => $emailTemplate,
            'subject' => $rendered['subject'],
            'body' => $rendered['body'],
        ]);
    }

    // =============== SMS TEMPLATES ===============

    /**
     * Display SMS templates.
     */
    public function smsIndex(Request $request)
    {
        $query = SmsTemplate::query();

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

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }

        $templates = $query->paginate(15);
        $categories = SmsTemplate::distinct()->pluck('category');

        return view('admin.notifications.sms-templates.index', compact('templates', 'categories'));
    }

    /**
     * Create SMS template.
     */
    public function smsCreate()
    {
        return view('admin.notifications.sms-templates.create');
    }

    /**
     * Store SMS template.
     */
    public function smsStore(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:sms_templates,name',
            'slug' => 'required|string|max:255|unique:sms_templates,slug',
            'category' => 'required|string|max:100',
            'content' => 'required|string|max:160',
            'available_variables' => 'nullable|array',
            'is_active' => 'boolean',
        ]);

        $template = SmsTemplate::create([
            ...$validated,
            'character_count' => strlen($validated['content']),
            'created_by' => auth()->id(),
        ]);

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

    /**
     * Show SMS template.
     */
    public function smsShow(SmsTemplate $smsTemplate)
    {
        return view('admin.notifications.sms-templates.show', ['template' => $smsTemplate]);
    }

    /**
     * Edit SMS template.
     */
    public function smsEdit(SmsTemplate $smsTemplate)
    {
        return view('admin.notifications.sms-templates.edit', ['template' => $smsTemplate]);
    }

    /**
     * Update SMS template.
     */
    public function smsUpdate(Request $request, SmsTemplate $smsTemplate)
    {
        $validated = $request->validate([
            'name' => "required|string|max:255|unique:sms_templates,name,{$smsTemplate->id}",
            'category' => 'required|string|max:100',
            'content' => 'required|string|max:160',
            'available_variables' => 'nullable|array',
            'is_active' => 'boolean',
        ]);

        $smsTemplate->update([
            ...$validated,
            'character_count' => strlen($validated['content']),
            'updated_by' => auth()->id(),
        ]);

        return redirect()->route('admin.notifications.sms-templates.show', $smsTemplate)
            ->with('success', 'SMS template updated successfully.');
    }

    /**
     * Delete SMS template.
     */
    public function smsDestroy(SmsTemplate $smsTemplate)
    {
        $smsTemplate->delete();

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

    /**
     * Preview SMS template.
     */
    public function smsPreview(Request $request, SmsTemplate $smsTemplate)
    {
        $testData = $request->get('data', []);
        $rendered = $smsTemplate->render($testData);

        return view('admin.notifications.sms-templates.preview', [
            'template' => $smsTemplate,
            'content' => $rendered,
            'character_count' => strlen($rendered),
        ]);
    }
}

