<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

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

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

        // 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;
        }

        if ($this->product->price_discount) {
            $price_total = $this->product->price_discount * $this->count * $currency->dollar;
        } else {
            $price_total = $this->product->price * $this->count * $currency->dollar;
        }

        return [
            'id' => $this->id,
            'name' => $this->product->name[$lang],
            'price' => ceiling($this->product->price * $currency->dollar, 100),
            'price_usd' => floatval($this->product->price),
            'price_discount' => $this->product->price_discount != null ? $this->product->price_discount * $currency->dollar : null,
            'price_discount_usd' => floatval($this->product->price_discount != null ? ceiling($this->product->price_discount, 100) : null),
            'discount_percent' => $discount_percent,
            'price_total' => ceiling($price_total, 100),
            'poster' => $this->product->getPoster(),
            'poster_thumb' => $this->product->getPosterThumb(),
            'count' => $this->count,
            'available_count' => $this->product->count,
            'is_available' => $this->product->count <= $this->count ? false : true,
            'product_id' => $this->product->id,
            'product_count' => $this->product->count,
        ];
    }
}
