<?php

namespace App\Http\Controllers\Settings;

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

class WhatsAppTemplateController extends Controller
{
    public function index()
    {
        $templates = WhatsAppTemplate::latest()->paginate(10);
        return view('settings.system.whatsapp.index', compact('templates'));
    }

    public function create()
    {
        return view('settings.system.whatsapp.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'key' => 'required|string|max:255|unique:whatsapp_templates',
            'content' => 'required|string',
            'variables' => 'nullable|string',
        ]);

        WhatsAppTemplate::create($validated);

        return redirect()->route('settings.whatsapp.index')->with('success', 'Template created successfully.');
    }

    public function edit(WhatsAppTemplate $template)
    {
        return view('settings.system.whatsapp.edit', compact('template'));
    }

    public function update(Request $request, WhatsAppTemplate $template)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'key' => 'required|string|max:255|unique:whatsapp_templates,key,' . $template->id,
            'content' => 'required|string',
            'variables' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $template->update($validated);

        return redirect()->route('settings.whatsapp.index')->with('success', 'Template updated successfully.');
    }

    public function destroy(WhatsAppTemplate $template)
    {
        $template->delete();
        return back()->with('success', 'Template deleted successfully.');
    }
}
