<?php

namespace App\Http\Resources;

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

class UserResource 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);
        $postCount = Post::where('user_id', Auth::id())->get()->count();
        return [
            "id" => $this->id,
            "uid" => $this->uid,
            "email" => $this->email,
            "email_verified_at" => $this->email_verified_at,
            "name" => $this->name,
            "bio" => $this->bio,
            "phone" => $this->phone,
            "is_phone_verified" => $this->is_phone_verified,
            "image_url" => $this->image_url,
            "province_id" => $this->province_id,
            "province_name" => $this->province?->name_en,
            "latitude" => $this->latitude,
            "longitude" => $this->longitude,
            "cm_firebase_token" => $this->cm_firebase_token,
            "type" => $this->type,
            "following_count" => $this->following_count,
            "follower_count" => $this->follower_count,
            "post_count" => $postCount,
            "status" => $this->status,
            "created_at" => $this->created_at,
            "token" => $this->token,
        ];


    }

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