<?php

declare(strict_types=1);

namespace App\Http\Resources;

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

class InvoiceResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'number' => $this->number,
            'title' => $this->title,
            'project_id' => $this->project_id,
            'user_id' => $this->user_id,
            'type' => $this->type,
            'status' => $this->status,
            'total' => (int) $this->total,
            'late_fee_amount' => (int) ($this->late_fee_amount ?? 0),
            'payable_amount' => $this->payableAmount(),
            'commission_percent' => $this->commission_percent !== null ? (float) $this->commission_percent : null,
            'issued_at' => $this->issued_at?->toDateString(),
            'due_at' => $this->due_at?->toDateString(),
            'description' => $this->description,
            'admin_reason' => $this->admin_reason,
            'tracking_code' => $this->tracking_code,
            'payment_method' => $this->payment_method,
            'counterparty_name' => $this->counterparty_name,
            'counterparty_phone' => $this->counterparty_phone,
            'meta' => $this->meta,
            'created_by' => $this->created_by,
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'project' => new ProjectResource($this->whenLoaded('project')),
            'user' => new UserResource($this->whenLoaded('user')),
            'items' => InvoiceItemResource::collection($this->whenLoaded('items')),
        ];
    }
}
