<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // Place this at the beginning to ensure Auth is used correctly
        $isUserLoggedIn = Auth::check();
        $currentUserId = $isUserLoggedIn ? Auth::id() : null;
        
        return [
            'id' => $this->id,
            
            // Basic Product Information
            'name' => $this->name,
            'description' => $this->description,
            'price' => (float) $this->price,
            'currency' => $this->currency,
            'type' => $this->type,
            'units' => $this->units,
            'status' => $this->status,
            
            // Inventory and Pricing
            'stock_quantity' => $this->stock_quantity,
            'sku' => $this->sku,
            'shipping_cost' => (float) $this->shipping_cost,
            'tax_rate' => (float) $this->tax_rate,
            'discount_percentage' => (float) $this->discount_percentage,
            'sale_price' => (float) $this->sale_price,
            'specifications' => $this->specifications,
            'warranty_info' => $this->warranty_info,
            
            // Location Details
            'location' => $this->location,
            
            // Category Information
            'category' => $this->whenLoaded('category', function() {
                return [
                    'id' => $this->category->id,
                    'name' => $this->category->name
                ];
            }),
            'category_id' => $this->category_id,
            
            // Seller and Store Information
            'user' => $this->whenLoaded('user', function() {
                return [
                    'id' => $this->user->id,
                    'name' => $this->user->name,
                    'profile_photo' => $this->user->profile_photo ? asset('storage/' . $this->user->profile_photo) : null
                ];
            }),
            'user_id' => $this->user_id,
            
            'store' => $this->whenLoaded('store', function() {
                return [
                    'id' => $this->store->id,
                    'name' => $this->store->name,
                    'logo' => $this->store->logo ? asset('storage/' . $this->store->logo) : null
                ];
            }),
            'store_id' => $this->store_id,
            
            // Media and Images
            'media' => $this->whenLoaded('media', function() {
                return $this->media->map(function($mediaItem) {
                    return [
                        'id' => $mediaItem->id,
                        'url' => $mediaItem->url,
                        'file_name' => $mediaItem->file_name,
                        'file_type' => $mediaItem->file_type,
                        'is_primary' => $mediaItem->is_primary
                    ];
                });
            }),
            'primary_image' => $this->whenLoaded('media', function () {
                $primaryImage = $this->media->where('is_primary', true)->first() ?? $this->media->first();
                return $primaryImage ? asset('storage/' . $primaryImage->file_path) : null;
            }),
            
            // Rating and Reviews
            'rating' => (float) $this->average_rating,
            'total_reviews' => $this->whenCounted('reviews'),
            'reviews' => $this->whenLoaded('reviews', function() {
                return $this->reviews->map(function($review) {
                    return [
                        'id' => $review->id,
                        'rating' => (float) $review->rating,
                        'comment' => $review->comment,
                        'is_recommended' => (bool) $review->is_recommended,
                        'created_at' => $review->created_at->format('Y-m-d H:i:s'),
                        'user' => [
                            'id' => $review->user->id,
                            'name' => $review->user->name,
                            'profile_photo' => $review->user->profile_photo ? asset('storage/' . $review->user->profile_photo) : null
                        ]
                    ];
                });
            }),
            
            // Sales Information
            'total_sales' => $this->total_sales,
            
            // Additional Features
            'is_featured' => (bool) $this->is_featured,
            'delivery_options' => $this->delivery_options,
            'views' => (int) $this->views,
            
            // Timestamps
            'created_at' => $this->created_at->toDateTimeString(),
            'updated_at' => $this->updated_at->toDateTimeString(),
            
            // User-specific flags
            'is_saved' => $this->when($isUserLoggedIn, function() use ($currentUserId) {
                return $this->isSavedBy($currentUserId);
            }, false),
            
            // Conditional relationships for detailed views
            'similar_products' => ProductResource::collection($this->whenLoaded('similarProducts')),
            'seller_products' => ProductResource::collection($this->whenLoaded('sellerProducts')),
        ];
    }
}