<?php

namespace Modules\MedNotify\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedNotify\Entities\MednotifyEvent;
use Modules\MedNotify\Entities\MednotifyTemplate;

/**
 * Templates admin — per event × channel body editing with variable hints, an
 * enable toggle and reset-to-default. A tenant edit creates/updates a
 * business-scoped override row; the system default (business_id NULL) is never
 * mutated. Reset deletes the override so the system default takes over again.
 */
class TemplateController extends MedNotifyBaseController
{
    public function index()
    {
        $this->guard('mednotify.templates.manage');

        $businessId = $this->businessId();
        $events = $this->events($businessId);

        return view('mednotify::templates.index', [
            'events'   => $events,
            'channels' => $this->channels(),
        ]);
    }

    /**
     * Edit form for one event × channel (returned into the modal). Shows the
     * effective template (business override else system default) plus the
     * event's available variable hints.
     */
    public function edit(Request $request)
    {
        $this->guard('mednotify.templates.manage');

        $businessId = $this->businessId();
        $eventKey = (string) $request->get('event_key');
        $channel = (string) $request->get('channel');

        $event = MednotifyEvent::resolve($businessId, $eventKey);
        if (! $event || ! in_array($channel, $this->channels(), true)) {
            abort(404);
        }

        $template = MednotifyTemplate::resolve($businessId, $eventKey, $channel);
        $isOverride = $template && (int) $template->business_id === $businessId;

        return view('mednotify::templates.edit', [
            'event'      => $event,
            'channel'    => $channel,
            'template'   => $template,
            'isOverride' => $isOverride,
            'variables'  => $event->available_variables ?? [],
        ]);
    }

    /** Persist a business override for one event × channel. */
    public function update(Request $request)
    {
        $this->guard('mednotify.templates.manage');

        $data = $this->validate($request, [
            'event_key' => 'required|string|max:100',
            'channel'   => 'required|in:in_app,email,sms,whatsapp',
            'subject'   => 'nullable|string|max:191',
            'body'      => 'required|string',
            'enabled'   => 'nullable',
        ]);

        try {
            $businessId = $this->businessId();

            $event = MednotifyEvent::resolve($businessId, $data['event_key']);
            if (! $event) {
                return $this->fail(__('mednotify::lang.unknown_event'));
            }

            MednotifyTemplate::updateOrCreate(
                [
                    'business_id' => $businessId,
                    'event_key'   => $data['event_key'],
                    'channel'     => $data['channel'],
                ],
                [
                    'subject' => $data['subject'] ?? null,
                    'body'    => $data['body'],
                    'enabled' => $request->boolean('enabled', true),
                ]
            );

            return $this->ok(__('mednotify::lang.template_saved'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** Reset to the shipped default: delete the business override row. */
    public function reset(Request $request)
    {
        $this->guard('mednotify.templates.manage');

        $data = $this->validate($request, [
            'event_key' => 'required|string|max:100',
            'channel'   => 'required|in:in_app,email,sms,whatsapp',
        ]);

        try {
            MednotifyTemplate::where('business_id', $this->businessId())
                ->where('event_key', $data['event_key'])
                ->where('channel', $data['channel'])
                ->delete();

            return $this->ok(__('mednotify::lang.template_reset'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** System events + this business's overrides, effective-resolved for display. */
    protected function events(int $businessId)
    {
        return MednotifyEvent::where(function ($q) use ($businessId) {
            $q->where('business_id', $businessId)->orWhereNull('business_id');
        })
            ->orderBy('module_key')
            ->orderBy('event_key')
            ->get()
            ->unique('event_key')
            ->values();
    }
}
