<?php

namespace Modules\WhatsApp\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\WhatsApp\Entities\WaTemplate;

class WaTemplateController extends Controller
{
    public function index()
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        // Seed starter templates on first visit.
        \Modules\WhatsApp\Entities\Services\DefaultTemplates::ensure($businessId);

        $templates = WaTemplate::where('business_id', $businessId)->orderBy('name')->get();
        $tags = $this->availableTags();

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

    public function store(Request $request)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        $data = $this->validateTemplate($request, $businessId);
        $data['business_id'] = $businessId;
        $data['variables'] = $this->splitVars($request->input('variables'));

        WaTemplate::create($data);

        return redirect()->route('whatsapp.templates.index')->with('status', [
            'success' => 1, 'msg' => __('whatsapp::lang.saved'),
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        $template = WaTemplate::where('business_id', $businessId)->findOrFail($id);
        $data = $this->validateTemplate($request, $businessId, $template->id);
        $data['variables'] = $this->splitVars($request->input('variables'));

        $template->update($data);

        return redirect()->route('whatsapp.templates.index')->with('status', [
            'success' => 1, 'msg' => __('whatsapp::lang.saved'),
        ]);
    }

    public function destroy($id)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        WaTemplate::where('business_id', $businessId)->findOrFail($id)->delete();

        return redirect()->route('whatsapp.templates.index')->with('status', [
            'success' => 1, 'msg' => __('whatsapp::lang.saved'),
        ]);
    }

    private function authorizeManage(): void
    {
        if (!auth()->user()->can('whatsapp.manage_templates')) {
            abort(403, 'Unauthorized action.');
        }
    }

    private function validateTemplate(Request $request, int $businessId, ?int $ignoreId = null): array
    {
        return $request->validate([
            'name'               => 'required|string|max:120',
            'language'           => 'required|string|max:12',
            'category'           => 'required|string|max:40',
            'meta_template_name' => 'nullable|string|max:160',
            'meta_status'        => 'required|in:none,pending,approved,rejected',
            'header'             => 'nullable|string',
            'body'               => 'required|string',
            'footer'             => 'nullable|string',
            'active'             => 'nullable|boolean',
        ]);
    }

    /** Tags supported by the core notification engine (Util::replaceTags). */
    private function availableTags(): array
    {
        return [
            '{contact_name}', '{business_name}', '{invoice_number}', '{order_ref_number}',
            '{total_amount}', '{paid_amount}', '{received_amount}', '{due_amount}',
            '{cumulative_due_amount}', '{due_date}', '{invoice_url}',
            '{location_name}', '{location_address}', '{location_phone}',
        ];
    }

    private function splitVars($raw): array
    {
        if (empty($raw)) {
            return [];
        }
        return array_values(array_filter(preg_split('/[\s,]+/', $raw, -1, PREG_SPLIT_NO_EMPTY)));
    }
}
