<?php

namespace Inside\DESK\Http\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inside\Content\Facades\Schema;
use Inside\Content\Models\Contents\ImageStyles;
use Inside\Content\Models\Contents\Tools;
use Inside\Content\Models\Contents\Users;

/**
 * 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 ToolsMiddleware
{
    /**
     * 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/content/users') !== 0) {
            return $next($request);
        }

        $response = $next($request);

        $content = $response->getContent();

        $content = json_decode($content, true);

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

        $filters = $request->get('filters');

        if (!empty($filters)) {
            $filters = json_decode($filters, true);
        } else {
            $filters = [];
        }

        foreach ($content['data'] as $key => &$data) {
            if ((!array_key_exists('uuid', $data) && !array_key_exists('uuid', $filters)) || !array_key_exists('tools', $data)) {
                continue;
            }

            $uuid = $data['uuid'] ?? $filters['uuid'];
            $user = Users::query()->find($uuid);

            if (!$user) {
                continue;
            }

            $toolsText = !empty($user->tools_text) ? $user->tools_text : '[]';
            $toolsText = json_decode($toolsText);

            if (!is_array($toolsText)) {
                $toolsText = [];
            }

            $data['tools']['data'] = [];

            foreach ($toolsText as $toolUuid) {
                $tool = Tools::query()->find($toolUuid);

                if (!$tool instanceof Tools) {
                    continue;
                }

                if ($tool->langcode !== $user->langcode) {
                    $tool = $tool->getTranslationIfExists($user->langcode);

                    if (!$tool instanceof Tools || $tool->langcode !== $user->langcode) {
                        continue;
                    }
                }

                $data['tools']['data'][] = [
                    'uuid' => $tool->uuid,
                    'title' => $tool->title,
                    'slug' => $tool->slug,
                    'logo' => $this->handleImage($tool),
                    'tools_link' => $this->handleLink($tool),
                ];
            }
        }

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

        return $response;
    }

    protected function handleLink(Tools $tool): string
    {
        $url = $tool->tools_link;
        $info = parse_url($url) ?: [];
        $external = (isset($info['host'], $info['scheme']) && $info['scheme'] . '://' . $info['host'] !== env('APP_URL'));
        $fragment = '';

        if (isset($info['fragment'])) {
            if (($fragment = trim($info['fragment'])) != '') {
                $fragment = '#' . $fragment;
            }
        }

        $link = !$external && isset($info['path']) ? ($info['path'] . $fragment) : $url;

        return $link;
    }

    protected function handleImage(Tools $tool): ?array
    {
        $value = $tool->logo;

        if (empty($value)) {
            return null;
        }

        $original = $value;
        $value = protected_file_url($tool, 'logo'); // @phpstan-ignore-line
        $realpath = Storage::disk('local')->path($original);
        $value = [
            'main' => $value,
        ];

        // Add styled image
        $options = Schema::getFieldOptions(class_to_type($tool), 'logo');
        if (isset($options['image_styles']) && !empty($options['image_styles'])) {
            $styles = ImageStyles::find($options['image_styles']);
            foreach ($styles as $style) {
                $value[Str::slug($style->title)] = protected_file_url($tool, 'logo', true, $style->title); // @phpstan-ignore-line
            }
        }

        return $value;
    }
}
