<?php

namespace App\Http\Controllers\Concerns;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Redirect;

trait FlashesToasts
{
    protected function toast(Request $request, string $message, string $type = 'success')
    {
        if ($request->header('HX-Request')) {
            return response('', 204)->header('HX-Trigger', json_encode([
                'toast' => ['message' => $message, 'type' => $type],
            ]));
        }

        // for normal requests, just flash to session
        return Redirect::back()->with('toast', [
            'message' => $message,
            'type' => $type ]);
    }

    protected function redirectWithToast(Request $request, string $routeName, string $message, string $type = 'success')
    {
        if ($request->header('HX-Request')) {
            // optionally: you can HX-Redirect and also trigger toast
            return response('', 204)
                ->header('HX-Redirect', route($routeName))
                ->header('HX-Trigger', json_encode([
                    'toast' => ['message' => $message, 'type' => $type],
                ]));
        }

        return Redirect::route($routeName)->with('toast', [
            'message' => $message,
            'type' => $type ]);
    }
}
