<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Services\API\ProductService;

class ProductDetailResource extends JsonResource
{
    public static $wrap = false;

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $lang = $request->header('Accept-Language') ?? 'ru';
        $service = new ProductService($this);

        // get currency from cache
        $currency = cache()->get('currency');

        if ($this->price_discount) {
            $discount_percent = 100 - round($this->price_discount / $this->price * 100);
        } else {
            $discount_percent = 0;
        }

        $in_cart = $this->in_cart;

        return [
            'id' => $this->id,
            'name' => $this->name[$lang],
            'price' => ceiling($this->price * $currency->dollar, 100),
            'price_usd' => $this->price,
            'price_discount' => ceiling($this->price_discount * $currency->dollar, 100),
            'price_discount_usd' => $this->price_discount,
            'discount_percent' => $discount_percent,
            'published' => $this->published,
            'is_ready_solution' => $this->is_ready_solution,
            'is_leader_of_sales' => $this->leader_of_sales,
            'poster' => $this->getPoster(),
            'poster_thumb' => $this->getPosterThumb(),
            "is_install" => $service->isInstall(),
            'is_favorite' => $this->is_favorite,
            'is_cart' => $this->is_cart,
            'is_available' => $this->count > 0 ? $this->available : false,
            'count' => $this->count,
            "measurement" => $this->measurement()->get()->first()?->getName(),
            'data_sheet' => $this->getDataSheet(),
            'screens' => $this->childrens->first() ? ProductScreenResource::collection($this->childrens->first()->screens) : [],
            'characteristics' => $this->characteristics->count() > 0 ? ProductCharacteristicResource::collection($this->characteristics) : null,
            'in_cart' => $in_cart,
            'short_description' => $this->short_body[$lang],
            'description' => $this->body[$lang],
        ];
    }
}
