<?php

namespace App\Http\Resources;

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

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        // Determine current selling price and old price
        // If discount_price is present and > 0, that's the selling price.
        $currentPrice = $this->discount_price > 0 ? $this->discount_price : $this->price;
        $oldPrice = $this->discount_price > 0 ? $this->price : null;

        return [
            'id' => (string) $this->id,
            'name' => $this->name,
            'description' => strip_tags((string) $this->description),
            'slug' => $this->slug,
            'seo_title' => $this->seo_title ?: $this->name,
            'seo_description' => $this->seo_description ?: Str::limit(strip_tags((string) $this->description), 155),
            'seo_keywords' => $this->seo_keywords,
            'price' => (float) $currentPrice,
            'oldPrice' => $oldPrice ? (float) $oldPrice : null,
            'imageUrl' => $this->getImageUrl(),
            'unit' => $this->unit,
            'reviews_avg_rating' => $this->reviews_avg_rating !== null ? (float) $this->reviews_avg_rating : null,
            'reviews_count' => (int) ($this->reviews_count ?? 0),
            'rating' => $this->reviews_avg_rating !== null ? (float) $this->reviews_avg_rating : 0,
            'isPopular' => (boolean) $this->is_featured,
            'categoryId' => (string) $this->category_id,
            'category_name' => optional($this->category)->name,
        ];
    }

    protected function getImageUrl()
    {
        if (!$this->image) {
            return null;
        }

        if (Str::startsWith($this->image, ['http://', 'https://'])) {
            return $this->image;
        }

        // Use the standard storage URL helper if possible, or fallback to the route
        // Ideally, this should use Storage::url($this->image)
        // But to keep consistency with existing logic, we can use the route helper
        // or switch to Storage::url() if the symbolic link is set up.
        // Given the critique, using the route helper is safer if we keep the route,
        // but let's try to be standard.
        // However, the original code used route('public.media').
        
        return route('public.media', ['path' => $this->image]);
    }
}
