<?php

namespace App\Http\Resources;

use App\Models\Image;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductsResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $images = $this->images;
        return [
            'id'    =>  HashIdObj()->encode($this->id),
            'name_ar'   =>  $this->name_ar,
            'name_en'   =>  $this->name_en,
            'ar_description'   =>  $this->ar_description,
            'en_description'   =>  $this->en_description,
            'price' =>  $this->price,
            // 'price_after_discount'  =>  $this->price_after_discount,
            'ar_currency'  => optional($this->shop->country)->ar_currency,
            'en_currency'  => optional($this->shop->country)->en_currency,
            'discount_status'   =>  (boolean) 0,
            'is_active' =>  $this->is_active,
            'is_approved' =>  $this->is_approved,
            'favorite_count' =>  $this->favorite_count,
            'category'  =>  new CategoryResource($this->category),
            'is_favorite'   =>  $this->when(request()->user('sanctum'), function (){
                return $this->favorite()->where('user_id', request()->user('sanctum')->id)->exists();
            }),
            'default_image' =>  optional(optional(optional($images)->filter(function($image){ return $image->is_default;}))->first())->full_path,
            'images'    =>  optional(optional($images)->sortBy('order'))->map(function ($image){
                return [
                    'id'    =>  HashIdObj()->encode($image->id),
                    'full_path'    =>  $image->full_path,
                    'is_default'    =>  $image->is_default,
                    'order'    =>  $image->order,
                ];
            })->values(),
            'date_time' => $this->created_at,
            'declined' => $this->when(!$this->is_approved, [
                'declined' => !$this->is_approved,
                'reason' => $this->declined_reason,
            ])
        ];
    }

}
