<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'user_id' => $this->user_id,
            'total_amount' => (float) $this->total_amount,
            'status' => $this->status,
            'payment_method' => $this->payment_method,
            'payment_status' => $this->payment_status,
            'payment_id' => $this->payment_id,
            'shipping_address' => $this->shipping_address,
            'billing_address' => $this->billing_address,
            'shipping_method' => $this->shipping_method,
            'shipping_cost' => (float) $this->shipping_cost,
            'tax_amount' => (float) $this->tax_amount,
            'discount_amount' => (float) $this->discount_amount,
            'tracking_number' => $this->tracking_number,
            'notes' => $this->notes,
            'subtotal' => (float) $this->subtotal,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
            'products' => $this->when($this->relationLoaded('products'), function() {
                return $this->products->map(function($product) {
                    return [
                        'id' => $product->id,
                        'name' => $product->name,
                        'price' => (float) $product->pivot->price,
                        'quantity' => $product->pivot->quantity,
                        'total' => (float) ($product->pivot->price * $product->pivot->quantity),
                        'image' => optional($product->media->first())->file_path 
                            ? asset('storage/' . $product->media->first()->file_path) 
                            : null,
                        'store' => $this->when($product->relationLoaded('store'), function() use ($product) {
                            return [
                                'id' => $product->store->id,
                                'name' => $product->store->name,
                            ];
                        }),
                        'is_reviewed' => $product->pivot->is_reviewed ?? false,
                        'status' => $product->pivot->status
                    ];
                });
            }),
        ];
    }
} 