<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\ConsentTemplate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ConsentTemplateController extends Controller
{
    public function index(): View
    {
        $templates = ConsentTemplate::latest()->paginate(15);

        return view('tenant.consent-templates.index', compact('templates'));
    }

    public function create(): View
    {
        return view('tenant.consent-templates.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'title'               => ['required', 'string', 'max:255'],
            'content'             => ['required', 'string'],
            'requires_signature'  => ['boolean'],
            'is_active'           => ['boolean'],
        ]);

        ConsentTemplate::create($data + ['created_by' => auth()->id()]);

        return redirect()->route('tenant.consent-templates.index')
            ->with('success', 'Plantilla de consentimiento creada.');
    }

    public function edit(ConsentTemplate $consentTemplate): View
    {
        return view('tenant.consent-templates.edit', ['template' => $consentTemplate]);
    }

    public function update(Request $request, ConsentTemplate $consentTemplate): RedirectResponse
    {
        $data = $request->validate([
            'title'              => ['required', 'string', 'max:255'],
            'content'            => ['required', 'string'],
            'requires_signature' => ['boolean'],
            'is_active'          => ['boolean'],
        ]);

        $consentTemplate->update($data);

        return back()->with('success', 'Plantilla actualizada.');
    }

    public function destroy(ConsentTemplate $consentTemplate): RedirectResponse
    {
        $consentTemplate->delete();

        return redirect()->route('tenant.consent-templates.index')
            ->with('success', 'Plantilla eliminada.');
    }
}
