<?php

namespace App\Http\Controllers;

use App\Models\DocumentTemplate;
use Illuminate\Http\Request;

class DocumentTemplateController extends Controller
{
    public function index()
    {
        $templates = DocumentTemplate::with('creator')->latest()->paginate(20);
        return view('admin.document-generator.templates.index', compact('templates'));
    }

    public function create()
    {
        return view('admin.document-generator.templates.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:commercial_invoice,packing_list,certificate_origin,bill_of_lading,inspection_certificate,shipping_label',
            'content' => 'required|string',
            'variables' => 'nullable|array',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
        ]);

        if ($validated['is_default'] ?? false) {
            DocumentTemplate::where('type', $validated['type'])->update(['is_default' => false]);
        }

        $validated['created_by'] = auth()->id();
        DocumentTemplate::create($validated);

        return redirect()->route('admin.document-templates.index')
            ->with('success', 'Template created successfully.');
    }

    public function edit(DocumentTemplate $documentTemplate)
    {
        return view('admin.document-generator.templates.edit', compact('documentTemplate'));
    }

    public function update(Request $request, DocumentTemplate $documentTemplate)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:commercial_invoice,packing_list,certificate_origin,bill_of_lading,inspection_certificate,shipping_label',
            'content' => 'required|string',
            'variables' => 'nullable|array',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
        ]);

        if ($validated['is_default'] ?? false) {
            DocumentTemplate::where('type', $validated['type'])
                ->where('id', '!=', $documentTemplate->id)
                ->update(['is_default' => false]);
        }

        $documentTemplate->update($validated);

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

    public function destroy(DocumentTemplate $documentTemplate)
    {
        $documentTemplate->delete();

        return redirect()->route('admin.document-templates.index')
            ->with('success', 'Template deleted successfully.');
    }

    public function setDefault(DocumentTemplate $documentTemplate)
    {
        DocumentTemplate::where('type', $documentTemplate->type)
            ->update(['is_default' => false]);

        $documentTemplate->update(['is_default' => true]);

        return back()->with('success', 'Template set as default successfully.');
    }
}