<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\EmailTemplateDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreEmailTemplateRequest;
use App\Http\Requests\UpdateEmailTemplateRequest;
use App\Models\EmailTemplate;
use App\Services\EmailService;
use Illuminate\Http\Request;

class EmailTemplateController extends Controller
{
    public function __construct(protected EmailService $service)
    {
        $this->authorizeResource(EmailTemplate::class, 'email_template');
    }

    public function index()
    {
        return view('admin.email-templates.index');
    }

    public function data(Request $request, EmailTemplateDataTable $dataTable)
    {
        $this->authorize('viewAny', EmailTemplate::class);

        return $dataTable->render($request);
    }

    public function store(StoreEmailTemplateRequest $request)
    {
        $template = $this->service->createTemplate($request->validated());

        return response()->json(['success' => true, 'data' => $template], 201);
    }

    public function edit(EmailTemplate $email_template)
    {
        return response()->json([
            'data' => $email_template,
            'update_url' => route('admin.email-templates.update', $email_template),
        ]);
    }

    public function update(UpdateEmailTemplateRequest $request, EmailTemplate $email_template)
    {
        $this->service->updateTemplate($email_template, $request->validated());

        return response()->json(['success' => true, 'data' => $email_template->fresh()]);
    }

    public function destroy(EmailTemplate $email_template)
    {
        $email_template->delete();

        return response()->json(['success' => true]);
    }
}
