<?php

namespace App\Http\Resources;

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

/** @mixin \App\Models\Invoice */
class InvoiceResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $clientName = null;
        if ($this->relationLoaded('client') && $this->client) {
            $clientName = $this->client->name;
        }

        return [
            'id' => $this->id,
            'invoiceNumber' => $this->invoice_number,
            'clientId' => $this->client_id,
            'date' => $this->date?->format('Y-m-d'),
            'dueDate' => $this->due_date?->format('Y-m-d'),
            'items' => $this->items ?? [],
            'subtotal' => (float) $this->subtotal,
            'tax' => (float) $this->tax,
            'total' => (float) $this->total,
            'status' => $this->status,
            'notes' => $this->notes,
            'createdAt' => $this->created_at?->toIso8601String(),
            'clientName' => $clientName,
        ];
    }
}
