<?php

namespace App\Http\Resources;

use App\Models\PostBookmark;
use App\Models\PostLike;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        // return parent::toArray($request);

        $isLiked = PostLike::where('user_id',Auth::id())->where('post_id',$this->id)->count() > 0 ? true : false;
        $isBookmarked = PostBookmark::where('user_id',Auth::id())->where('post_id',$this->id)->count() > 0 ? true : false;

        return [
            'id' => $this->id,
            //attributes
            'image_url'  => $this->image_url,
            'latitude'  => $this->latitude,
            'longitude'  => $this->longitude,
            'place_id'  => $this->place_id,
            'google_place_name'  => $this->google_place_name,
            'google_place_id'  => $this->google_place_id,
            'google_place_url'  => $this->google_place_url,
            'google_place_address'  => $this->google_place_address,
            'description'  => $this->description,
            // 'like_count'  => $this->like_count,
            // 'comment_count'  => $this->comment_count,
            'language_code'  => $this->language_code,
            'enable_comment'  => $this->enable_comment,
            'is_public'  => $this->is_public,
            'active'  => $this->active,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,


            //relationship
            'user_id'       => $this->user_id,
            'user_name'     => $this->user?->name,
            'user_image_url'=> $this->user?->image_url,
            'user'          => $this->user,
            'post_images'   => $this->images,
            'province_id'   => $this->province_id,
            'province_name' => $this->province?->name_en,
            'like_count'    => $this->likes?->count(),
            'comment_count' => $this->comments?->count(),
            'is_liked'      => $isLiked,
            'is_bookmarked' => $isBookmarked,
            'current_user_id' => Auth::id(),
        ];
    }

    public function withResponse($request, $response)
    {
        $charset = $request->header('Accept-Charset', 'utf-8');
        if ($charset === 'utf-8') {
            $response->header('Charset', 'utf-8');
            $response->header('Content-Type','application/json; charset=utf-8');
            $response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
    }
}
