<?php

namespace App\Http\Resources;

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

class PaymentSplitResource extends JsonResource
{
    public function toArray(Request $request): array
{
    $schedule = $this->payment?->schedule ?? $this->payment?->servicePackage?->items?->first()?->schedule;

    return [
        'id' => $this->id,
        'payment_id' => $this->payment_id,
        'provider_id' => $this->provider_id,
        'provider_name' => $this->provider?->user?->name,
        'provider_withdrawal_id' => $this->provider_withdrawal_id,

        'gateway_provider' => $this->gateway_provider,
        'gateway_transfer_target_reference' => $this->gateway_transfer_target_reference,
        'gateway_transfer_target_label' => $this->gateway_transfer_target_label,

        'status' => $this->status,

        'gross_amount' => $this->gross_amount,
        'gateway_fee_amount' => $this->gateway_fee_amount,
        'net_amount' => $this->net_amount,

        'transferred_at' => $this->transferred_at?->toISOString(),

        'metadata' => $this->metadata,

        'payment_status' => $this->payment?->status?->value,
        'payment_paid_at' => $this->payment?->paid_at?->toISOString(),

        'service_package_id' => $this->payment?->service_package_id,

        'schedule_ids' => $this->payment?->servicePackage?->items
            ?->pluck('schedule_id')
            ->values(),

        'schedule_date' => $schedule?->date?->format('d/m/Y'),
        'schedule_status' => $schedule?->status,
        'schedule_period_type' => $schedule?->period_type,
        'client_name' => $schedule?->client?->user?->name,

        'created_at' => $this->created_at?->toISOString(),
        'updated_at' => $this->updated_at?->toISOString(),
    ];
}

    public static function collection($resource): AnonymousResourceCollection
    {
        return parent::collection($resource);
    }
}
