<?php

namespace App\Http\Resources;

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Resources\Json\JsonResource;

class DefaultResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $attr = $this->resource->toArray();

        $attr = $this->formatValidUTF8($attr);

        $table = $this->resource->getTable();

        return [
            'type' => $table,
            'id' => (string) $this->resource->getRouteKey(),
            'attributes' => $attr,
            'links' => [
                'self' => $this->getShowRoute($this->resource->getRouteKey(), $table)
            ]
        ];
    }

    private function formatValidUTF8($data)
    {
        $json = json_encode($data, JSON_INVALID_UTF8_SUBSTITUTE | JSON_UNESCAPED_UNICODE);

        if ($json === false) {
            return $data;
        }

        $decoded = json_decode($json, true);

        return is_array($decoded) ? $decoded : $data;
    }

    private function getShowRoute($key, $table)
    {
        $route_name = "api.v1.{$table}.show";
        if (Route::has($route_name)) {

            $route = route($route_name, $key);
            return asset($route);
        }
    }
    public function toResponse($request)
    {
        $table = $this->resource->getTable();

        return parent::toResponse($request)->withHeaders([
            'Location' => $this->getShowRoute($this->resource->getRouteKey(), $table)
        ]);
    }
}
