<?php

namespace Inside\DESK\Http\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Inside\Authentication\Models\User;
use Inside\Notify\Models\Notification;

/**
 * Handle custom workflow notification texts
 *
 * @category Class
 * @package  Inside\DESK\Http\Middleware\NotificationsMiddleware
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class NotificationsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $currentPath = $request->path();

        if (strpos($currentPath, 'api/v1/notifications') !== 0) {
            return $next($request);
        }

        $response = $next($request);

        $content = $response->getContent();

        $content = json_decode($content, true);

        if (empty($content['data'])) {
            return $response;
        }

        foreach ($content['data'] as $key => &$data) {
            $this->handleNotifications($data);
        }

        $response->setContent(json_encode($content));

        return $response;
    }

    protected function handleNotifications(array &$data): void
    {
        switch ($data['text']) {
            case 'notifications.workflow.proposals.edited.text':
                if (! array_key_exists('steps', $data)) {
                    break;
                }

                /** @var Notification $notification */
                $notification = Notification::query()->find($data['id']);
                $notification = $notification->toArray();

                $key = 'notifications.workflow';

                $data['content'] = Lang::getFromJson($key.'.approval.text', ['title' => $data['model']['title']]);

                break;
            case 'notifications.workflow.proposals.accepted.text':
                /** @var Notification $notification */
                $notification = Notification::query()->find($data['id']);
                $notification = $notification->toArray();
                $query = call_user_func($notification['notifiable_type'].'::withoutGlobalScopes');
                $model = $query->where('uuid', $notification['notifiable_uuid'])->first();

                $key = 'notifications.workflow';

                /** @var User $user */
                $user = Auth::user();

                if ($model->author === $user->uuid) {
                    $data['content'] = Lang::getFromJson($key.'.accepted.author.text', ['title' => $data['model']['title']]);
                } else {
                    $data['content'] = Lang::getFromJson($key.'.accepted.text', ['title' => $data['model']['title']]);
                }
                break;
        }
    }
}
