<?php

namespace App\Http\Resources\Api;

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

class OrderResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'number' => $this->number,
            'invoice_number' => $this->invoice_number,
            'user_id' => $this->user_id,
            'address_id' => $this->address_id,
            'subtotal' => (float) $this->subtotal,
            'delivery_fee' => (float) $this->delivery_fee,
            'total' => (float) $this->total,
            'status' => $this->status,
            'payment_status' => $this->payment_status,
            'paid_at' => $this->paid_at?->toIso8601String(),
            'created_at' => $this->created_at->toIso8601String(),
            'livreur_id' => $this->livreur_id,
            'delivery_status' => $this->delivery_status,
            'delivery_assigned_at' => $this->delivery_assigned_at?->toIso8601String(),
            'delivered_at' => $this->delivered_at?->toIso8601String(),
            'delivery_proof_url' => $this->delivery_proof_path
                ? url('storage/' . $this->delivery_proof_path)
                : null,
            'items' => $this->whenLoaded('items', fn () => $this->items->map(fn ($item) => [
                'id' => $item->id,
                'product_id' => $item->product_id,
                'product_name' => $item->product_name,
                'unit_price' => (float) $item->unit_price,
                'quantity' => $item->quantity,
                'total' => (float) $item->total,
            ])),
            'address' => $this->whenLoaded('address', fn () => [
                'id' => $this->address->id,
                'label' => $this->address->label,
                'street' => $this->address->street,
                'city' => $this->address->city,
            ]),
            'livreur' => $this->whenLoaded('livreur', fn () => [
                'id' => $this->livreur->id,
                'name' => $this->livreur->name,
                'email' => $this->livreur->email,
                'phone' => $this->livreur->phone,
            ]),
        ];
    }
}
