<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\WhatsApp\DefaultTemplates;
use App\Enums\WaTemplateKey;
use App\Http\Controllers\Controller;
use App\Models\WaTemplate;
use App\Support\Tenancy;
use Illuminate\Http\Request;

class WaTemplateController extends Controller
{
    public function index(Tenancy $tenancy)
    {
        abort_unless(auth()->user()->can('settings.manage'), 403);

        $tenant = $tenancy->get();
        $existing = WaTemplate::where('tenant_id', $tenant->id)->get()->keyBy('key');
        $defaults = DefaultTemplates::all();

        $templates = collect(WaTemplateKey::cases())->map(function (WaTemplateKey $key) use ($existing, $defaults) {
            $row = $existing->get($key->value);

            return [
                'key' => $key->value,
                'label' => $key->label(),
                'tokens' => $key->tokens(),
                'body_ar' => $row->body_ar ?? $defaults[$key->value]['ar'],
                'body_en' => $row->body_en ?? $defaults[$key->value]['en'],
                'enabled' => $row->enabled ?? true,
            ];
        });

        return view('whatsapp.templates', compact('templates'));
    }

    public function update(Request $request, string $key)
    {
        abort_unless(auth()->user()->can('settings.manage'), 403);
        abort_unless(in_array($key, array_column(WaTemplateKey::cases(), 'value'), true), 404);

        $data = $request->validate([
            'body_ar' => ['required', 'string', 'max:4000'],
            'body_en' => ['required', 'string', 'max:4000'],
            'enabled' => ['sometimes', 'boolean'],
        ]);

        WaTemplate::updateOrCreate(
            ['tenant_id' => app(Tenancy::class)->id(), 'key' => $key],
            [
                'body_ar' => $data['body_ar'],
                'body_en' => $data['body_en'],
                'enabled' => $request->boolean('enabled'),
            ],
        );

        return back()->with('status', __('Template saved.'));
    }
}
